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

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

class BW_Schema_Person extends BW_Schema_Base {
	
	/**
	 * Generate person schema
	 */
	public function generate( $post, $type = 'Person' ) {
		// Base schema
		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => $type,
		);
		
		// Add common properties
		$schema['name'] = get_the_title( $post );
		$schema['url'] = get_permalink( $post );
		
		// Add description - check multiple sources
		$description = '';
		
		// First check for excerpt
		if ( has_excerpt( $post ) ) {
			$description = wp_strip_all_tags( get_the_excerpt( $post ) );
		}
		
		// Check for team member bio fields
		if ( empty( $description ) ) {
			// Check various possible bio field names
			$bio_fields = array(
				'leadership_bio',
				'_sw_teammember_bio',
				'bio',
				'biography',
				'description',
				'team_member_bio',
				'member_bio',
				'staff_bio',
				'employee_bio',
				'person_bio',
				'profile_bio',
				'about',
				'about_text',
				'about_content'
			);
			
			foreach ( $bio_fields as $field ) {
				$description = get_post_meta( $post->ID, $field, true );
				if ( ! empty( $description ) ) {
					break;
				}
			}
			
			// Also check ACF fields if available
			if ( empty( $description ) && function_exists( 'get_field' ) ) {
				foreach ( $bio_fields as $field ) {
					$description = get_field( $field, $post->ID );
					if ( ! empty( $description ) ) {
						break;
					}
				}
			}
		}
		
		// Fall back to post content
		if ( empty( $description ) && ! empty( $post->post_content ) ) {
			$content = wp_strip_all_tags( $post->post_content );
			if ( ! empty( trim( $content ) ) ) {
				$description = wp_trim_words( $content, 50 );
			}
		}
		
		// Add description to schema if we found one
		if ( ! empty( trim( $description ) ) ) {
			$schema['description'] = trim( wp_strip_all_tags( $description ) );
		}
		
		// Add featured image as person image
		if ( has_post_thumbnail( $post ) ) {
			$schema['image'] = get_the_post_thumbnail_url( $post, 'full' );
		}
		
		// Add job title - check multiple possible meta keys
		$job_title = get_post_meta( $post->ID, '_bw_schema_job_title', true );
		if ( empty( $job_title ) ) {
			// Check for team member specific fields
			$job_title = get_post_meta( $post->ID, 'job_title', true );
			if ( empty( $job_title ) ) {
				$job_title = get_post_meta( $post->ID, 'position', true );
			}
			if ( empty( $job_title ) ) {
				$job_title = get_post_meta( $post->ID, 'role', true );
			}
			if ( empty( $job_title ) ) {
				$job_title = get_post_meta( $post->ID, '_sw_teammember_position', true );
			}
		}
		if ( empty( $job_title ) && function_exists( 'get_field' ) ) {
			// Check ACF fields
			$job_title = get_field( 'job_title', $post->ID );
			if ( empty( $job_title ) ) {
				$job_title = get_field( 'position', $post->ID );
			}
			if ( empty( $job_title ) ) {
				$job_title = get_field( 'role', $post->ID );
			}
		}
		if ( ! empty( $job_title ) ) {
			$schema['jobTitle'] = $job_title;
		}
		
		// Add organization
		$organization = get_post_meta( $post->ID, '_bw_schema_works_for', true );
		if ( empty( $organization ) ) {
			// For team members, use the site organization
			$org_data = BW_Schema_Core::get_organization_schema();
			if ( ! empty( $org_data['name'] ) ) {
				$organization = $org_data['name'];
			}
		}
		
		if ( ! empty( $organization ) ) {
			// Get full organization data if this is a team member
			if ( get_post_type( $post ) === 'sw_teammember' ) {
				$org_data = BW_Schema_Core::get_organization_schema();
				$schema['worksFor'] = array(
					'@type' => 'Organization',
					'name' => $org_data['name'],
					'url' => home_url( '/' )
				);
				if ( ! empty( $org_data['logo'] ) ) {
					$schema['worksFor']['logo'] = $org_data['logo'];
				}
			} else {
				$schema['worksFor'] = array(
					'@type' => 'Organization',
					'name' => $organization,
				);
			}
		}
		
		// Add contact info
		$email = get_post_meta( $post->ID, '_bw_schema_email', true );
		if ( empty( $email ) ) {
			// Check common team member email fields
			$email = get_post_meta( $post->ID, 'email', true );
			if ( empty( $email ) ) {
				$email = get_post_meta( $post->ID, '_sw_teammember_email', true );
			}
			if ( empty( $email ) ) {
				$email = get_post_meta( $post->ID, 'contact_email', true );
			}
			if ( empty( $email ) && function_exists( 'get_field' ) ) {
				$email = get_field( 'email', $post->ID );
			}
		}
		if ( ! empty( $email ) && is_email( $email ) ) {
			$schema['email'] = $email;
		}
		
		$telephone = get_post_meta( $post->ID, '_bw_schema_telephone', true );
		if ( empty( $telephone ) ) {
			// Check common team member phone fields
			$telephone = get_post_meta( $post->ID, 'phone', true );
			if ( empty( $telephone ) ) {
				$telephone = get_post_meta( $post->ID, '_sw_teammember_phone', true );
			}
			if ( empty( $telephone ) ) {
				$telephone = get_post_meta( $post->ID, 'telephone', true );
			}
			if ( empty( $telephone ) ) {
				$telephone = get_post_meta( $post->ID, 'contact_phone', true );
			}
			if ( empty( $telephone ) && function_exists( 'get_field' ) ) {
				$telephone = get_field( 'phone', $post->ID );
			}
		}
		if ( ! empty( $telephone ) ) {
			$schema['telephone'] = $telephone;
		}
		
		// Add social profiles (sameAs)
		$social_profiles = get_post_meta( $post->ID, '_bw_schema_social_profiles', true );
		if ( empty( $social_profiles ) ) {
			// Check for team member specific social fields
			$social_profiles = array();
			
			// LinkedIn
			$linkedin = get_post_meta( $post->ID, '_sw_teammember_linkedin', true );
			if ( empty( $linkedin ) ) {
				$linkedin = get_post_meta( $post->ID, 'linkedin_url', true );
			}
			if ( ! empty( $linkedin ) ) {
				$social_profiles[] = $linkedin;
			}
			
			// Twitter
			$twitter = get_post_meta( $post->ID, '_sw_teammember_twitter', true );
			if ( empty( $twitter ) ) {
				$twitter = get_post_meta( $post->ID, 'twitter_url', true );
			}
			if ( ! empty( $twitter ) ) {
				$social_profiles[] = $twitter;
			}
			
			// Facebook
			$facebook = get_post_meta( $post->ID, '_sw_teammember_facebook', true );
			if ( empty( $facebook ) ) {
				$facebook = get_post_meta( $post->ID, 'facebook_url', true );
			}
			if ( ! empty( $facebook ) ) {
				$social_profiles[] = $facebook;
			}
			
			// Instagram
			$instagram = get_post_meta( $post->ID, '_sw_teammember_instagram', true );
			if ( empty( $instagram ) ) {
				$instagram = get_post_meta( $post->ID, 'instagram_url', true );
			}
			if ( ! empty( $instagram ) ) {
				$social_profiles[] = $instagram;
			}
			
			// Website
			$website = get_post_meta( $post->ID, '_sw_teammember_website', true );
			if ( empty( $website ) ) {
				$website = get_post_meta( $post->ID, 'website_url', true );
			}
			if ( empty( $website ) ) {
				$website = get_post_meta( $post->ID, 'personal_website', true );
			}
			if ( ! empty( $website ) ) {
				$social_profiles[] = $website;
			}
			
			// YouTube
			$youtube = get_post_meta( $post->ID, '_sw_teammember_youtube', true );
			if ( empty( $youtube ) ) {
				$youtube = get_post_meta( $post->ID, 'youtube_url', true );
			}
			if ( ! empty( $youtube ) ) {
				$social_profiles[] = $youtube;
			}
		}
		
		if ( ! empty( $social_profiles ) && is_array( $social_profiles ) ) {
			$schema['sameAs'] = array_values( array_filter( $social_profiles ) );
		}
		
		// Add department/affiliation if available
		$department = get_post_meta( $post->ID, 'department', true );
		if ( empty( $department ) ) {
			$department = get_post_meta( $post->ID, '_sw_teammember_department', true );
		}
		if ( empty( $department ) && function_exists( 'get_field' ) ) {
			$department = get_field( 'department', $post->ID );
		}
		if ( ! empty( $department ) && ! empty( $schema['worksFor'] ) ) {
			// Add department to the organization affiliation
			$schema['affiliation'] = array(
				'@type' => 'Organization',
				'name' => $department,
				'parentOrganization' => $schema['worksFor']
			);
		}
		
		// Add expertise (knowsAbout) - AI optimized
		$expertise = get_post_meta( $post->ID, '_bw_schema_expertise', true );
		if ( ! empty( $expertise ) ) {
			if ( is_string( $expertise ) ) {
				// Handle comma-separated string
				$expertise_array = array_map( 'trim', explode( ',', $expertise ) );
				$schema['knowsAbout'] = array_values( array_filter( $expertise_array ) );
			} elseif ( is_array( $expertise ) ) {
				// Ensure it's a properly indexed array
				$schema['knowsAbout'] = array_values( array_filter( $expertise ) );
			}
		}
		
		// Also check for common expertise/skills fields
		if ( empty( $schema['knowsAbout'] ) ) {
			$skills = get_post_meta( $post->ID, 'skills', true );
			if ( empty( $skills ) ) {
				$skills = get_post_meta( $post->ID, '_sw_teammember_skills', true );
			}
			if ( empty( $skills ) && function_exists( 'get_field' ) ) {
				$skills = get_field( 'skills', $post->ID );
			}
			if ( ! empty( $skills ) ) {
				if ( is_string( $skills ) ) {
					$schema['knowsAbout'] = array_values( array_filter( array_map( 'trim', explode( ',', $skills ) ) ) );
				} elseif ( is_array( $skills ) ) {
					$schema['knowsAbout'] = array_values( array_filter( $skills ) );
				}
			}
		}
		
		// Add education (alumniOf)
		$education = get_post_meta( $post->ID, '_bw_schema_education', true );
		if ( ! empty( $education ) && is_array( $education ) ) {
			$alumni = array();
			foreach ( $education as $edu ) {
				if ( ! empty( $edu['name'] ) ) {
					$alumni[] = array(
						'@type' => 'EducationalOrganization',
						'name' => $edu['name'],
					);
				}
			}
			if ( ! empty( $alumni ) ) {
				$schema['alumniOf'] = $alumni;
			}
		}
		
		// Add credentials (hasCredential) - AI optimized
		$credentials = get_post_meta( $post->ID, '_bw_schema_credentials', true );
		if ( ! empty( $credentials ) ) {
			$creds = array();
			
			// Handle both string and array formats
			if ( is_string( $credentials ) ) {
				// If it's a string, treat it as a single credential or comma-separated list
				$credential_list = array_map( 'trim', explode( ',', $credentials ) );
				foreach ( $credential_list as $cred_name ) {
					if ( ! empty( $cred_name ) ) {
						$creds[] = array(
							'@type' => 'EducationalOccupationalCredential',
							'name' => $cred_name,
						);
					}
				}
			} elseif ( is_array( $credentials ) ) {
				// Handle array format
				foreach ( $credentials as $credential ) {
					if ( is_string( $credential ) && ! empty( $credential ) ) {
						// Simple string in array
						$creds[] = array(
							'@type' => 'EducationalOccupationalCredential',
							'name' => $credential,
						);
					} elseif ( is_array( $credential ) && ! empty( $credential['name'] ) ) {
						// Structured credential data
						$cred = array(
							'@type' => 'EducationalOccupationalCredential',
							'name' => $credential['name'],
						);
						if ( ! empty( $credential['category'] ) ) {
							$cred['credentialCategory'] = $credential['category'];
						}
						$creds[] = $cred;
					}
				}
			}
			
			if ( ! empty( $creds ) ) {
				$schema['hasCredential'] = $creds;
			}
		}
		
		// Add awards
		$awards = get_post_meta( $post->ID, '_bw_schema_awards', true );
		if ( ! empty( $awards ) && is_array( $awards ) ) {
			$schema['award'] = array_filter( $awards );
		}
		
		// Add memberships (memberOf)
		$memberships = get_post_meta( $post->ID, '_bw_schema_memberships', true );
		if ( ! empty( $memberships ) && is_array( $memberships ) ) {
			$members = array();
			foreach ( $memberships as $membership ) {
				if ( ! empty( $membership ) ) {
					$members[] = array(
						'@type' => 'Organization',
						'name' => $membership,
					);
				}
			}
			if ( ! empty( $members ) ) {
				$schema['memberOf'] = $members;
			}
		}
		
		// Add publishing principles (for authors)
		if ( $type === 'Author' || $type === 'Expert' ) {
			$principles = get_post_meta( $post->ID, '_bw_schema_publishing_principles', true );
			if ( ! empty( $principles ) ) {
				$schema['publishingPrinciples'] = $principles;
			}
			
			// Add author-specific properties
			$schema = $this->add_author_properties( $schema, $post );
		}
		
		// Add expert-specific properties
		if ( $type === 'Expert' ) {
			$schema = $this->add_expert_properties( $schema, $post );
		}
		
		// Add AI-optimized properties
		$schema = $this->add_ai_properties( $schema, $post );
		
		return apply_filters( 'bw_schema_person', $schema, $post, $type );
	}
	
	/**
	 * Add author-specific properties
	 */
	private function add_author_properties( $schema, $post ) {
		// Add written works
		$args = array(
			'author' => $post->post_author,
			'post_type' => 'post',
			'posts_per_page' => 5,
			'orderby' => 'date',
			'order' => 'DESC',
		);
		
		$author_posts = get_posts( $args );
		if ( ! empty( $author_posts ) ) {
			$works = array();
			foreach ( $author_posts as $author_post ) {
				$works[] = array(
					'@type' => 'Article',
					'name' => get_the_title( $author_post ),
					'url' => get_permalink( $author_post ),
				);
			}
			$schema['workExample'] = $works;
		}
		
		return $schema;
	}
	
	/**
	 * Add expert-specific properties
	 */
	private function add_expert_properties( $schema, $post ) {
		// Add expertise validation
		$validation = get_post_meta( $post->ID, '_bw_schema_expertise_validation', true );
		if ( ! empty( $validation ) ) {
			$schema['expertiseValidation'] = $validation;
		}
		
		// Add years of experience
		$experience = get_post_meta( $post->ID, '_bw_schema_years_experience', true );
		if ( ! empty( $experience ) ) {
			$schema['yearsOfExperience'] = intval( $experience );
		}
		
		// Add specializations
		$specializations = get_post_meta( $post->ID, '_bw_schema_specializations', true );
		if ( ! empty( $specializations ) && is_array( $specializations ) ) {
			$schema['hasOccupation'] = array(
				'@type' => 'Occupation',
				'name' => $schema['jobTitle'] ?? '',
				'specialization' => array_filter( $specializations ),
			);
		}
		
		return $schema;
	}
}