<?php
/**
 * Base Schema Class for BW AI Schema Pro
 *
 * @package BW_AI_Schema_Pro
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

abstract class BW_Schema_Base {
	
	/**
	 * Generate schema markup
	 */
	abstract public function generate( $post, $type );
	
	/**
	 * Get common properties
	 */
	protected function get_common_properties( $post ) {
		$properties = array(
			'name' => get_the_title( $post ),
			'url' => get_permalink( $post ),
			'datePublished' => get_the_date( 'c', $post ),
			'dateModified' => get_the_modified_date( 'c', $post ),
		);
		
		// Add description
		if ( has_excerpt( $post ) ) {
			$properties['description'] = wp_strip_all_tags( get_the_excerpt( $post ) );
		} else {
			$properties['description'] = wp_trim_words( wp_strip_all_tags( $post->post_content ), 55 );
		}
		
		// Add featured image
		if ( has_post_thumbnail( $post ) ) {
			$image_id = get_post_thumbnail_id( $post );
			$image_url = wp_get_attachment_image_url( $image_id, 'full' );
			$image_meta = wp_get_attachment_metadata( $image_id );
			
			$properties['image'] = array(
				'@type' => 'ImageObject',
				'url' => $image_url,
				'width' => isset( $image_meta['width'] ) ? $image_meta['width'] : '',
				'height' => isset( $image_meta['height'] ) ? $image_meta['height'] : '',
			);
		}
		
		return $properties;
	}
	
	/**
	 * Get multiple authors properties
	 */
	protected function get_multiple_authors_properties( $post ) {
		$authors_schema = array();
		
		// Check for multiple authors
		$multiple_authors = get_post_meta( $post->ID, '_bw_schema_multiple_authors', true );
		
		if ( ! empty( $multiple_authors ) && is_array( $multiple_authors ) ) {
			// Use multiple authors system
			foreach ( $multiple_authors as $author_data ) {
				$author_schema = null;

				switch ( $author_data['type'] ) {
					// v2.0: Team Member Author
					case 'team_member':
						if ( ! empty( $author_data['team_member_id'] ) ) {
							$team_member = get_post( intval( $author_data['team_member_id'] ) );
							if ( $team_member && $team_member->post_status === 'publish' ) {
								$author_schema = $this->get_team_member_author_schema( $team_member );
							}
						}
						break;

					// v2.0: External Author (saved in settings)
					case 'external_saved':
						if ( ! empty( $author_data['external_author_id'] ) ) {
							$author_schema = $this->get_external_saved_author_schema( $author_data['external_author_id'] );
						}
						break;

					// Legacy: WordPress User
					case 'wordpress':
						if ( ! empty( $author_data['wordpress_user_id'] ) ) {
							$author_schema = $this->get_wordpress_author_schema( $author_data['wordpress_user_id'] );
						}
						break;

					// Legacy: Custom Author
					case 'custom':
						if ( ! empty( $author_data['custom_author_id'] ) ) {
							$author_schema = $this->get_custom_author_schema( $author_data['custom_author_id'] );
						}
						break;

					// External (One-time)
					case 'external':
						if ( ! empty( $author_data['external']['name'] ) ) {
							$author_schema = $this->get_external_author_schema( $author_data['external'] );
						}
						break;
				}

				if ( $author_schema ) {
					$authors_schema[] = $author_schema;
				}
			}
		} else {
			// Fall back to single author (legacy support)
			$single_author = $this->get_author_properties( $post->post_author, $post );
			if ( $single_author ) {
				$authors_schema[] = $single_author;
			}
		}
		
		return $authors_schema;
	}
	
	/**
	 * Get WordPress author schema
	 */
	protected function get_wordpress_author_schema( $user_id ) {
		$user = get_userdata( $user_id );
		if ( ! $user ) {
			return null;
		}

		// Check if this WP user has a linked team member
		$team_member = BW_Schema_Team_Member::get_team_member_by_user( $user_id );
		if ( $team_member ) {
			// Return a Person schema that references the team member's profile
			return $this->get_team_member_author_schema( $team_member );
		}

		// Fall back to standard WordPress user schema
		$author = array(
			'@type' => 'Person',
			'name' => $user->display_name,
		);

		if ( $user->user_url ) {
			$author['url'] = $user->user_url;
		}

		if ( $user->user_email ) {
			$author['email'] = $user->user_email;
		}

		// Get author bio
		$bio = get_the_author_meta( 'description', $user->ID );
		if ( $bio ) {
			$author['description'] = $bio;
		}

		// Get author avatar
		$avatar_url = get_avatar_url( $user->ID, array( 'size' => 512 ) );
		if ( $avatar_url ) {
			$author['image'] = $avatar_url;
		}

		return $author;
	}

	/**
	 * Get team member author schema
	 * Returns a Person schema that references the team member's profile page
	 */
	protected function get_team_member_author_schema( $team_member ) {
		// Get the full person schema data
		$person_data = BW_Schema_Team_Member::get_person_schema_data( $team_member );

		if ( empty( $person_data ) ) {
			return null;
		}

		// Build a compact author schema with @id reference
		$author = array(
			'@type' => 'Person',
			'@id'   => get_permalink( $team_member ) . '#person',
			'name'  => $person_data['name'],
			'url'   => $person_data['url'],
		);

		// Add key fields for rich author schema
		if ( ! empty( $person_data['image'] ) ) {
			$author['image'] = $person_data['image'];
		}

		if ( ! empty( $person_data['description'] ) ) {
			$author['description'] = $person_data['description'];
		}

		if ( ! empty( $person_data['jobTitle'] ) ) {
			$author['jobTitle'] = $person_data['jobTitle'];
		}

		if ( ! empty( $person_data['sameAs'] ) ) {
			$author['sameAs'] = $person_data['sameAs'];
		}

		return $author;
	}
	
	/**
	 * Get custom author schema
	 */
	protected function get_custom_author_schema( $custom_author_id ) {
		$custom_authors = get_option( 'bw_schema_custom_authors', array() );
		
		foreach ( $custom_authors as $custom_author ) {
			if ( $custom_author['id'] == $custom_author_id ) {
				return $this->build_author_schema_from_custom( $custom_author );
			}
		}
		
		return null;
	}
	
	/**
	 * Get external author schema
	 */
	protected function get_external_author_schema( $external_data ) {
		$author = array(
			'@type' => 'Person',
			'name' => $external_data['name'],
		);
		
		if ( ! empty( $external_data['job_title'] ) ) {
			$author['jobTitle'] = $external_data['job_title'];
		}
		
		if ( ! empty( $external_data['bio'] ) ) {
			$author['description'] = $external_data['bio'];
		}
		
		if ( ! empty( $external_data['image'] ) ) {
			$author['image'] = $external_data['image'];
		}
		
		if ( ! empty( $external_data['email'] ) ) {
			$author['email'] = $external_data['email'];
		}
		
		if ( ! empty( $external_data['website'] ) ) {
			$author['url'] = $external_data['website'];
		}
		
		// Social profiles
		$same_as = array();
		if ( ! empty( $external_data['linkedin'] ) ) {
			$same_as[] = $external_data['linkedin'];
		}
		if ( ! empty( $external_data['twitter'] ) ) {
			$same_as[] = $external_data['twitter'];
		}
		
		if ( ! empty( $same_as ) ) {
			$author['sameAs'] = count( $same_as ) === 1 ? $same_as[0] : $same_as;
		}
		
		// Expertise
		if ( ! empty( $external_data['expertise'] ) ) {
			$expertise = array_map( 'trim', explode( ',', $external_data['expertise'] ) );
			if ( ! empty( $expertise ) ) {
				$author['knowsAbout'] = $expertise;
			}
		}
		
		return $author;
	}

	/**
	 * Get external saved author schema (v2.0)
	 *
	 * Retrieves author data from the bw_schema_external_authors option
	 * and builds a Person schema.
	 */
	protected function get_external_saved_author_schema( $author_id ) {
		$external_authors = get_option( 'bw_schema_external_authors', array() );

		if ( ! isset( $external_authors[ $author_id ] ) ) {
			return null;
		}

		$ext = $external_authors[ $author_id ];

		$author = array(
			'@type' => 'Person',
			'name'  => $ext['name'] ?? '',
		);

		if ( ! empty( $ext['jobTitle'] ) ) {
			$author['jobTitle'] = $ext['jobTitle'];
		}

		if ( ! empty( $ext['description'] ) ) {
			$author['description'] = $ext['description'];
		}

		if ( ! empty( $ext['image'] ) ) {
			$author['image'] = $ext['image'];
		}

		if ( ! empty( $ext['website'] ) ) {
			$author['url'] = $ext['website'];
		}

		// Credentials
		if ( ! empty( $ext['credentials'] ) ) {
			$author['honorificSuffix'] = $ext['credentials'];
		}

		// Social profiles
		$same_as = array();
		if ( ! empty( $ext['social']['linkedin'] ) ) {
			$same_as[] = $ext['social']['linkedin'];
		}
		if ( ! empty( $ext['social']['twitter'] ) ) {
			$same_as[] = $ext['social']['twitter'];
		}

		if ( ! empty( $same_as ) ) {
			$author['sameAs'] = count( $same_as ) === 1 ? $same_as[0] : $same_as;
		}

		return $author;
	}

	/**
	 * Build author schema from custom author data
	 */
	protected function build_author_schema_from_custom( $custom_author ) {
		$author = array(
			'@type' => 'Person',
			'name' => $custom_author['name'],
		);
		
		if ( ! empty( $custom_author['jobTitle'] ) ) {
			$author['jobTitle'] = $custom_author['jobTitle'];
		}
		
		if ( ! empty( $custom_author['description'] ) ) {
			$author['description'] = $custom_author['description'];
		}
		
		if ( ! empty( $custom_author['image'] ) ) {
			$author['image'] = $custom_author['image'];
		}
		
		// Add URL (team page URL if external, team page ID if internal, otherwise website)
		if ( ! empty( $custom_author['teamPageUrl'] ) ) {
			$author['url'] = $custom_author['teamPageUrl'];
		} elseif ( ! empty( $custom_author['teamPageId'] ) && $custom_author['teamPageId'] !== 'custom' ) {
			$team_page_url = get_permalink( $custom_author['teamPageId'] );
			if ( $team_page_url ) {
				$author['url'] = $team_page_url;
			}
		} elseif ( ! empty( $custom_author['social']['website'] ) ) {
			$author['url'] = $custom_author['social']['website'];
		}
		
		if ( ! empty( $custom_author['email'] ) ) {
			$author['email'] = $custom_author['email'];
		}
		
		// Add social profiles
		$social_profiles = array();
		if ( ! empty( $custom_author['social'] ) ) {
			foreach ( $custom_author['social'] as $platform => $url ) {
				if ( ! empty( $url ) ) {
					$social_profiles[] = $url;
				}
			}
		}
		if ( ! empty( $social_profiles ) ) {
			$author['sameAs'] = $social_profiles;
		}
		
		// Add credentials if available
		if ( ! empty( $custom_author['credentials'] ) ) {
			$author['hasCredential'] = array(
				array(
					'@type' => 'EducationalOccupationalCredential',
					'name' => $custom_author['credentials'],
				)
			);
		}
		
		// Add expertise (knowsAbout)
		if ( ! empty( $custom_author['expertise'] ) ) {
			$expertise = array_map( 'trim', explode( ',', $custom_author['expertise'] ) );
			$author['knowsAbout'] = array_filter( $expertise );
		}
		
		// Add professional affiliations
		if ( ! empty( $custom_author['affiliations'] ) ) {
			$affiliations = array_map( 'trim', explode( ',', $custom_author['affiliations'] ) );
			$affiliation_list = array();
			foreach ( $affiliations as $affiliation ) {
				if ( ! empty( $affiliation ) ) {
					$affiliation_list[] = array(
						'@type' => 'Organization',
						'name' => $affiliation
					);
				}
			}
			if ( ! empty( $affiliation_list ) ) {
				$author['affiliation'] = $affiliation_list;
			}
		}
		
		// Add alumni of
		if ( ! empty( $custom_author['alumniOf'] ) ) {
			$alumni = array_map( 'trim', explode( ',', $custom_author['alumniOf'] ) );
			$alumni_list = array();
			foreach ( $alumni as $school ) {
				if ( ! empty( $school ) ) {
					$alumni_list[] = array(
						'@type' => 'EducationalOrganization',
						'name' => $school
					);
				}
			}
			if ( ! empty( $alumni_list ) ) {
				$author['alumniOf'] = $alumni_list;
			}
		}
		
		return $author;
	}
	
	/**
	 * Get author properties
	 */
	protected function get_author_properties( $author_id, $post = null ) {
		// Check if using custom authors and if there's a custom author selected for this post
		if ( $post && get_option( 'bw_schema_use_custom_authors', 'no' ) === 'yes' ) {
			$custom_author_id = get_post_meta( $post->ID, '_bw_schema_custom_author', true );
			
			if ( ! empty( $custom_author_id ) ) {
				// Get custom author data
				$custom_authors = get_option( 'bw_schema_custom_authors', array() );
				foreach ( $custom_authors as $custom_author ) {
					if ( $custom_author['id'] == $custom_author_id ) {
						$author = array(
							'@type' => 'Person',
							'name' => $custom_author['name'],
						);
						
						if ( ! empty( $custom_author['jobTitle'] ) ) {
							$author['jobTitle'] = $custom_author['jobTitle'];
						}
						
						if ( ! empty( $custom_author['description'] ) ) {
							$author['description'] = $custom_author['description'];
						}
						
						if ( ! empty( $custom_author['image'] ) ) {
							$author['image'] = $custom_author['image'];
						}
						
						// Add URL (team page URL if external, team page ID if internal, otherwise website)
						if ( ! empty( $custom_author['teamPageUrl'] ) ) {
							// External URL
							$author['url'] = $custom_author['teamPageUrl'];
						} elseif ( ! empty( $custom_author['teamPageId'] ) && $custom_author['teamPageId'] !== 'custom' ) {
							// Internal page/post
							$team_page_url = get_permalink( $custom_author['teamPageId'] );
							if ( $team_page_url ) {
								$author['url'] = $team_page_url;
							}
						} elseif ( ! empty( $custom_author['social']['website'] ) ) {
							// Fallback to website
							$author['url'] = $custom_author['social']['website'];
						}
						
						// Add email
						if ( ! empty( $custom_author['email'] ) ) {
							$author['email'] = $custom_author['email'];
						}
						
						// Add social profiles
						$social_profiles = array();
						if ( ! empty( $custom_author['social'] ) ) {
							foreach ( $custom_author['social'] as $platform => $url ) {
								if ( ! empty( $url ) ) {
									$social_profiles[] = $url;
								}
							}
						}
						if ( ! empty( $social_profiles ) ) {
							$author['sameAs'] = $social_profiles;
						}
						
						// Add credentials if available
						if ( ! empty( $custom_author['credentials'] ) ) {
							$author['hasCredential'] = array(
								array(
									'@type' => 'EducationalOccupationalCredential',
									'name' => $custom_author['credentials'],
								)
							);
						}
						
						// Add expertise (knowsAbout)
						if ( ! empty( $custom_author['expertise'] ) ) {
							$expertise = array_map( 'trim', explode( ',', $custom_author['expertise'] ) );
							$author['knowsAbout'] = array_filter( $expertise );
						}
						
						// Add professional affiliations
						if ( ! empty( $custom_author['affiliations'] ) ) {
							$affiliations = array_map( 'trim', explode( ',', $custom_author['affiliations'] ) );
							$affiliation_list = array();
							foreach ( $affiliations as $affiliation ) {
								if ( ! empty( $affiliation ) ) {
									$affiliation_list[] = array(
										'@type' => 'Organization',
										'name' => $affiliation
									);
								}
							}
							if ( ! empty( $affiliation_list ) ) {
								$author['affiliation'] = $affiliation_list;
							}
						}
						
						// Add alumni of
						if ( ! empty( $custom_author['alumniOf'] ) ) {
							$alumni = array_map( 'trim', explode( ',', $custom_author['alumniOf'] ) );
							$alumni_list = array();
							foreach ( $alumni as $school ) {
								if ( ! empty( $school ) ) {
									$alumni_list[] = array(
										'@type' => 'EducationalOrganization',
										'name' => $school
									);
								}
							}
							if ( ! empty( $alumni_list ) ) {
								$author['alumniOf'] = $alumni_list;
							}
						}
						
						// Add organization affiliation
						$author['worksFor'] = $this->get_organization_properties();
						
						return apply_filters( 'bw_schema_custom_author_properties', $author, $custom_author_id );
					}
				}
			}
		}
		
		// Check if this WP user has a linked team member
		$team_member = BW_Schema_Team_Member::get_team_member_by_user( $author_id );
		if ( $team_member ) {
			// Return a Person schema that references the team member's profile
			$author = $this->get_team_member_author_schema( $team_member );
			if ( $author ) {
				return apply_filters( 'bw_schema_author_properties', $author, $author_id );
			}
		}

		// Fall back to WordPress user author
		$author_data = BW_Schema_Core::get_author_schema( $author_id );

		$author = array(
			'@type' => 'Person',
			'name' => $author_data['name'],
			'url' => $author_data['url'],
		);

		// Add image
		if ( ! empty( $author_data['image'] ) ) {
			$author['image'] = $author_data['image'];
		}

		// Add description/bio
		if ( ! empty( $author_data['description'] ) ) {
			$author['description'] = $author_data['description'];
		}

		// Add same as (social profiles)
		if ( ! empty( $author_data['sameAs'] ) && is_array( $author_data['sameAs'] ) ) {
			$author['sameAs'] = array_filter( $author_data['sameAs'] );
		}

		// Add expertise (AI-optimized)
		if ( ! empty( $author_data['knowsAbout'] ) && is_array( $author_data['knowsAbout'] ) ) {
			$author['knowsAbout'] = array_filter( $author_data['knowsAbout'] );
		}

		// Add credentials (AI-optimized)
		if ( ! empty( $author_data['hasCredential'] ) && is_array( $author_data['hasCredential'] ) ) {
			$credentials = array();
			foreach ( $author_data['hasCredential'] as $credential ) {
				$credentials[] = array(
					'@type' => 'EducationalOccupationalCredential',
					'name' => $credential,
				);
			}
			$author['hasCredential'] = $credentials;
		}

		return apply_filters( 'bw_schema_author_properties', $author, $author_id );
	}
	
	/**
	 * Get organization properties
	 */
	protected function get_organization_properties() {
		$org_data = BW_Schema_Core::get_organization_schema();
		
		$org = array(
			'@type' => 'Organization',
			'name' => $org_data['name'],
			'url' => $org_data['url'],
		);
		
		// Add logo
		if ( ! empty( $org_data['logo'] ) ) {
			$org['logo'] = array(
				'@type' => 'ImageObject',
				'url' => $org_data['logo'],
			);
		}
		
		// Add same as
		if ( ! empty( $org_data['sameAs'] ) && is_array( $org_data['sameAs'] ) ) {
			$org['sameAs'] = array_filter( $org_data['sameAs'] );
		}
		
		return apply_filters( 'bw_schema_organization_properties', $org );
	}
	
	/**
	 * Add AI-optimized properties
	 */
	protected function add_ai_properties( $schema, $post ) {
		// Add keywords
		$tags = wp_get_post_tags( $post->ID );
		if ( ! empty( $tags ) ) {
			$keywords = array();
			foreach ( $tags as $tag ) {
				$keywords[] = $tag->name;
			}
			$schema['keywords'] = implode( ', ', $keywords );
		}
		
		// Add about (main entities)
		$about_entities = get_post_meta( $post->ID, '_bw_schema_about_entities', true );
		if ( ! empty( $about_entities ) && is_array( $about_entities ) ) {
			$about = array();
			foreach ( $about_entities as $entity ) {
				$about[] = array(
					'@type' => 'Thing',
					'name' => $entity,
				);
			}
			$schema['about'] = $about;
		}
		
		// Add mentions
		$mentions = get_post_meta( $post->ID, '_bw_schema_mentions', true );
		if ( ! empty( $mentions ) && is_array( $mentions ) ) {
			$mention_array = array();
			foreach ( $mentions as $mention ) {
				$mention_array[] = array(
					'@type' => 'Thing',
					'name' => $mention,
				);
			}
			$schema['mentions'] = $mention_array;
		}
		
		// Add fact checking info
		$fact_checked_by = get_post_meta( $post->ID, '_bw_schema_fact_checked_by', true );
		if ( ! empty( $fact_checked_by ) ) {
			$schema['reviewedBy'] = array(
				'@type' => 'Person',
				'name' => $fact_checked_by,
			);
		}
		
		$last_reviewed = get_post_meta( $post->ID, '_bw_schema_last_reviewed', true );
		if ( ! empty( $last_reviewed ) ) {
			$schema['lastReviewed'] = $last_reviewed;
		}
		
		return apply_filters( 'bw_schema_ai_properties', $schema, $post );
	}
	
	/**
	 * Get breadcrumb list
	 */
	protected function get_breadcrumb_list( $post ) {
		$items = array();
		$position = 1;
		
		// Check if we're on the homepage
		$is_homepage = ( get_permalink( $post ) === home_url( '/' ) );
		
		// Don't add home item if we're already on the homepage
		if ( ! $is_homepage ) {
			// Home
			$items[] = array(
				'@type' => 'ListItem',
				'position' => $position++,
				'name' => get_bloginfo( 'name' ),
				'item' => array(
					'@type' => 'Thing',
					'@id' => home_url( '/' ),
				),
			);
			
			// Categories
			if ( get_post_type( $post ) === 'post' ) {
				$categories = get_the_category( $post->ID );
				if ( ! empty( $categories ) ) {
					$category = $categories[0];
					$items[] = array(
						'@type' => 'ListItem',
						'position' => $position++,
						'name' => $category->name,
						'item' => array(
							'@type' => 'Thing',
							'@id' => get_category_link( $category->term_id ),
						),
					);
				}
			}
		}
		
		// Current post/page
		$items[] = array(
			'@type' => 'ListItem',
			'position' => $position++,
			'name' => get_the_title( $post ),
			'item' => array(
				'@type' => 'Thing',
				'@id' => get_permalink( $post ),
			),
		);
		
		return array(
			'@type' => 'BreadcrumbList',
			'itemListElement' => $items,
		);
	}
}