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

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

class BW_Schema_Renderer {
	
	/**
	 * Render schema markup
	 */
	public function render() {
		// Check if schema is enabled
		if ( get_option( 'bw_schema_enable_schema', 'yes' ) !== 'yes' ) {
			return;
		}

		// Check for custom schema override on singular posts
		// If custom schema exists, output ONLY that and skip all plugin-generated schemas
		if ( is_singular() ) {
			global $post;
			$custom_schema = get_post_meta( $post->ID, '_bw_schema_custom', true );
			if ( ! empty( $custom_schema ) ) {
				// Validate it's proper JSON before outputting
				$decoded = json_decode( $custom_schema, true );
				if ( json_last_error() === JSON_ERROR_NONE ) {
					echo "\n<!-- BW AI Schema Pro - Custom Schema Override -->\n";
					echo '<script type="application/ld+json">' . "\n";
					// Output the original JSON string directly (preserves @graph and all formatting)
					// Re-encode to ensure proper formatting but from the decoded array
					echo json_encode( $decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . "\n";
					echo '</script>' . "\n";
					echo "<!-- / BW AI Schema Pro -->\n\n";
					return; // Skip all other schema generation
				}
			}
		}

		// Get current context
		$schemas = $this->get_context_schemas();

		if ( ! empty( $schemas ) ) {
			echo "\n<!-- BW AI Schema Pro - Structured Data for AI Era -->\n";

			foreach ( $schemas as $schema ) {
				if ( $schema ) {
					// Ensure @ symbols are preserved
					$json = json_encode( $schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
					// Fix any potential issues with @ symbols being stripped
					$json = str_replace( '"context":', '"@context":', $json );
					$json = str_replace( '"type":', '"@type":', $json );
					$json = str_replace( '"id":', '"@id":', $json );
					
					echo '<script type="application/ld+json">' . "\n";
					echo $json . "\n";
					echo '</script>' . "\n";
				}
			}
			
			echo "<!-- / BW AI Schema Pro -->\n\n";
		} else {
			echo "\n<!-- BW AI Schema Pro - No schemas generated -->\n";
		}
	}
	
	/**
	 * Get schemas for current context
	 */
	private function get_context_schemas() {
		$schemas = array();
		
		// Check if we're outputting Organization schema on homepage
		$output_org_on_homepage = get_option( 'bw_schema_output_org_homepage', 'no' );
		$is_homepage = is_front_page() || is_home();
		
		// Check if this is a team page
		$is_team_page = $this->is_team_page();

		// Check if this is a team member profile page
		$team_post_type = BW_Schema_Team_Member::get_team_post_type();
		$is_team_member_page = $team_post_type && is_singular( $team_post_type );

		// Add organization/website schema except on team member pages and team list pages
		if ( ! $is_team_member_page && ! $is_team_page ) {
			$schemas[] = $this->get_website_schema();
		}
		
		// Add breadcrumb schema if enabled
		if ( get_option( 'bw_schema_enable_breadcrumbs', 'yes' ) === 'yes' ) {
			$breadcrumb = $this->get_breadcrumb_schema();
			if ( $breadcrumb ) {
				$schemas[] = $breadcrumb;
			}
		}
		
		// If on homepage and outputting Organization schema, skip post-specific schema
		if ( $is_homepage && $output_org_on_homepage === 'yes' ) {
			// Skip adding any other schemas for homepage
			$schemas = array_filter( $schemas );
			return apply_filters( 'bw_schema_rendered_schemas', $schemas );
		}
		
		// Context-specific schemas
		// Check team pages first
		if ( $is_team_page ) {
			$team_schema = $this->get_team_page_schema();
			if ( $team_schema ) {
				$schemas[] = $team_schema;
			}
		} elseif ( is_singular() ) {
			global $post;

			// Check if schema is disabled for this post
			if ( get_post_meta( $post->ID, '_bw_schema_disable', true ) === 'yes' ) {
				return $schemas;
			}

			// Check if this is a team member post - use ProfilePage + Person schema
			$team_post_type = BW_Schema_Team_Member::get_team_post_type();
			if ( $team_post_type && $post->post_type === $team_post_type ) {
				$team_member_schema = $this->get_team_member_profile_schema( $post );
				if ( $team_member_schema ) {
					$schemas[] = $team_member_schema;
				}
			} else {
				// Get post-specific schema for other post types
				$post_schema = $this->get_post_schema( $post );
				if ( $post_schema ) {
					$schemas[] = $post_schema;
				}
			}

		} elseif ( is_author() ) {
			$author_schema = $this->get_author_page_schema();
			if ( $author_schema ) {
				$schemas[] = $author_schema;
			}
			
		} elseif ( is_archive() || is_home() ) {
			$archive_schema = $this->get_archive_schema();
			if ( $archive_schema ) {
				$schemas[] = $archive_schema;
			}
		}
		
		// Filter out null or empty schemas
		$schemas = array_filter( $schemas );
		
		return apply_filters( 'bw_schema_rendered_schemas', $schemas );
	}
	
	/**
	 * Check if current page is a team page
	 */
	private function is_team_page() {
		$team_post_type = BW_Schema_Team_Member::get_team_post_type();
		
		
		// Check various conditions for team page
		if ( is_post_type_archive( $team_post_type ) ) {
			return true;
		}
		
		if ( is_page() ) {
			global $post;
			// Check manual designation
			if ( $post && get_post_meta( $post->ID, '_bw_schema_is_team_page', true ) === 'yes' ) {
				return true;
			}
			// Check URL patterns
			if ( strpos( get_permalink(), '/team' ) !== false || strpos( get_permalink(), '/about/team' ) !== false ) {
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * Get website/organization schema
	 */
	private function get_website_schema() {
		// Check if we're on the homepage and should output Organization schema instead
		$output_org_on_homepage = get_option( 'bw_schema_output_org_homepage', 'no' );
		$is_homepage = is_front_page() || is_home();
		
		// Check for custom organization schema override first
		$custom_schema = get_option( 'bw_schema_organization_override' );
		if ( ! empty( $custom_schema ) ) {
			$decoded = json_decode( $custom_schema, true );
			if ( json_last_error() === JSON_ERROR_NONE ) {
				// If on homepage and option is enabled, return Organization schema directly
				if ( $is_homepage && $output_org_on_homepage === 'yes' ) {
					return $decoded;
				}
				
				// Clean up the organization schema for use as publisher
				// Publisher should be Organization type, not LocalBusiness
				$publisher = array(
					'@context' => 'https://schema.org',
					'@type' => 'Organization',
					'name' => $decoded['name'] ?? get_bloginfo( 'name' ),
					'url' => $decoded['url'] ?? home_url( '/' )
				);
				
				// Copy only relevant Organization properties
				$org_properties = array('logo', 'sameAs', 'contactPoint', 'email', 'telephone', 'address');
				foreach ( $org_properties as $prop ) {
					if ( isset( $decoded[$prop] ) && ! empty( $decoded[$prop] ) ) {
						$publisher[$prop] = $decoded[$prop];
					}
				}
				
				// Wrap in WebSite schema
				$schema = array(
					'@context' => 'https://schema.org',
					'@type' => 'WebSite',
					'name' => $decoded['name'] ?? get_bloginfo( 'name' ),
					'url' => home_url( '/' ),
					'publisher' => $publisher
				);
				
				// Add site search if enabled
				if ( get_option( 'bw_schema_enable_sitelinks_search', 'yes' ) === 'yes' ) {
					$schema['potentialAction'] = array(
						'@type' => 'SearchAction',
						'target' => array(
							'@type' => 'EntryPoint',
							'urlTemplate' => home_url( '/?s={search_term_string}' ),
						),
						'query-input' => array(
							'@type' => 'PropertyValueSpecification',
							'valueRequired' => true,
							'valueName' => 'search_term_string'
						),
					);
				}
				
				return $schema;
			}
		}
		
		// Default organization schema
		$org_data = BW_Schema_Core::get_organization_schema();

		// If on homepage and option is enabled, return Organization schema directly
		if ( $is_homepage && $output_org_on_homepage === 'yes' ) {
			$schema_org_type = get_option( 'bw_schema_schema_org_type', '' );
			if ( empty( $schema_org_type ) ) {
				$schema_org_type = 'Organization';
			}
			$org_schema = array(
				'@context' => 'https://schema.org',
				'@type' => $schema_org_type,
				'name' => $org_data['name'],
				'url' => home_url( '/' )
			);

			// Add telephone and email from org_data
			if ( ! empty( $org_data['telephone'] ) ) {
				$org_schema['telephone'] = $org_data['telephone'];
			}
			if ( ! empty( $org_data['email'] ) ) {
				$org_schema['email'] = $org_data['email'];
			}

			// Add logo if available
			if ( ! empty( $org_data['logo'] ) ) {
				$org_schema['logo'] = array(
					'@type' => 'ImageObject',
					'url' => $org_data['logo'],
				);
			}

			// Add same as links
			if ( ! empty( $org_data['sameAs'] ) && is_array( $org_data['sameAs'] ) ) {
				$org_schema['sameAs'] = array_filter( $org_data['sameAs'] );
			}

			// Add description from wizard Step 1
			$org_description = get_option( 'bw_schema_org_description', '' );
			if ( ! empty( $org_description ) ) {
				$org_schema['description'] = $org_description;
			}

			// Add founding date from wizard Step 1
			$founding_date = get_option( 'bw_schema_founding_date', '' );
			if ( empty( $founding_date ) ) {
				$founding_date = get_option( 'bw_schema_org_founding_date', '' );
			}
			if ( ! empty( $founding_date ) ) {
				$org_schema['foundingDate'] = $founding_date;
			}

			// Add number of employees from wizard Step 1
			$employee_count = get_option( 'bw_schema_employee_count', 0 );
			if ( ! empty( $employee_count ) && $employee_count > 0 ) {
				$org_schema['numberOfEmployees'] = array(
					'@type' => 'QuantitativeValue',
					'value' => intval( $employee_count )
				);
			}

			// Add address from wizard Step 3
			$address = get_option( 'bw_schema_address', array() );
			if ( ! empty( $address ) && ! empty( $address['street'] ) ) {
				$postal_address = array(
					'@type' => 'PostalAddress',
				);
				if ( ! empty( $address['street'] ) ) {
					$postal_address['streetAddress'] = $address['street'];
				}
				if ( ! empty( $address['city'] ) ) {
					$postal_address['addressLocality'] = $address['city'];
				}
				if ( ! empty( $address['state'] ) ) {
					$postal_address['addressRegion'] = $address['state'];
				}
				if ( ! empty( $address['postal'] ) ) {
					$postal_address['postalCode'] = $address['postal'];
				}
				if ( ! empty( $address['country'] ) ) {
					$postal_address['addressCountry'] = $address['country'];
				}
				$org_schema['address'] = $postal_address;
			}

			// Add contact points from wizard Step 3
			$contact_points = get_option( 'bw_schema_contact_points', array() );
			if ( ! empty( $contact_points ) && is_array( $contact_points ) ) {
				$schema_contact_points = array();
				foreach ( $contact_points as $contact ) {
					if ( ! empty( $contact['telephone'] ) || ! empty( $contact['email'] ) ) {
						$cp = array(
							'@type' => 'ContactPoint',
						);
						if ( ! empty( $contact['type'] ) ) {
							$cp['contactType'] = $contact['type'];
						}
						if ( ! empty( $contact['telephone'] ) ) {
							$cp['telephone'] = $contact['telephone'];
						}
						if ( ! empty( $contact['email'] ) ) {
							$cp['email'] = $contact['email'];
						}
						$schema_contact_points[] = $cp;
					}
				}
				if ( ! empty( $schema_contact_points ) ) {
					$org_schema['contactPoint'] = $schema_contact_points;
				}
			}

			// Add founders (v2.0: from team members with Is Founder flag)
			$schema_founders = array();
			$team_post_type = get_option( 'bw_schema_team_post_type', '' );
			if ( $team_post_type ) {
				$leader_members = get_posts( array(
					'post_type'      => $team_post_type,
					'posts_per_page' => -1,
					'post_status'    => 'publish',
					'meta_query'     => array(
						array(
							'key'     => '_bw_schema_is_leader',
							'value'   => '1',
							'compare' => '=',
						),
					),
				) );
				foreach ( $leader_members as $leader ) {
					$person = array(
						'@type' => 'Person',
						'name'  => $leader->post_title,
						'@id'   => get_permalink( $leader->ID ) . '#person',
					);
					// Get job title
					if ( class_exists( 'BW_Schema_Team_Member' ) ) {
						$job_title_data = BW_Schema_Team_Member::detect_job_title( $leader->ID );
						$job_title = is_array( $job_title_data ) ? ( $job_title_data['value'] ?? '' ) : $job_title_data;
						if ( ! empty( $job_title ) ) {
							$person['jobTitle'] = $job_title;
						}
					}
					$person['url'] = get_permalink( $leader->ID );
					$schema_founders[] = $person;
				}
			}
			// Fallback to legacy founders option if no team members flagged
			if ( empty( $schema_founders ) ) {
				$founders = get_option( 'bw_schema_founders', array() );
				if ( ! empty( $founders ) && is_array( $founders ) ) {
					foreach ( $founders as $founder ) {
						if ( ! empty( $founder['name'] ) ) {
							$person = array(
								'@type' => 'Person',
								'name' => $founder['name'],
							);
							if ( ! empty( $founder['jobTitle'] ) ) {
								$person['jobTitle'] = $founder['jobTitle'];
							}
							if ( ! empty( $founder['url'] ) ) {
								$person['url'] = $founder['url'];
							}
							$schema_founders[] = $person;
						}
					}
				}
			}
			if ( ! empty( $schema_founders ) ) {
				$org_schema['founder'] = count( $schema_founders ) === 1 ? $schema_founders[0] : $schema_founders;
			}

			// Add awards from wizard Step 2
			$awards = get_option( 'bw_schema_awards', array() );
			if ( ! empty( $awards ) && is_array( $awards ) ) {
				$filtered_awards = array_filter( $awards );
				if ( ! empty( $filtered_awards ) ) {
					$org_schema['award'] = array_values( $filtered_awards );
				}
			} else {
				// Legacy: check old format
				$awards_legacy = get_option( 'bw_schema_org_awards', '' );
				if ( ! empty( $awards_legacy ) ) {
					$org_schema['award'] = array_filter( array_map( 'trim', explode( "\n", $awards_legacy ) ) );
				}
			}

			// Add certifications/credentials from wizard Step 2
			$certifications = get_option( 'bw_schema_certifications', array() );
			if ( ! empty( $certifications ) && is_array( $certifications ) ) {
				$filtered_certs = array_filter( $certifications );
				if ( ! empty( $filtered_certs ) ) {
					$org_schema['hasCredential'] = array_values( $filtered_certs );
				}
			}

			// Add areas served if available
			if ( ! empty( $org_data['areaServed'] ) && is_array( $org_data['areaServed'] ) ) {
				$org_schema['areaServed'] = $org_data['areaServed'];
			}

			// Add services/products offered if available
			if ( ! empty( $org_data['makesOffer'] ) && is_array( $org_data['makesOffer'] ) ) {
				$offers = array();
				foreach ( $org_data['makesOffer'] as $offer ) {
					$offers[] = array(
						'@type' => 'Offer',
						'itemOffered' => array(
							'@type' => 'Service',
							'name' => $offer
						)
					);
				}
				$org_schema['makesOffer'] = $offers;
			}

			// Add employee array from team members (reciprocal linking)
			$team_post_type = BW_Schema_Team_Member::get_team_post_type();
			if ( $team_post_type ) {
				$team_members = get_posts( array(
					'post_type'      => $team_post_type,
					'posts_per_page' => -1,
					'post_status'    => 'publish',
					'orderby'        => 'menu_order title',
					'order'          => 'ASC',
				) );

				if ( ! empty( $team_members ) ) {
					$employees = array();
					foreach ( $team_members as $member ) {
						// Get basic Person reference with @id
						$employee = array(
							'@type' => 'Person',
							'@id'   => get_permalink( $member ) . '#person',
							'name'  => $member->post_title,
							'url'   => get_permalink( $member ),
						);

						// Add job title if available
						$job_title = get_post_meta( $member->ID, '_bw_schema_override_job_title', true );
						if ( empty( $job_title ) ) {
							$detected = BW_Schema_Team_Member::detect_job_title( $member->ID );
							$job_title = $detected['value'];
						}
						if ( ! empty( $job_title ) ) {
							$employee['jobTitle'] = $job_title;
						}

						// Add image if available
						$image = get_the_post_thumbnail_url( $member, 'thumbnail' );
						if ( ! empty( $image ) ) {
							$employee['image'] = $image;
						}

						$employees[] = $employee;
					}

					if ( ! empty( $employees ) ) {
						$org_schema['employee'] = $employees;
					}
				}
			}

			return $org_schema;
		}
		
		$publisher_type = get_option( 'bw_schema_schema_org_type', '' );
		if ( empty( $publisher_type ) ) {
			$publisher_type = 'Organization';
		}
		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => 'WebSite',
			'name' => $org_data['name'],
			'url' => home_url( '/' ),
			'publisher' => array(
				'@type' => $publisher_type,
				'name' => $org_data['name'],
				'url' => home_url( '/' ),
			)
		);
		
		// Add logo if available
		if ( ! empty( $org_data['logo'] ) ) {
			$schema['publisher']['logo'] = array(
				'@type' => 'ImageObject',
				'url' => $org_data['logo'],
			);
		}
		
		// Add same as links
		if ( ! empty( $org_data['sameAs'] ) && is_array( $org_data['sameAs'] ) ) {
			$schema['publisher']['sameAs'] = array_filter( $org_data['sameAs'] );
		}
		
		// Add phone to publisher if available
		if ( ! empty( $org_data['telephone'] ) ) {
			$schema['publisher']['telephone'] = $org_data['telephone'];
		}
		
		// Add site search if enabled
		if ( get_option( 'bw_schema_enable_sitelinks_search', 'yes' ) === 'yes' ) {
			$schema['potentialAction'] = array(
				'@type' => 'SearchAction',
				'target' => array(
					'@type' => 'EntryPoint',
					'urlTemplate' => home_url( '/?s={search_term_string}' ),
				),
				'query-input' => array(
					'@type' => 'PropertyValueSpecification',
					'valueRequired' => true,
					'valueName' => 'search_term_string'
				),
			);
		}
		
		return $schema;
	}
	
	/**
	 * Get breadcrumb schema
	 */
	private function get_breadcrumb_schema() {
		// Don't show breadcrumb on homepage
		if ( is_front_page() ) {
			return null;
		}
		
		$items = array();
		$position = 1;
		
		// Home
		$items[] = array(
			'@type' => 'ListItem',
			'position' => $position++,
			'name' => get_bloginfo( 'name' ),
			'item' => home_url( '/' ),
		);
		
		// Build breadcrumb trail
		if ( is_singular() ) {
			global $post;
			
			// Categories/taxonomies
			if ( is_single() && get_post_type() === 'post' ) {
				$categories = get_the_category( $post->ID );
				if ( ! empty( $categories ) ) {
					$category = $categories[0];
					$items[] = array(
						'@type' => 'ListItem',
						'position' => $position++,
						'name' => $category->name,
						'item' => get_category_link( $category->term_id ),
					);
				}
			}
			
			// Current page
			$items[] = array(
				'@type' => 'ListItem',
				'position' => $position++,
				'name' => get_the_title(),
				'item' => get_permalink(),
			);
			
		} elseif ( is_archive() ) {
			if ( is_category() || is_tag() || is_tax() ) {
				$term = get_queried_object();
				$items[] = array(
					'@type' => 'ListItem',
					'position' => $position++,
					'name' => $term->name,
					'item' => get_term_link( $term ),
				);
			}
		}
		
		if ( count( $items ) > 1 ) {
			return array(
				'@context' => 'https://schema.org',
				'@type' => 'BreadcrumbList',
				'itemListElement' => $items,
			);
		}
		
		return null;
	}
	
	/**
	 * Get post schema
	 */
	public function get_post_schema( $post ) {
		// Try to get from cache first
		$cache_key = BW_Schema_Cache::get_cache_key( 'post', $post->ID );
		$cached_schema = BW_Schema_Cache::get( $cache_key );
		
		if ( $cached_schema !== false ) {
			return $cached_schema;
		}
		
		// Check for custom schema first
		$custom_schema = get_post_meta( $post->ID, '_bw_schema_custom', true );
		if ( ! empty( $custom_schema ) ) {
			$decoded = json_decode( $custom_schema, true );
			if ( json_last_error() === JSON_ERROR_NONE ) {
				BW_Schema_Cache::set( $cache_key, $decoded );
				return $decoded;
			}
		}
		
		// Get schema type (checks: post meta > taxonomy mapping > post type default > fallback)
		$schema_type = BW_Schema_Core::get_schema_type_for_post( $post );
		
		// Check if schema type is 'none' or 'no_schema' - return null to skip schema generation
		if ( $schema_type === 'none:None' || strpos( $schema_type, 'none:' ) === 0 || $schema_type === 'no_schema' ) {
			return null;
		}
		
		// Generate schema based on type
		list( $main_type, $sub_type ) = explode( ':', $schema_type );
		
		switch ( $main_type ) {
			case 'article':
				$schema_class = new BW_Schema_Article();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'person':
				$schema_class = new BW_Schema_Person();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'organization':
				$schema_class = new BW_Schema_Organization();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'localbusiness':
				$schema_class = new BW_Schema_LocalBusiness();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'product':
				$schema_class = new BW_Schema_Product();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'event':
				$schema_class = new BW_Schema_Event();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'howto':
				$schema_class = new BW_Schema_HowTo();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'faq':
				$schema_class = new BW_Schema_FAQ();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'review':
				$schema_class = new BW_Schema_Review();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'recipe':
				$schema_class = new BW_Schema_Recipe();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'video':
				$schema_class = new BW_Schema_Video();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'course':
				$schema_class = new BW_Schema_Course();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'jobposting':
				$schema_class = new BW_Schema_JobPosting();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'webpage':
				$schema_class = new BW_Schema_WebPage();
				$schema = $schema_class->generate( $post, $sub_type );
				break;
				
			case 'none':
				// No schema - return null
				return null;
				break;
				
			default:
				// Default to article
				$schema_class = new BW_Schema_Article();
				$schema = $schema_class->generate( $post, 'Article' );
				break;
		}
		
		// Cache the generated schema
		if ( ! empty( $schema ) ) {
			BW_Schema_Cache::set( $cache_key, $schema );
		}
		
		return $schema;
	}
	
	/**
	 * Get author page schema
	 */
	private function get_author_page_schema() {
		$author_id = get_queried_object_id();
		$author_data = BW_Schema_Core::get_author_schema( $author_id );
		
		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => 'ProfilePage',
			'mainEntity' => array(
				'@type' => 'Person',
				'name' => $author_data['name'],
				'url' => $author_data['url'],
				'description' => $author_data['description'],
			)
		);
		
		// Add image
		if ( ! empty( $author_data['image'] ) ) {
			$schema['mainEntity']['image'] = $author_data['image'];
		}
		
		// Add same as
		if ( ! empty( $author_data['sameAs'] ) && is_array( $author_data['sameAs'] ) ) {
			$schema['mainEntity']['sameAs'] = array_filter( $author_data['sameAs'] );
		}
		
		// Add expertise
		if ( ! empty( $author_data['knowsAbout'] ) && is_array( $author_data['knowsAbout'] ) ) {
			$schema['mainEntity']['knowsAbout'] = array_filter( $author_data['knowsAbout'] );
		}
		
		return $schema;
	}
	
	/**
	 * Get archive schema
	 */
	private function get_archive_schema() {
		// Check if this is a team members page
		if ( $this->is_team_page() ) {
			return $this->get_team_page_schema();
		}
		
		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => 'CollectionPage',
			'name' => wp_get_document_title(),
			'url' => get_permalink(),
		);
		
		if ( is_category() || is_tag() || is_tax() ) {
			$term = get_queried_object();
			$schema['description'] = term_description( $term->term_id );
		}
		
		return $schema;
	}
	
	/**
	 * Get team page schema
	 */
	private function get_team_page_schema() {
		global $wp_query;

		// Save the current page URL before any queries change the global post
		$page_url = is_page() ? get_permalink( get_queried_object_id() ) : get_post_type_archive_link( get_query_var( 'post_type' ) );
		$page_name = is_page() ? get_the_title( get_queried_object_id() ) : post_type_archive_title( '', false );

		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => 'ItemList',
			'name' => $page_name ?: 'Our Team',
			'url' => $page_url ?: home_url(),
			'numberOfItems' => 0,
			'itemListElement' => array()
		);

		// Get team members
		$team_members = array();
		
		// Get the team post type option (uses centralized getter, no hardcoded default)
		$team_post_type = BW_Schema_Team_Member::get_team_post_type();
		
		// First, check if we're on a page with a query loop
		if ( is_page() ) {
			// Try to get team members from the page content's query loop
			// We'll query for team member post type
			$args = array(
				'post_type' => $team_post_type,
				'posts_per_page' => -1,
				'orderby' => 'menu_order title',
				'order' => 'ASC',
				'post_status' => 'publish'
			);
			
			$team_query = new WP_Query( $args );
			
			if ( $team_query->have_posts() ) {
				while ( $team_query->have_posts() ) {
					$team_query->the_post();
					$team_members[] = get_post();
				}
				wp_reset_postdata();
			}
		} elseif ( is_post_type_archive( $team_post_type ) ) {
			// On archive page, use the main query
			if ( have_posts() ) {
				while ( have_posts() ) {
					the_post();
					$team_members[] = get_post();
				}
				rewind_posts();
			}
		}
		
		// Generate Person schema for each team member
		$position = 1;
		foreach ( $team_members as $member ) {
			$person_schema_class = new BW_Schema_Person();
			$person_schema = $person_schema_class->generate( $member, 'Person' );
			
			// Add to ItemList
			if ( $person_schema ) {
				$schema['itemListElement'][] = array(
					'@type' => 'ListItem',
					'position' => $position,
					'item' => $person_schema
				);
				$position++;
			}
		}
		
		$schema['numberOfItems'] = count( $schema['itemListElement'] );
		
		// Add description if available
		if ( is_page() ) {
			$page = get_post();
			if ( has_excerpt( $page ) ) {
				$schema['description'] = wp_strip_all_tags( get_the_excerpt( $page ) );
			}
		}
		
		// Add organization context
		$org_data = BW_Schema_Core::get_organization_schema();
		$schema['isPartOf'] = array(
			'@type' => 'WebSite',
			'name' => $org_data['name'],
			'url' => home_url( '/' )
		);
		
		return apply_filters( 'bw_schema_team_page', $schema, $team_members );
	}

	/**
	 * Get ProfilePage + Person schema for a team member profile page
	 *
	 * @param WP_Post $team_member Team member post object
	 * @return array ProfilePage schema with Person as mainEntity
	 */
	private function get_team_member_profile_schema( $team_member ) {
		// Get Person schema data from the team member class
		$person_data = BW_Schema_Team_Member::get_person_schema_data( $team_member );

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

		// Build the Person schema with @type and @id
		$person_schema = array_merge(
			array(
				'@type' => 'Person',
				'@id'   => get_permalink( $team_member ) . '#person',
			),
			$person_data
		);

		// Build the ProfilePage schema
		$schema = array(
			'@context'   => 'https://schema.org',
			'@type'      => 'ProfilePage',
			'@id'        => get_permalink( $team_member ),
			'name'       => $team_member->post_title,
			'url'        => get_permalink( $team_member ),
			'mainEntity' => $person_schema,
		);

		// Add datePublished and dateModified
		$schema['datePublished'] = get_the_date( 'c', $team_member );
		$schema['dateModified'] = get_the_modified_date( 'c', $team_member );

		// Add description if available
		$excerpt = get_the_excerpt( $team_member );
		if ( ! empty( $excerpt ) ) {
			$schema['description'] = wp_strip_all_tags( $excerpt );
		}

		// Add isPartOf to link to the website
		$org_data = BW_Schema_Core::get_organization_schema();
		$schema['isPartOf'] = array(
			'@type' => 'WebSite',
			'name'  => ! empty( $org_data['name'] ) ? $org_data['name'] : get_bloginfo( 'name' ),
			'url'   => home_url( '/' ),
		);

		return apply_filters( 'bw_schema_team_member_profile', $schema, $team_member );
	}
}