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

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

class BW_Schema_Core {
	
	/**
	 * Get default schema types
	 */
	public static function get_schema_types() {
		$types = array(
			'article' => array(
				'label' => __( 'Article', 'bw-ai-schema-pro' ),
				'description' => __( 'For blog posts, news articles, and general content', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-media-document',
				'subtypes' => array(
					'Article' => __( 'General Article', 'bw-ai-schema-pro' ),
					'NewsArticle' => __( 'News Article', 'bw-ai-schema-pro' ),
					'BlogPosting' => __( 'Blog Post', 'bw-ai-schema-pro' ),
					'TechArticle' => __( 'Technical Article', 'bw-ai-schema-pro' ),
					'ScholarlyArticle' => __( 'Scholarly Article', 'bw-ai-schema-pro' ),
				)
			),
			'person' => array(
				'label' => __( 'Person', 'bw-ai-schema-pro' ),
				'description' => __( 'For author profiles and personal pages', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-admin-users',
				'subtypes' => array(
					'Person' => __( 'General Person', 'bw-ai-schema-pro' ),
					'Author' => __( 'Author', 'bw-ai-schema-pro' ),
					'Expert' => __( 'Subject Matter Expert', 'bw-ai-schema-pro' ),
				)
			),
			'organization' => array(
				'label' => __( 'Organization', 'bw-ai-schema-pro' ),
				'description' => __( 'For company and organization pages', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-building',
				'subtypes' => array(
					'Organization' => __( 'General Organization', 'bw-ai-schema-pro' ),
					'Corporation' => __( 'Corporation', 'bw-ai-schema-pro' ),
					'EducationalOrganization' => __( 'Educational Organization', 'bw-ai-schema-pro' ),
					'GovernmentOrganization' => __( 'Government Organization', 'bw-ai-schema-pro' ),
					'NGO' => __( 'Non-Governmental Organization', 'bw-ai-schema-pro' ),
				)
			),
			'localbusiness' => array(
				'label' => __( 'Local Business', 'bw-ai-schema-pro' ),
				'description' => __( 'For local business listings', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-store',
				'subtypes' => array(
					'LocalBusiness' => __( 'General Local Business', 'bw-ai-schema-pro' ),
					'ProfessionalService' => __( 'Professional Service', 'bw-ai-schema-pro' ),
					'ConsultingBusiness' => __( 'Consulting Firm', 'bw-ai-schema-pro' ),
					'Hotel' => __( 'Hotel', 'bw-ai-schema-pro' ),
					'Resort' => __( 'Resort', 'bw-ai-schema-pro' ),
					'Attorney' => __( 'Law Firm / Attorney', 'bw-ai-schema-pro' ),
					'Restaurant' => __( 'Restaurant', 'bw-ai-schema-pro' ),
					'MedicalBusiness' => __( 'Medical Business', 'bw-ai-schema-pro' ),
					'FinancialService' => __( 'Financial Service', 'bw-ai-schema-pro' ),
					'RealEstateAgent' => __( 'Real Estate Agent', 'bw-ai-schema-pro' ),
				)
			),
			'howto' => array(
				'label' => __( 'How-To', 'bw-ai-schema-pro' ),
				'description' => __( 'For tutorials and guides', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-lightbulb',
				'subtypes' => array(
					'HowTo' => __( 'How-To Guide', 'bw-ai-schema-pro' ),
					'Recipe' => __( 'Recipe', 'bw-ai-schema-pro' ),
				)
			),
			'faq' => array(
				'label' => __( 'FAQ', 'bw-ai-schema-pro' ),
				'description' => __( 'For frequently asked questions', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-editor-help',
				'subtypes' => array(
					'FAQPage' => __( 'FAQ Page', 'bw-ai-schema-pro' ),
				)
			),
			'review' => array(
				'label' => __( 'Review', 'bw-ai-schema-pro' ),
				'description' => __( 'For reviews and ratings', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-star-filled',
				'subtypes' => array(
					'Review' => __( 'Review', 'bw-ai-schema-pro' ),
					'AggregateRating' => __( 'Aggregate Rating', 'bw-ai-schema-pro' ),
				)
			),
			'event' => array(
				'label' => __( 'Event', 'bw-ai-schema-pro' ),
				'description' => __( 'For events, conferences, concerts', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-calendar-alt',
				'subtypes' => array(
					'Event' => __( 'General Event', 'bw-ai-schema-pro' ),
					'BusinessEvent' => __( 'Business Event', 'bw-ai-schema-pro' ),
					'MusicEvent' => __( 'Concert/Music Event', 'bw-ai-schema-pro' ),
					'SportsEvent' => __( 'Sports Event', 'bw-ai-schema-pro' ),
					'EducationEvent' => __( 'Educational Event', 'bw-ai-schema-pro' ),
				)
			),
			'product' => array(
				'label' => __( 'Product', 'bw-ai-schema-pro' ),
				'description' => __( 'For products and services', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-products',
				'subtypes' => array(
					'Product' => __( 'General Product', 'bw-ai-schema-pro' ),
					'Book' => __( 'Book', 'bw-ai-schema-pro' ),
					'Movie' => __( 'Movie', 'bw-ai-schema-pro' ),
					'SoftwareApplication' => __( 'Software/App', 'bw-ai-schema-pro' ),
					'Vehicle' => __( 'Vehicle', 'bw-ai-schema-pro' ),
				)
			),
			'recipe' => array(
				'label' => __( 'Recipe', 'bw-ai-schema-pro' ),
				'description' => __( 'For cooking recipes', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-food',
				'subtypes' => array(
					'Recipe' => __( 'Recipe', 'bw-ai-schema-pro' ),
				)
			),
			'video' => array(
				'label' => __( 'Video', 'bw-ai-schema-pro' ),
				'description' => __( 'For video content', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-video-alt3',
				'subtypes' => array(
					'VideoObject' => __( 'General Video', 'bw-ai-schema-pro' ),
					'Movie' => __( 'Movie', 'bw-ai-schema-pro' ),
					'TVEpisode' => __( 'TV Episode', 'bw-ai-schema-pro' ),
					'MusicVideoObject' => __( 'Music Video', 'bw-ai-schema-pro' ),
				)
			),
			'course' => array(
				'label' => __( 'Course', 'bw-ai-schema-pro' ),
				'description' => __( 'For educational courses', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-welcome-learn-more',
				'subtypes' => array(
					'Course' => __( 'Course', 'bw-ai-schema-pro' ),
				)
			),
			'jobposting' => array(
				'label' => __( 'Job Posting', 'bw-ai-schema-pro' ),
				'description' => __( 'For job listings', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-businessperson',
				'subtypes' => array(
					'JobPosting' => __( 'Job Posting', 'bw-ai-schema-pro' ),
				)
			),
			'webpage' => array(
				'label' => __( 'Web Page', 'bw-ai-schema-pro' ),
				'description' => __( 'For specific page types', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-admin-page',
				'subtypes' => array(
					'WebPage' => __( 'General Web Page', 'bw-ai-schema-pro' ),
					'AboutPage' => __( 'About Page', 'bw-ai-schema-pro' ),
					'ContactPage' => __( 'Contact Page', 'bw-ai-schema-pro' ),
					'ProfilePage' => __( 'Profile/Team Member Page', 'bw-ai-schema-pro' ),
					'CollectionPage' => __( 'Collection/Archive Page', 'bw-ai-schema-pro' ),
					'QAPage' => __( 'Question & Answer Page', 'bw-ai-schema-pro' ),
				)
			),
			'none' => array(
				'label' => __( 'No Schema', 'bw-ai-schema-pro' ),
				'description' => __( 'Disable schema markup for this content', 'bw-ai-schema-pro' ),
				'icon' => 'dashicons-dismiss',
				'subtypes' => array(
					'None' => __( 'No Schema Markup', 'bw-ai-schema-pro' ),
				)
			),
		);
		
		// Allow developers to add or modify schema types
		return apply_filters( 'bw_schema_types', $types );
	}
	
	/**
	 * Get AI-optimized properties for enhanced schema
	 */
	public static function get_ai_properties() {
		$properties = array(
			'credibility' => array(
				'sameAs' => __( 'Social/Authority Profiles', 'bw-ai-schema-pro' ),
				'citation' => __( 'Citations and References', 'bw-ai-schema-pro' ),
				'award' => __( 'Awards and Recognition', 'bw-ai-schema-pro' ),
				'certification' => __( 'Certifications', 'bw-ai-schema-pro' ),
			),
			'expertise' => array(
				'knowsAbout' => __( 'Areas of Expertise', 'bw-ai-schema-pro' ),
				'alumniOf' => __( 'Education', 'bw-ai-schema-pro' ),
				'memberOf' => __( 'Professional Memberships', 'bw-ai-schema-pro' ),
				'hasCredential' => __( 'Credentials', 'bw-ai-schema-pro' ),
			),
			'trust' => array(
				'reviewedBy' => __( 'Reviewed By', 'bw-ai-schema-pro' ),
				'factCheckedBy' => __( 'Fact Checked By', 'bw-ai-schema-pro' ),
				'lastReviewed' => __( 'Last Review Date', 'bw-ai-schema-pro' ),
				'sourceOrganization' => __( 'Source Organization', 'bw-ai-schema-pro' ),
			),
			'content' => array(
				'about' => __( 'Main Topic Entities', 'bw-ai-schema-pro' ),
				'mentions' => __( 'Mentioned Entities', 'bw-ai-schema-pro' ),
				'keywords' => __( 'Keywords', 'bw-ai-schema-pro' ),
				'learningResourceType' => __( 'Content Type', 'bw-ai-schema-pro' ),
			)
		);
		
		// Allow developers to add or modify AI properties
		return apply_filters( 'bw_schema_ai_properties', $properties );
	}
	
	/**
	 * Get post type default schemas
	 */
	public static function get_post_type_defaults() {
		$defaults = get_option( 'bw_schema_post_type_defaults', array() );

		if ( empty( $defaults ) ) {
			$defaults = array(
				'post' => 'article:BlogPosting',
				'page' => 'article:Article',
			);
		}

		return $defaults;
	}

	/**
	 * Get taxonomy-based schema mappings
	 *
	 * Structure:
	 * [
	 *     'post_type' => [
	 *         'taxonomy' => 'category',
	 *         'term_mappings' => [
	 *             'term-slug' => 'article:NewsArticle',
	 *         ]
	 *     ]
	 * ]
	 */
	public static function get_taxonomy_mappings() {
		$mappings = get_option( 'bw_schema_taxonomy_mappings', array() );
		return apply_filters( 'bw_schema_taxonomy_mappings', $mappings );
	}

	/**
	 * Update taxonomy mappings
	 */
	public static function update_taxonomy_mappings( $mappings ) {
		return update_option( 'bw_schema_taxonomy_mappings', $mappings );
	}

	/**
	 * Get schema type for a specific post
	 *
	 * Priority:
	 * 1. Post-specific meta override (_bw_schema_type)
	 * 2. Taxonomy term mapping (if configured for this post type)
	 * 3. Post type default
	 * 4. Fallback to article:Article
	 *
	 * @param WP_Post|int $post Post object or ID
	 * @return string Schema type in format "main_type:sub_type"
	 */
	public static function get_schema_type_for_post( $post ) {
		if ( is_numeric( $post ) ) {
			$post = get_post( $post );
		}

		if ( ! $post ) {
			return 'article:Article';
		}

		// 1. Check for post-specific override
		$schema_type = get_post_meta( $post->ID, '_bw_schema_type', true );
		if ( ! empty( $schema_type ) ) {
			return $schema_type;
		}

		// 2. Check page mappings (wizard step 4)
		$schema_type = self::get_schema_type_from_page_mapping( $post );
		if ( ! empty( $schema_type ) ) {
			return $schema_type;
		}

		// 3. Check taxonomy mappings
		$schema_type = self::get_schema_type_from_taxonomy( $post );
		if ( ! empty( $schema_type ) ) {
			return $schema_type;
		}

		// 4. Fall back to post type default
		$defaults = self::get_post_type_defaults();
		if ( isset( $defaults[ $post->post_type ] ) ) {
			return $defaults[ $post->post_type ];
		}

		// 5. Ultimate fallback
		return 'article:Article';
	}

	/**
	 * Get schema type based on page mappings from wizard
	 *
	 * @param WP_Post $post Post object
	 * @return string|null Schema type or null if no mapping found
	 */
	public static function get_schema_type_from_page_mapping( $post ) {
		// Only applies to pages
		if ( $post->post_type !== 'page' ) {
			return null;
		}

		$page_mappings = get_option( 'bw_schema_page_mappings', array() );
		if ( empty( $page_mappings ) ) {
			return null;
		}

		// Map page type to schema type
		// Note: Homepage not included - uses WebSite/Organization schema handled separately
		$schema_type_map = array(
			'about'    => 'webpage:AboutPage',
			'services' => 'webpage:CollectionPage',
			'contact'  => 'webpage:ContactPage',
			'blog'     => 'webpage:CollectionPage',
			'team'     => 'webpage:CollectionPage',
			'terms'    => 'webpage:WebPage',
			'privacy'  => 'webpage:WebPage',
		);

		// Check if this page is mapped
		foreach ( $page_mappings as $page_type => $page_id ) {
			if ( intval( $page_id ) === $post->ID && isset( $schema_type_map[ $page_type ] ) ) {
				return $schema_type_map[ $page_type ];
			}
		}

		return null;
	}

	/**
	 * Get schema type based on post's taxonomy terms
	 *
	 * @param WP_Post $post Post object
	 * @return string|null Schema type or null if no mapping found
	 */
	public static function get_schema_type_from_taxonomy( $post ) {
		$mappings = self::get_taxonomy_mappings();

		// Check if this post type has taxonomy mapping configured
		if ( ! isset( $mappings[ $post->post_type ] ) ) {
			return null;
		}

		$config = $mappings[ $post->post_type ];
		$taxonomy = $config['taxonomy'] ?? '';
		$term_mappings = $config['term_mappings'] ?? array();

		if ( empty( $taxonomy ) || empty( $term_mappings ) ) {
			return null;
		}

		// Get post's terms for this taxonomy
		$terms = wp_get_post_terms( $post->ID, $taxonomy, array( 'fields' => 'slugs' ) );

		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return null;
		}

		// Check each term against mappings (first match wins)
		foreach ( $terms as $term_slug ) {
			if ( isset( $term_mappings[ $term_slug ] ) ) {
				return $term_mappings[ $term_slug ];
			}
		}

		return null;
	}

	/**
	 * Get global organization schema
	 */
	public static function get_organization_schema() {
		return get_option( 'bw_schema_organization', array(
			'name' => get_bloginfo( 'name' ),
			'url' => home_url(),
			'logo' => '',
			'telephone' => '',
			'sameAs' => array(),
			'contactPoint' => array(),
		));
	}

	/**
	 * Get setup completion status with detailed checklist
	 *
	 * @return array Completion status with checks, counts, and percentage
	 */
	public static function get_setup_completion_status() {
		$org_data = self::get_organization_schema();
		$founders = get_option( 'bw_schema_founders', array() );
		$contact_points = get_option( 'bw_schema_contact_points', array() );
		$page_mappings = get_option( 'bw_schema_page_mappings', array() );
		$post_type_defaults = get_option( 'bw_schema_post_type_defaults', array() );

		// Check if org name was explicitly set (not just defaulted)
		$org_option_exists = get_option( 'bw_schema_organization', false );
		$org_name_set = $org_option_exists !== false && isset( $org_option_exists['name'] ) && ! empty( $org_option_exists['name'] );

		$checks = array(
			'organization_name' => array(
				'label'       => __( 'Organization Name', 'bw-ai-schema-pro' ),
				'description' => __( 'Your company or organization name', 'bw-ai-schema-pro' ),
				'complete'    => $org_name_set,
				'step'        => 1,
				'priority'    => 'required',
			),
			'organization_url' => array(
				'label'       => __( 'Website URL', 'bw-ai-schema-pro' ),
				'description' => __( 'Your website address', 'bw-ai-schema-pro' ),
				'complete'    => ! empty( $org_data['url'] ),
				'step'        => 1,
				'priority'    => 'required',
			),
			'organization_logo' => array(
				'label'       => __( 'Organization Logo', 'bw-ai-schema-pro' ),
				'description' => __( 'Logo image for rich results', 'bw-ai-schema-pro' ),
				'complete'    => ! empty( $org_data['logo'] ),
				'step'        => 1,
				'priority'    => 'recommended',
			),
			'business_type' => array(
				'label'       => __( 'Business Type', 'bw-ai-schema-pro' ),
				'description' => __( 'Type of business or organization', 'bw-ai-schema-pro' ),
				'complete'    => ! empty( get_option( 'bw_schema_business_type' ) ),
				'step'        => 1,
				'priority'    => 'required',
			),
			'founders' => array(
				'label'       => __( 'Leadership/Founders', 'bw-ai-schema-pro' ),
				'description' => __( 'Key people in your organization', 'bw-ai-schema-pro' ),
				'complete'    => ! empty( $founders ) && isset( $founders[0]['name'] ) && ! empty( $founders[0]['name'] ),
				'step'        => 2,
				'priority'    => 'recommended',
			),
			'social_profiles' => array(
				'label'       => __( 'Social Profiles', 'bw-ai-schema-pro' ),
				'description' => __( 'Social media links for sameAs property', 'bw-ai-schema-pro' ),
				'complete'    => ! empty( $org_data['sameAs'] ) && count( array_filter( (array) $org_data['sameAs'] ) ) > 0,
				'step'        => 3,
				'priority'    => 'recommended',
			),
			'contact_info' => array(
				'label'       => __( 'Contact Information', 'bw-ai-schema-pro' ),
				'description' => __( 'Phone, email, or contact points', 'bw-ai-schema-pro' ),
				'complete'    => ! empty( $contact_points ) || ! empty( $org_data['telephone'] ) || ! empty( $org_data['email'] ),
				'step'        => 3,
				'priority'    => 'recommended',
			),
			'page_mappings' => array(
				'label'       => __( 'Page Mappings', 'bw-ai-schema-pro' ),
				'description' => __( 'Key pages mapped (About, Contact, etc.)', 'bw-ai-schema-pro' ),
				'complete'    => count( array_filter( $page_mappings ) ) >= 2,
				'step'        => 4,
				'priority'    => 'recommended',
			),
			'content_defaults' => array(
				'label'       => __( 'Content Type Defaults', 'bw-ai-schema-pro' ),
				'description' => __( 'Default schema for posts and pages', 'bw-ai-schema-pro' ),
				'complete'    => ! empty( $post_type_defaults ),
				'step'        => 5,
				'priority'    => 'optional',
			),
		);

		// Calculate stats
		$required_checks = array_filter( $checks, function( $check ) {
			return $check['priority'] === 'required';
		});
		$recommended_checks = array_filter( $checks, function( $check ) {
			return $check['priority'] === 'recommended';
		});

		$required_complete = count( array_filter( $required_checks, function( $check ) {
			return $check['complete'];
		}));
		$recommended_complete = count( array_filter( $recommended_checks, function( $check ) {
			return $check['complete'];
		}));
		$total_complete = count( array_filter( $checks, function( $check ) {
			return $check['complete'];
		}));

		$total = count( $checks );
		$percentage = $total > 0 ? round( ( $total_complete / $total ) * 100 ) : 0;

		// Determine status level
		$status = 'incomplete';
		if ( $percentage === 100 ) {
			$status = 'complete';
		} elseif ( $required_complete === count( $required_checks ) ) {
			$status = 'good';
		} elseif ( $percentage >= 50 ) {
			$status = 'partial';
		}

		return array(
			'checks'               => $checks,
			'completed'            => $total_complete,
			'total'                => $total,
			'percentage'           => $percentage,
			'required_complete'    => $required_complete,
			'required_total'       => count( $required_checks ),
			'recommended_complete' => $recommended_complete,
			'recommended_total'    => count( $recommended_checks ),
			'status'               => $status,
		);
	}

	/**
	 * Get author schema data
	 */
	public static function get_author_schema( $author_id ) {
		$author_data = get_user_meta( $author_id, '_bw_schema_author_data', true );
		
		if ( empty( $author_data ) ) {
			$user = get_userdata( $author_id );
			$author_data = array(
				'name' => $user->display_name,
				'description' => get_the_author_meta( 'description', $author_id ),
				'url' => get_author_posts_url( $author_id ),
				'image' => get_avatar_url( $author_id ),
				'sameAs' => array(),
				'knowsAbout' => array(),
			);
		}
		
		return $author_data;
	}
	
	/**
	 * Sanitize schema data
	 */
	public static function sanitize_schema_data( $data ) {
		if ( is_array( $data ) ) {
			foreach ( $data as $key => $value ) {
				if ( is_array( $value ) ) {
					$data[$key] = self::sanitize_schema_data( $value );
				} else {
					$data[$key] = sanitize_text_field( $value );
				}
			}
		} else {
			$data = sanitize_text_field( $data );
		}
		
		return $data;
	}
	
	/**
	 * Validate schema markup
	 */
	public static function validate_schema( $schema ) {
		// Basic validation - ensure required properties
		if ( ! isset( $schema['@context'] ) || ! isset( $schema['@type'] ) ) {
			return false;
		}
		
		// Additional validation can be added here
		return true;
	}
	
	/**
	 * ========================================
	 * CONSOLIDATED OPTIONS SYSTEM
	 * ========================================
	 */

	/**
	 * Settings schema version for migrations
	 */
	const SETTINGS_VERSION = '2.0.0';

	/**
	 * Get the default consolidated settings structure
	 *
	 * @return array Default settings
	 */
	public static function get_default_settings() {
		return array(
			'settings_version' => self::SETTINGS_VERSION,
			'features' => array(
				'enable_schema'          => 'yes',
				'enable_breadcrumbs'     => 'yes',
				'enable_sitelinks_search' => 'yes',
				'enable_cache'           => 'yes',
				'enable_price_range'     => 'no',
			),
			'display' => array(
				'metabox_position'       => 'normal',
				'metabox_default_state'  => 'collapsed',
				'metabox_post_types'     => array(),
				'output_org_homepage'    => 'no',
			),
			'author_box' => array(
				'enabled'                => 'yes',
				'position'               => 'after_content',
				'post_types'             => array( 'post' ),
			),
			'content' => array(
				'page_mappings'          => array(),
				'post_type_defaults'     => array(),
				'team_post_type'         => 'sw_teammember',
			),
			'ai_optimization' => array(
				'publishing_principles'  => '',
				'fact_checking_policy'   => '',
			),
			'conflict_management' => array(
				'disable_sources'        => array(),
			),
		);
	}

	/**
	 * Get consolidated settings
	 *
	 * @param string|null $group Optional group to retrieve (features, display, etc.)
	 * @param string|null $key   Optional specific key within the group
	 * @param mixed       $default Default value if not found
	 * @return mixed Settings value(s)
	 */
	public static function get_settings( $group = null, $key = null, $default = null ) {
		$settings = get_option( 'bw_schema_settings', array() );
		$defaults = self::get_default_settings();

		// Merge with defaults
		$settings = self::array_merge_recursive_distinct( $defaults, $settings );

		// Return all settings
		if ( $group === null ) {
			return $settings;
		}

		// Return specific group
		if ( $key === null ) {
			return isset( $settings[ $group ] ) ? $settings[ $group ] : ( $default !== null ? $default : array() );
		}

		// Return specific key within group
		if ( isset( $settings[ $group ][ $key ] ) ) {
			return $settings[ $group ][ $key ];
		}

		// Fallback to legacy option for backward compatibility
		$legacy_value = self::get_legacy_option( $group, $key );
		if ( $legacy_value !== null ) {
			return $legacy_value;
		}

		return $default;
	}

	/**
	 * Update consolidated settings
	 *
	 * @param string $group Group to update
	 * @param string|array $key Key to update or array of key=>value pairs
	 * @param mixed $value Value to set (if $key is string)
	 * @return bool Success
	 */
	public static function update_settings( $group, $key, $value = null ) {
		$settings = get_option( 'bw_schema_settings', array() );
		$defaults = self::get_default_settings();
		$settings = self::array_merge_recursive_distinct( $defaults, $settings );

		if ( is_array( $key ) ) {
			// Bulk update
			$settings[ $group ] = array_merge( $settings[ $group ], $key );
		} else {
			// Single key update
			$settings[ $group ][ $key ] = $value;
		}

		$settings['settings_version'] = self::SETTINGS_VERSION;

		return update_option( 'bw_schema_settings', $settings );
	}

	/**
	 * Get legacy option value for backward compatibility
	 *
	 * @param string $group Settings group
	 * @param string $key   Settings key
	 * @return mixed|null Value or null if not found
	 */
	private static function get_legacy_option( $group, $key ) {
		$legacy_map = array(
			'features' => array(
				'enable_schema'           => 'bw_schema_enable_schema',
				'enable_breadcrumbs'      => 'bw_schema_enable_breadcrumbs',
				'enable_sitelinks_search' => 'bw_schema_enable_sitelinks_search',
				'enable_cache'            => 'bw_schema_enable_cache',
				'enable_price_range'      => 'bw_schema_enable_price_range',
			),
			'display' => array(
				'metabox_position'        => 'bw_schema_metabox_position',
				'metabox_default_state'   => 'bw_schema_metabox_default_state',
				'metabox_post_types'      => 'bw_schema_metabox_post_types',
				'output_org_homepage'     => 'bw_schema_output_org_homepage',
			),
			'author_box' => array(
				'enabled'                 => 'bw_schema_author_box_enabled',
				'position'                => 'bw_schema_author_box_position',
				'post_types'              => 'bw_schema_author_box_post_types',
			),
			'content' => array(
				'page_mappings'           => 'bw_schema_page_mappings',
				'post_type_defaults'      => 'bw_schema_post_type_defaults',
				'team_post_type'          => 'bw_schema_team_post_type',
			),
			'ai_optimization' => array(
				'publishing_principles'   => 'bw_schema_publishing_principles',
				'fact_checking_policy'    => 'bw_schema_fact_checking_policy',
			),
			'conflict_management' => array(
				'disable_sources'         => 'bw_schema_disable_sources',
			),
		);

		if ( isset( $legacy_map[ $group ][ $key ] ) ) {
			$legacy_key = $legacy_map[ $group ][ $key ];
			$value = get_option( $legacy_key, null );
			if ( $value !== null ) {
				return $value;
			}
		}

		return null;
	}

	/**
	 * Migrate legacy options to consolidated structure
	 *
	 * @return bool Whether migration was performed
	 */
	public static function maybe_migrate_options() {
		$current_version = get_option( 'bw_schema_settings_version', '1.0.0' );

		// Already migrated
		if ( version_compare( $current_version, self::SETTINGS_VERSION, '>=' ) ) {
			return false;
		}

		$settings = self::get_default_settings();

		// Migrate features
		$features_map = array(
			'enable_schema'           => array( 'bw_schema_enable_schema', 'yes' ),
			'enable_breadcrumbs'      => array( 'bw_schema_enable_breadcrumbs', 'yes' ),
			'enable_sitelinks_search' => array( 'bw_schema_enable_sitelinks_search', 'yes' ),
			'enable_cache'            => array( 'bw_schema_enable_cache', 'yes' ),
			'enable_price_range'      => array( 'bw_schema_enable_price_range', 'no' ),
		);
		foreach ( $features_map as $key => $legacy ) {
			$value = get_option( $legacy[0], $legacy[1] );
			if ( $value !== null ) {
				$settings['features'][ $key ] = $value;
			}
		}

		// Migrate display settings
		$display_map = array(
			'metabox_position'      => array( 'bw_schema_metabox_position', 'normal' ),
			'metabox_default_state' => array( 'bw_schema_metabox_default_state', 'collapsed' ),
			'metabox_post_types'    => array( 'bw_schema_metabox_post_types', array() ),
			'output_org_homepage'   => array( 'bw_schema_output_org_homepage', 'no' ),
		);
		foreach ( $display_map as $key => $legacy ) {
			$value = get_option( $legacy[0], $legacy[1] );
			if ( $value !== null ) {
				$settings['display'][ $key ] = $value;
			}
		}

		// Migrate author box settings
		$author_box_map = array(
			'enabled'    => array( 'bw_schema_author_box_enabled', 'yes' ),
			'position'   => array( 'bw_schema_author_box_position', 'after_content' ),
			'post_types' => array( 'bw_schema_author_box_post_types', array( 'post' ) ),
		);
		foreach ( $author_box_map as $key => $legacy ) {
			$value = get_option( $legacy[0], $legacy[1] );
			if ( $value !== null ) {
				$settings['author_box'][ $key ] = $value;
			}
		}

		// Migrate content settings
		$content_map = array(
			'page_mappings'      => array( 'bw_schema_page_mappings', array() ),
			'post_type_defaults' => array( 'bw_schema_post_type_defaults', array() ),
			'team_post_type'     => array( 'bw_schema_team_post_type', '' ),
		);
		foreach ( $content_map as $key => $legacy ) {
			$value = get_option( $legacy[0], $legacy[1] );
			if ( $value !== null ) {
				$settings['content'][ $key ] = $value;
			}
		}

		// Migrate AI optimization settings
		$ai_map = array(
			'publishing_principles' => array( 'bw_schema_publishing_principles', '' ),
			'fact_checking_policy'  => array( 'bw_schema_fact_checking_policy', '' ),
		);
		foreach ( $ai_map as $key => $legacy ) {
			$value = get_option( $legacy[0], '' );
			if ( ! empty( $value ) ) {
				$settings['ai_optimization'][ $key ] = $value;
			}
		}

		// Migrate conflict management
		$conflict_map = array(
			'disable_sources' => array( 'bw_schema_disable_sources', array() ),
		);
		foreach ( $conflict_map as $key => $legacy ) {
			$value = get_option( $legacy[0], array() );
			if ( ! empty( $value ) ) {
				$settings['conflict_management'][ $key ] = $value;
			}
		}

		// Save consolidated settings
		update_option( 'bw_schema_settings', $settings );
		update_option( 'bw_schema_settings_version', self::SETTINGS_VERSION );

		// Log migration
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'BW Schema Pro: Migrated options to consolidated structure v' . self::SETTINGS_VERSION );
		}

		return true;
	}

	/**
	 * Helper: Recursively merge arrays (distinct)
	 *
	 * @param array $array1 Base array
	 * @param array $array2 Array to merge
	 * @return array Merged array
	 */
	private static function array_merge_recursive_distinct( array $array1, array $array2 ) {
		$merged = $array1;

		foreach ( $array2 as $key => $value ) {
			if ( is_array( $value ) && isset( $merged[ $key ] ) && is_array( $merged[ $key ] ) ) {
				$merged[ $key ] = self::array_merge_recursive_distinct( $merged[ $key ], $value );
			} else {
				$merged[ $key ] = $value;
			}
		}

		return $merged;
	}

	/**
	 * ========================================
	 * END CONSOLIDATED OPTIONS SYSTEM
	 * ========================================
	 */

	/**
	 * Plugin activation
	 */
	public static function activate() {
		// Run migration if needed
		self::maybe_migrate_options();

		// Set default options (legacy support)
		$defaults = array(
			'enable_schema' => 'yes',
			'enable_breadcrumbs' => 'yes',
			'enable_sitelinks_search' => 'yes',
			'schema_output_location' => 'head',
		);

		foreach ( $defaults as $key => $value ) {
			add_option( 'bw_schema_' . $key, $value );
		}

		// Set plugin version
		update_option( 'bw_schema_version', BW_SCHEMA_VERSION );
	}
	
	/**
	 * Get detected schema sources
	 */
	public static function detect_schema_sources() {
		$sources = array();
		
		// Check for popular SEO plugins
		if ( defined( 'WPSEO_VERSION' ) ) {
			$sources['yoast'] = array(
				'name' => 'Yoast SEO',
				'active' => get_option( 'wpseo_titles' ) && ! empty( get_option( 'wpseo_titles' )['company_or_person'] ),
				'type' => 'plugin'
			);
		}
		
		if ( defined( 'AIOSEO_VERSION' ) ) {
			$sources['aioseo'] = array(
				'name' => 'All in One SEO',
				'active' => true,
				'type' => 'plugin'
			);
		}
		
		if ( defined( 'SEOPRESS_VERSION' ) ) {
			$sources['seopress'] = array(
				'name' => 'SEOPress',
				'active' => get_option( 'seopress_titles_option_name' ),
				'type' => 'plugin'
			);
		}
		
		if ( class_exists( 'RankMath' ) ) {
			$sources['rankmath'] = array(
				'name' => 'Rank Math SEO',
				'active' => get_option( 'rank-math-options-titles' ),
				'type' => 'plugin'
			);
		}
		
		// Check for WooCommerce
		if ( class_exists( 'WooCommerce' ) ) {
			$sources['woocommerce'] = array(
				'name' => 'WooCommerce',
				'active' => true,
				'type' => 'plugin'
			);
		}
		
		// Check for theme schema
		$theme = wp_get_theme();
		if ( current_theme_supports( 'schema' ) || current_theme_supports( 'structured-data' ) ) {
			$sources['theme'] = array(
				'name' => $theme->get( 'Name' ),
				'active' => true,
				'type' => 'theme'
			);
		}
		
		return $sources;
	}
	
	/**
	 * Disable other schema sources
	 */
	public static function disable_conflicting_schema() {
		$disable_sources = get_option( 'bw_schema_disable_sources', array() );
		
		if ( empty( $disable_sources ) ) {
			return;
		}
		
		// Disable Yoast Schema
		if ( in_array( 'yoast', $disable_sources ) && defined( 'WPSEO_VERSION' ) ) {
			add_filter( 'wpseo_json_ld_output', '__return_false', 99 );
			add_filter( 'wpseo_schema_graph_pieces', '__return_empty_array', 99 );
			add_filter( 'disable_wpseo_json_ld_search', '__return_true' );
		}
		
		// Disable All in One SEO Schema
		if ( in_array( 'aioseo', $disable_sources ) && defined( 'AIOSEO_VERSION' ) ) {
			add_filter( 'aioseo_schema_disable', '__return_true' );
			add_filter( 'aioseo_schema_graphs', '__return_empty_array' );
		}
		
		// Disable SEOPress Schema
		if ( in_array( 'seopress', $disable_sources ) && defined( 'SEOPRESS_VERSION' ) ) {
			add_filter( 'seopress_schemas_jsonld_output', '__return_false' );
		}
		
		// Disable Rank Math Schema
		if ( in_array( 'rankmath', $disable_sources ) && class_exists( 'RankMath' ) ) {
			add_filter( 'rank_math/json_ld', '__return_false', 99 );
			add_filter( 'rank_math/snippet/rich_snippet_scripts', '__return_empty_array' );
		}
		
		// Disable WooCommerce Schema
		if ( in_array( 'woocommerce', $disable_sources ) && class_exists( 'WooCommerce' ) ) {
			add_filter( 'woocommerce_structured_data_product', '__return_empty_array', 99 );
			add_filter( 'woocommerce_structured_data_type_for_page', '__return_empty_string', 99 );
			remove_action( 'wp_footer', array( WC()->structured_data, 'output_structured_data' ), 10 );
		}
		
		// Remove theme schema
		if ( in_array( 'theme', $disable_sources ) ) {
			// Remove common theme schema actions
			remove_action( 'wp_head', 'schema_wp_head', 10 );
			remove_action( 'wp_head', 'theme_output_structured_data', 10 );
			remove_action( 'wp_footer', 'theme_output_structured_data', 10 );
			
			// Filter common theme schema functions
			add_filter( 'theme_structured_data', '__return_empty_array', 99 );
			add_filter( 'get_schema_markup', '__return_false', 99 );
		}
	}
}