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

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

class BW_Schema_Admin {
	
	/**
	 * Add admin menu pages
	 *
	 * All pages are added under Settings menu (options-general.php)
	 */
	public function add_menu_pages() {
		// Main page under Settings menu
		add_options_page(
			__( 'AI Schema Pro', 'bw-ai-schema-pro' ),
			__( 'AI Schema Pro', 'bw-ai-schema-pro' ),
			'manage_options',
			'bw-ai-schema',
			array( $this, 'render_dashboard_page' )
		);

		// Global Settings (hidden - accessed via tab or link from dashboard)
		add_submenu_page(
			null, // Hidden from menu
			__( 'AI Schema Pro - Settings', 'bw-ai-schema-pro' ),
			__( 'Settings', 'bw-ai-schema-pro' ),
			'manage_options',
			'bw-ai-schema-settings',
			array( $this, 'render_settings_page' )
		);

		// Author Profiles (hidden - accessed via tab or link from dashboard)
		add_submenu_page(
			null, // Hidden from menu
			__( 'AI Schema Pro - Author Profiles', 'bw-ai-schema-pro' ),
			__( 'Author Profiles', 'bw-ai-schema-pro' ),
			'manage_options',
			'bw-ai-schema-authors',
			array( $this, 'render_authors_page' )
		);

		// Setup Wizard (hidden from menu but accessible)
		add_submenu_page(
			null, // Hidden from menu
			__( 'AI Schema Pro - Setup Wizard', 'bw-ai-schema-pro' ),
			__( 'Setup Wizard', 'bw-ai-schema-pro' ),
			'manage_options',
			'bw-ai-schema-setup',
			array( $this, 'render_setup_wizard_page' )
		);

	}
	
	/**
	 * Render dashboard page
	 */
	public function render_dashboard_page() {
		// Handle form submission
		if ( isset( $_POST['bw_schema_save_dashboard'] ) && wp_verify_nonce( $_POST['bw_schema_dashboard_nonce'], 'bw_schema_dashboard' ) ) {
			$this->save_dashboard_settings();
		}
		
		include BW_SCHEMA_PLUGIN_DIR . 'admin/views/dashboard.php';
	}
	
	/**
	 * Render settings page
	 */
	public function render_settings_page() {
		// Handle form submission
		if ( isset( $_POST['bw_schema_save_settings'] ) && wp_verify_nonce( $_POST['bw_schema_settings_nonce'], 'bw_schema_settings' ) ) {
			$this->save_settings();
		}
		
		include BW_SCHEMA_PLUGIN_DIR . 'admin/views/settings.php';
	}
	
	/**
	 * Render authors page
	 */
	public function render_authors_page() {
		// Handle plugin-wide default author save (v2.0)
		if ( isset( $_POST['bw_schema_save_plugin_default'] ) && wp_verify_nonce( $_POST['bw_schema_plugin_default_author_nonce'], 'bw_schema_plugin_default_author' ) ) {
			$this->save_plugin_default_author();
		}

		// Handle legacy author migration (v2.0 architecture)
		if ( isset( $_POST['bw_schema_migrate_authors'] ) && wp_verify_nonce( $_POST['bw_schema_migrate_authors_nonce'], 'bw_schema_migrate_authors' ) ) {
			$this->process_author_migration();
		}

		// Handle external author form submissions (v2.0 architecture)
		if ( isset( $_POST['bw_schema_save_external_author'] ) && wp_verify_nonce( $_POST['bw_schema_external_author_nonce'], 'bw_schema_external_author' ) ) {
			$this->save_external_author();
		}

		if ( isset( $_POST['action'] ) && $_POST['action'] === 'bulk-delete-external' && wp_verify_nonce( $_POST['_wpnonce'], 'bulk-external-authors' ) ) {
			$this->bulk_delete_external_authors();
		}

		if ( isset( $_GET['action'] ) && $_GET['action'] === 'delete-external' && wp_verify_nonce( $_GET['_wpnonce'], 'delete_external_author' ) ) {
			$this->delete_external_author( sanitize_text_field( $_GET['external_id'] ) );
		}

		// Legacy support for old custom authors (deprecated in v2.0)
		if ( isset( $_POST['bw_schema_save_author'] ) && wp_verify_nonce( $_POST['bw_schema_author_nonce'], 'bw_schema_author' ) ) {
			$this->save_author();
		}

		if ( isset( $_POST['action'] ) && $_POST['action'] === 'bulk-delete' && wp_verify_nonce( $_POST['_wpnonce'], 'bulk-authors' ) ) {
			$this->bulk_delete_authors();
		}

		if ( isset( $_GET['action'] ) && $_GET['action'] === 'delete' && wp_verify_nonce( $_GET['_wpnonce'], 'delete_author' ) ) {
			$this->delete_author( sanitize_text_field( $_GET['author'] ) );
		}

		include BW_SCHEMA_PLUGIN_DIR . 'admin/views/author-profiles.php';
	}
	
	/**
	 * Render setup wizard page
	 */
	public function render_setup_wizard_page() {
		// Handle form submission
		if ( isset( $_POST['bw_schema_save_setup'] ) && wp_verify_nonce( $_POST['bw_schema_setup_nonce'], 'bw_schema_setup' ) ) {
			$this->save_setup_wizard();
		}

		include BW_SCHEMA_PLUGIN_DIR . 'admin/views/setup-wizard.php';
	}

	/**
	 * Render post meta box
	 */
	public function render_post_meta_box( $post ) {
		wp_nonce_field( 'bw_schema_meta', 'bw_schema_meta_nonce' );
		
		// Get current values
		$schema_type = get_post_meta( $post->ID, '_bw_schema_type', true );
		$custom_schema = get_post_meta( $post->ID, '_bw_schema_custom', true );
		$disable_schema = get_post_meta( $post->ID, '_bw_schema_disable', true );
		$simple_mode = get_post_meta( $post->ID, '_bw_schema_simple_mode', true );
		if ( empty( $simple_mode ) ) $simple_mode = 'yes'; // Default to simple mode
		
		// Get schema types
		$schema_types = BW_Schema_Core::get_schema_types();
		
		// Get post type default
		$defaults = BW_Schema_Core::get_post_type_defaults();
		$default_type = isset( $defaults[$post->post_type] ) ? $defaults[$post->post_type] : '';

		// Get meta box default state setting
		$default_state = get_option( 'bw_schema_metabox_default_state', 'collapsed' );
		$is_expanded = ( $default_state === 'expanded' );
		?>
		<div class="bw-schema-meta-box bw-schema-collapsible-box">
			<!-- Compact Header with Toggle -->
			<div class="bw-schema-box-header">
				<div class="bw-schema-box-summary">
					<span class="bw-schema-current-type">
						<?php
						if ( $schema_type ) {
							$type_parts = explode( ':', $schema_type );
							echo esc_html( isset( $type_parts[1] ) ? $type_parts[1] : $schema_type );
						} else {
							_e( 'Auto-detect', 'bw-ai-schema-pro' );
						}
						?>
					</span>
					<span class="bw-schema-status <?php echo $disable_schema === 'yes' ? 'disabled' : 'enabled'; ?>">
						<?php echo $disable_schema === 'yes' ? __( 'Disabled', 'bw-ai-schema-pro' ) : __( 'Active', 'bw-ai-schema-pro' ); ?>
					</span>
				</div>
				<button type="button" class="bw-schema-toggle-btn" aria-expanded="<?php echo $is_expanded ? 'true' : 'false'; ?>">
					<span class="dashicons dashicons-arrow-down-alt2"></span>
					<span class="screen-reader-text"><?php _e( 'Toggle Schema Settings', 'bw-ai-schema-pro' ); ?></span>
				</button>
			</div>

			<!-- Collapsible Content -->
			<div class="bw-schema-box-content" style="<?php echo $is_expanded ? '' : 'display: none;'; ?>">

			<!-- Mode Switcher -->
			<div class="bw-schema-mode-switcher" style="background: #f0f6fc; padding: 10px; border-radius: 5px; margin-bottom: 20px;">
				<label style="margin-right: 20px;">
					<input type="radio" name="bw_schema_simple_mode" value="yes" <?php checked( $simple_mode, 'yes' ); ?> />
					<strong><?php _e( 'Simple Mode', 'bw-ai-schema-pro' ); ?></strong>
					<span style="color: #666; font-size: 12px;"><?php _e( '(Recommended)', 'bw-ai-schema-pro' ); ?></span>
				</label>
				<label>
					<input type="radio" name="bw_schema_simple_mode" value="no" <?php checked( $simple_mode, 'no' ); ?> />
					<strong><?php _e( 'Advanced Mode', 'bw-ai-schema-pro' ); ?></strong>
					<span style="color: #666; font-size: 12px;"><?php _e( '(JSON Editor)', 'bw-ai-schema-pro' ); ?></span>
				</label>
			</div>

			<!-- Simple Mode -->
			<div id="bw-schema-simple-mode" style="<?php echo $simple_mode === 'yes' ? '' : 'display:none;'; ?>">
				<p>
					<label for="bw_schema_type">
						<strong><?php _e( 'What type of content is this?', 'bw-ai-schema-pro' ); ?></strong>
					</label>
					<select name="bw_schema_type" id="bw_schema_type" class="widefat">
						<option value=""><?php _e( '-- Auto-detect (Recommended) --', 'bw-ai-schema-pro' ); ?></option>
						<?php foreach ( $schema_types as $type_key => $type_data ) : ?>
							<optgroup label="<?php echo esc_attr( $type_data['label'] ); ?>">
								<?php foreach ( $type_data['subtypes'] as $subtype_key => $subtype_label ) : ?>
									<?php $value = $type_key . ':' . $subtype_key; ?>
									<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $schema_type, $value ); ?>>
										<?php echo esc_html( $subtype_label ); ?>
									</option>
								<?php endforeach; ?>
							</optgroup>
						<?php endforeach; ?>
					</select>
				</p>
				
				<!-- Dynamic Simple Fields Based on Schema Type -->
				<div id="bw-schema-simple-fields">
					<!-- These will be populated dynamically based on schema type -->
				</div>
				
				<div class="bw-schema-simple-extras" style="background: #f5f5f5; padding: 15px; border-radius: 5px; margin-top: 20px;">
					<h4 style="margin-top: 0;"><?php _e( '🤖 AI Optimization', 'bw-ai-schema-pro' ); ?></h4>
					
					<p>
						<label for="bw_schema_about_simple">
							<strong><?php _e( 'What is this content about?', 'bw-ai-schema-pro' ); ?></strong>
						</label>
						<input type="text" name="bw_schema_about_entities" id="bw_schema_about_simple" class="widefat" 
							value="<?php echo esc_attr( implode( ', ', (array) get_post_meta( $post->ID, '_bw_schema_about_entities', true ) ) ); ?>" 
							placeholder="<?php _e( 'e.g., Digital Marketing, SEO Strategy, Business Growth', 'bw-ai-schema-pro' ); ?>" />
						<span class="description"><?php _e( 'Help AI understand your main topics (comma-separated)', 'bw-ai-schema-pro' ); ?></span>
					</p>
					
					<!-- Multiple Authors Section -->
					<div class="bw-schema-multiple-authors" style="margin-top: 20px;">
						<h4 style="margin-bottom: 10px;">
							<?php _e( '👥 Authors', 'bw-ai-schema-pro' ); ?>
						</h4>
						
						<div id="bw-schema-authors-container">
							<?php
							$multiple_authors = get_post_meta( $post->ID, '_bw_schema_multiple_authors', true );
							$disable_default_author = get_post_meta( $post->ID, '_bw_schema_disable_default_author', true );
							
							// If no multiple authors, check for legacy single author
							if ( empty( $multiple_authors ) ) {
								$legacy_author = get_post_meta( $post->ID, '_bw_schema_custom_author', true );
								if ( $legacy_author ) {
									$multiple_authors = array(
										array(
											'type' => 'custom',
											'custom_author_id' => $legacy_author
										)
									);
								}
							}
							
							// Always show at least one author field
							if ( empty( $multiple_authors ) ) {
								$multiple_authors = array( array() );
							}
							
							foreach ( $multiple_authors as $index => $author ) {
								$this->render_author_field( $index, $author );
							}
							?>
						</div>
						
						<button type="button" class="button" id="bw-schema-add-author" style="margin-top: 10px;">
							<span class="dashicons dashicons-plus-alt2"></span> <?php _e( 'Add Another Author', 'bw-ai-schema-pro' ); ?>
						</button>
						
						<?php
						// Get global author box settings
						$author_box_enabled = get_option( 'bw_schema_author_box_enabled', 'yes' );
						$enabled_post_types = get_option( 'bw_schema_author_box_post_types', array( 'post' ) );
						$is_supported_post_type = in_array( $post->post_type, $enabled_post_types );

						// Get the saved value for this post (v2.0: 'default', 'show', 'hide')
						$show_author_box = get_post_meta( $post->ID, '_bw_schema_show_author_box', true );

						// Migrate legacy values
						if ( $show_author_box === 'yes' ) {
							$show_author_box = 'show';
						} elseif ( $show_author_box === 'no' ) {
							$show_author_box = 'hide';
						} elseif ( $show_author_box === '' ) {
							$show_author_box = 'default';
						}

						// Determine what the default behavior would be
						$default_would_show = ( $author_box_enabled === 'yes' && $is_supported_post_type );
						?>
						<div style="margin-top: 15px; padding: 15px; background: #f5f5f5; border-radius: 5px;">
							<h4 style="margin: 0 0 10px 0;"><?php _e( 'Author Box', 'bw-ai-schema-pro' ); ?></h4>

							<div style="display: flex; flex-direction: column; gap: 6px;">
								<label style="display: flex; align-items: center; gap: 6px;">
									<input type="radio" name="bw_schema_show_author_box" value="default" <?php checked( $show_author_box, 'default' ); ?>>
									<?php _e( 'Use Default', 'bw-ai-schema-pro' ); ?>
									<span style="color: #666; font-size: 12px;">
										(<?php echo $default_would_show ? __( 'will show', 'bw-ai-schema-pro' ) : __( 'will hide', 'bw-ai-schema-pro' ); ?>)
									</span>
								</label>
								<label style="display: flex; align-items: center; gap: 6px;">
									<input type="radio" name="bw_schema_show_author_box" value="show" <?php checked( $show_author_box, 'show' ); ?>>
									<?php _e( 'Show Author Box', 'bw-ai-schema-pro' ); ?>
								</label>
								<label style="display: flex; align-items: center; gap: 6px;">
									<input type="radio" name="bw_schema_show_author_box" value="hide" <?php checked( $show_author_box, 'hide' ); ?>>
									<?php _e( "Don't Show Author Box", 'bw-ai-schema-pro' ); ?>
								</label>
							</div>

							<p style="margin-top: 10px;">
								<label style="display: flex; align-items: center; gap: 6px;">
									<input type="checkbox" name="bw_schema_disable_default_author" value="1" <?php checked( $disable_default_author, '1' ); ?>>
									<?php _e( 'Hide theme\'s default author display', 'bw-ai-schema-pro' ); ?>
								</label>
							</p>
						</div>
					</div>
				</div>
			</div>
			
			<!-- Advanced Mode -->
			<div id="bw-schema-advanced-mode" style="<?php echo $simple_mode === 'no' ? '' : 'display:none;'; ?>">
				<div class="bw-schema-advanced">
					<p>
						<label for="bw_schema_custom">
							<strong><?php _e( 'Custom Schema JSON-LD:', 'bw-ai-schema-pro' ); ?></strong>
						</label>
						<textarea name="bw_schema_custom" id="bw_schema_custom" class="widefat" rows="10" placeholder='{"@context": "https://schema.org", "@type": "Article", ...}'><?php echo esc_textarea( $custom_schema ); ?></textarea>
						<span class="description"><?php _e( 'Enter custom JSON-LD schema to override automatic generation.', 'bw-ai-schema-pro' ); ?></span>
					</p>
					
					<div class="bw-schema-ai-fields">
						<h4><?php _e( 'Additional AI Fields', 'bw-ai-schema-pro' ); ?></h4>
						
						<p>
							<label for="bw_schema_fact_checked_by">
								<strong><?php _e( 'Fact Checked By:', 'bw-ai-schema-pro' ); ?></strong>
							</label>
							<input type="text" name="bw_schema_fact_checked_by" id="bw_schema_fact_checked_by" class="widefat" 
								value="<?php echo esc_attr( get_post_meta( $post->ID, '_bw_schema_fact_checked_by', true ) ); ?>" 
								placeholder="<?php _e( 'Name of fact checker', 'bw-ai-schema-pro' ); ?>" />
						</p>
						
						<p>
							<label for="bw_schema_last_reviewed">
								<strong><?php _e( 'Last Reviewed Date:', 'bw-ai-schema-pro' ); ?></strong>
							</label>
							<input type="date" name="bw_schema_last_reviewed" id="bw_schema_last_reviewed" 
								value="<?php echo esc_attr( get_post_meta( $post->ID, '_bw_schema_last_reviewed', true ) ); ?>" />
						</p>
					</div>
				</div>
			</div>
			
			<?php if ( $post->post_type === 'page' ) : ?>
			<p style="margin-top: 10px;">
				<label for="bw_schema_is_team_page">
					<input type="checkbox" name="bw_schema_is_team_page" id="bw_schema_is_team_page" value="yes" <?php checked( get_post_meta( $post->ID, '_bw_schema_is_team_page', true ), 'yes' ); ?> />
					<strong><?php _e( 'This is a team page', 'bw-ai-schema-pro' ); ?></strong>
				</label>
				<span class="description" style="display: block; margin-top: 5px; margin-left: 24px;">
					<?php _e( 'Check this if this page displays team members using a query loop. The page will output an ItemList of Person schemas instead of a regular WebPage schema.', 'bw-ai-schema-pro' ); ?>
				</span>
			</p>
			<?php endif; ?>
			
			<p style="margin-top: 10px;">
				<label for="bw_schema_disable">
					<input type="checkbox" name="bw_schema_disable" id="bw_schema_disable" value="yes" <?php checked( $disable_schema, 'yes' ); ?> />
					<?php _e( 'Disable all schema markup for this post', 'bw-ai-schema-pro' ); ?>
				</label>
			</p>
			
			<div class="bw-schema-preview" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd;">
				<button type="button" class="button button-primary" id="bw-schema-preview-btn">
					<span class="dashicons dashicons-search" style="vertical-align: middle;"></span>
					<?php _e( 'Preview in Google Rich Results', 'bw-ai-schema-pro' ); ?>
				</button>
				<button type="button" class="button" id="bw-schema-preview-json-btn">
					<span class="dashicons dashicons-code-standards" style="vertical-align: middle;"></span>
					<?php _e( 'View JSON-LD', 'bw-ai-schema-pro' ); ?>
				</button>
				<div id="bw-schema-preview-output" style="display:none;"></div>
			</div>
			</div><!-- .bw-schema-box-content -->
		</div>
		
		<style>
			/* Collapsible Meta Box Styles */
			.bw-schema-collapsible-box { padding: 0; }
			.bw-schema-box-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 12px 15px;
				background: #f6f7f7;
				border-bottom: 1px solid #ddd;
				cursor: pointer;
				margin: -6px -12px 0;
			}
			.bw-schema-box-header:hover { background: #f0f0f1; }
			.bw-schema-box-summary { display: flex; align-items: center; gap: 12px; }
			.bw-schema-current-type {
				font-weight: 600;
				color: #1d2327;
				font-size: 13px;
			}
			.bw-schema-status {
				font-size: 11px;
				padding: 2px 8px;
				border-radius: 3px;
				text-transform: uppercase;
				font-weight: 500;
			}
			.bw-schema-status.enabled { background: #d4edda; color: #155724; }
			.bw-schema-status.disabled { background: #f8d7da; color: #721c24; }
			.bw-schema-toggle-btn {
				background: none;
				border: none;
				cursor: pointer;
				padding: 5px;
				color: #666;
				transition: transform 0.2s ease;
			}
			.bw-schema-toggle-btn:hover { color: #2271b1; }
			.bw-schema-toggle-btn[aria-expanded="true"] .dashicons { transform: rotate(180deg); }
			.bw-schema-box-content { padding: 15px 0 0; }

			/* Original Styles */
			.bw-schema-meta-box p { margin-bottom: 15px; }
			.bw-schema-advanced { margin-top: 20px; }
			.bw-schema-ai-fields { margin-top: 20px; }
			#bw-schema-preview-output { margin-top: 10px; padding: 15px; background: #f5f5f5; border: 1px solid #ddd; border-radius: 5px; }
			.bw-schema-mode-switcher input[type="radio"] { margin-right: 5px; }
			.bw-schema-simple-field { margin-bottom: 15px; }
			.bw-schema-simple-field label { display: block; margin-bottom: 5px; font-weight: 600; }
			.bw-schema-simple-field input,
			.bw-schema-simple-field select,
			.bw-schema-simple-field textarea { width: 100%; }
			.bw-schema-rich-preview { background: #fff; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }
			.bw-schema-rich-preview h3 { color: #1a0dab; font-size: 18px; margin: 0 0 5px 0; }
			.bw-schema-rich-preview .url { color: #006621; font-size: 14px; }
			.bw-schema-rich-preview .description { color: #545454; font-size: 13px; margin-top: 5px; }
			.bw-schema-rich-preview .metadata { color: #70757a; font-size: 12px; margin-top: 5px; }
		</style>
		
		<script>
		jQuery(document).ready(function($) {
			// Collapsible meta box toggle
			$('.bw-schema-box-header').on('click', function() {
				var $content = $(this).siblings('.bw-schema-box-content');
				var $btn = $(this).find('.bw-schema-toggle-btn');
				var isExpanded = $btn.attr('aria-expanded') === 'true';

				if (isExpanded) {
					$content.slideUp(200);
					$btn.attr('aria-expanded', 'false');
				} else {
					$content.slideDown(200);
					$btn.attr('aria-expanded', 'true');
				}
			});

			// Update summary when schema type changes
			$('#bw_schema_type').on('change', function() {
				var val = $(this).val();
				var displayText = val ? val.split(':')[1] || val : '<?php _e( "Auto-detect", "bw-ai-schema-pro" ); ?>';
				$('.bw-schema-current-type').text(displayText);
			});

			// Update status when disable checkbox changes
			$('#bw_schema_disable').on('change', function() {
				var $status = $('.bw-schema-status');
				if ($(this).is(':checked')) {
					$status.removeClass('enabled').addClass('disabled').text('<?php _e( "Disabled", "bw-ai-schema-pro" ); ?>');
				} else {
					$status.removeClass('disabled').addClass('enabled').text('<?php _e( "Active", "bw-ai-schema-pro" ); ?>');
				}
			});

			// Mode switcher
			$('input[name="bw_schema_mode"]').on('change', function() {
				if ($(this).val() === 'simple') {
					$('#bw-schema-simple-mode').show();
					$('#bw-schema-advanced-mode').hide();
					$('input[name="bw_schema_simple_mode"]').val('yes');
				} else {
					$('#bw-schema-simple-mode').hide();
					$('#bw-schema-advanced-mode').show();
					$('input[name="bw_schema_simple_mode"]').val('no');
				}
			});

			// Dynamic simple fields based on schema type
			$('#bw_schema_type').on('change', function() {
				var type = $(this).val();
				if (!type) return;
				
				// Load type-specific simple fields
				$.post(ajaxurl, {
					action: 'bw_schema_get_simple_fields',
					type: type,
					post_id: <?php echo $post->ID; ?>,
					nonce: '<?php echo wp_create_nonce( 'bw_schema_nonce' ); ?>'
				}, function(response) {
					if (response.success) {
						$('#bw-schema-simple-fields').html(response.data);
					}
				});
			});
			
			// Trigger change on load if type is selected
			if ($('#bw_schema_type').val()) {
				$('#bw_schema_type').trigger('change');
			}
			
			// Multiple Authors functionality
			var authorIndex = $('.bw-schema-author-item').length;
			
			// Add author
			$('#bw-schema-add-author').on('click', function() {
				var newAuthor = $('<div class="bw-schema-author-item" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 10px; background: #f9f9f9; position: relative;"></div>');
				
				// Clone the first author item structure but with new index
				var firstAuthor = $('.bw-schema-author-item').first().clone();
				firstAuthor.find('input, select, textarea').each(function() {
					var name = $(this).attr('name');
					if (name) {
						$(this).attr('name', name.replace(/\[\d+\]/, '[' + authorIndex + ']'));
						$(this).val(''); // Clear values
					}
				});
				
				// Reset to first available type (v2.0: team_member > external_saved > external)
				var $typeSelect = firstAuthor.find('select.bw-schema-author-type');
				var defaultType = $typeSelect.find('option:first').val();
				$typeSelect.val(defaultType);
				firstAuthor.find('.bw-schema-author-fields').hide();
				firstAuthor.find('.bw-schema-author-' + defaultType).show();
				
				// Add remove button if not present
				if (firstAuthor.find('.bw-schema-remove-author').length === 0) {
					firstAuthor.find('div:first').append('<button type="button" class="button bw-schema-remove-author" style="color: #a00;"><span class="dashicons dashicons-trash"></span> Remove</button>');
				}
				
				$('#bw-schema-authors-container').append(firstAuthor);
				authorIndex++;
				
				// Trigger change event to initialize
				firstAuthor.find('.bw-schema-author-type').trigger('change');
			});
			
			// Remove author
			$(document).on('click', '.bw-schema-remove-author', function() {
				$(this).closest('.bw-schema-author-item').fadeOut(300, function() {
					$(this).remove();
				});
			});
			
			// Toggle author type fields
			$(document).on('change', '.bw-schema-author-type', function() {
				var $container = $(this).closest('.bw-schema-author-item');
				var type = $(this).val();
				
				$container.find('.bw-schema-author-fields').hide();
				$container.find('.bw-schema-author-' + type).show();
			});
			
			// Toggle external author advanced fields
			$(document).on('click', '.bw-schema-toggle-external-fields', function() {
				var $advanced = $(this).siblings('.bw-schema-author-external-advanced');
				
				if ($advanced.is(':visible')) {
					$advanced.slideUp();
					$(this).text('<?php _e( 'Show Advanced Fields', 'bw-ai-schema-pro' ); ?>');
				} else {
					$advanced.slideDown();
					$(this).text('<?php _e( 'Hide Advanced Fields', 'bw-ai-schema-pro' ); ?>');
				}
			});
			
			// Initialize existing author fields
			$('.bw-schema-author-type').trigger('change');
		});
		</script>
		
		<input type="hidden" name="bw_schema_simple_mode" value="<?php echo esc_attr( $simple_mode ); ?>" />
		<?php
	}

	/**
	 * Save settings
	 */
	private function save_settings() {
		// Note: Most settings are now configured in the Setup Wizard.
		// This page only saves advanced organization details and display settings.

		// Get existing organization data to preserve wizard-configured fields
		$org_data = get_option( 'bw_schema_organization', array() );

		// Update only the advanced fields (preserve existing basic fields from wizard)
		$org_data['alternateName'] = sanitize_text_field( $_POST['org_alternate_name'] ?? '' );
		$org_data['legalName'] = sanitize_text_field( $_POST['org_legal_name'] ?? '' );
		$org_data['taxID'] = sanitize_text_field( $_POST['org_tax_id'] ?? '' );
		$org_data['duns'] = sanitize_text_field( $_POST['org_duns'] ?? '' );
		$org_data['slogan'] = sanitize_text_field( $_POST['org_slogan'] ?? '' );

		// Process areas served (comma-separated to array)
		if ( isset( $_POST['org_areas_served'] ) ) {
			if ( ! empty( $_POST['org_areas_served'] ) ) {
				$areas = array_map( 'trim', explode( ',', sanitize_text_field( $_POST['org_areas_served'] ) ) );
				$org_data['areaServed'] = array_filter( $areas );
			} else {
				$org_data['areaServed'] = array();
			}
		}

		// Process services/products offered (comma-separated to array)
		if ( isset( $_POST['org_services'] ) ) {
			if ( ! empty( $_POST['org_services'] ) ) {
				$services = array_map( 'trim', explode( ',', sanitize_textarea_field( $_POST['org_services'] ) ) );
				$org_data['makesOffer'] = array_filter( $services );
			} else {
				$org_data['makesOffer'] = array();
			}
		}

		update_option( 'bw_schema_organization', $org_data );

		// Save author box settings
		update_option( 'bw_schema_author_box_enabled', isset( $_POST['author_box_enabled'] ) ? 'yes' : 'no' );
		
		// Save author box post types
		if ( isset( $_POST['author_box_post_types'] ) && is_array( $_POST['author_box_post_types'] ) ) {
			$post_types = array_map( 'sanitize_text_field', $_POST['author_box_post_types'] );
			update_option( 'bw_schema_author_box_post_types', $post_types );
		} else {
			update_option( 'bw_schema_author_box_post_types', array() );
		}
		
		// Save author box position
		if ( isset( $_POST['author_box_position'] ) ) {
			$allowed_positions = array( 'after_content', 'before_content', 'manual' );
			$position = sanitize_text_field( $_POST['author_box_position'] );
			if ( in_array( $position, $allowed_positions ) ) {
				update_option( 'bw_schema_author_box_position', $position );
			}
		}

		// Save author archive redirect setting
		update_option( 'bw_schema_redirect_author_archives', isset( $_POST['redirect_author_archives'] ) ? 'yes' : 'no' );

		// Save meta box display settings
		if ( isset( $_POST['metabox_position'] ) ) {
			$allowed_positions = array( 'normal', 'side' );
			$position = sanitize_text_field( $_POST['metabox_position'] );
			if ( in_array( $position, $allowed_positions ) ) {
				update_option( 'bw_schema_metabox_position', $position );
			}
		}

		if ( isset( $_POST['metabox_default_state'] ) ) {
			$allowed_states = array( 'collapsed', 'expanded' );
			$state = sanitize_text_field( $_POST['metabox_default_state'] );
			if ( in_array( $state, $allowed_states ) ) {
				update_option( 'bw_schema_metabox_default_state', $state );
			}
		}

		if ( isset( $_POST['metabox_post_types'] ) && is_array( $_POST['metabox_post_types'] ) ) {
			$post_types = array_map( 'sanitize_text_field', $_POST['metabox_post_types'] );
			update_option( 'bw_schema_metabox_post_types', $post_types );
		} else {
			// If none selected, save empty array
			update_option( 'bw_schema_metabox_post_types', array() );
		}

		// Add success message
		add_settings_error( 'bw_schema_settings', 'settings_saved', __( 'Settings saved successfully!', 'bw-ai-schema-pro' ), 'success' );
	}
	
	/**
	 * Save post type settings
	 */
	private function save_post_type_settings() {
		if ( isset( $_POST['post_type_defaults'] ) && is_array( $_POST['post_type_defaults'] ) ) {
			$defaults = array();
			foreach ( $_POST['post_type_defaults'] as $post_type => $schema_type ) {
				if ( ! empty( $schema_type ) ) {
					$defaults[$post_type] = sanitize_text_field( $schema_type );
				}
			}
			update_option( 'bw_schema_post_type_defaults', $defaults );
		}
		
		// Add success message
		add_settings_error( 'bw_schema_post_types', 'settings_saved', __( 'Post type settings saved successfully!', 'bw-ai-schema-pro' ), 'success' );
	}
	
	/**
	 * Save dashboard settings
	 */
	private function save_dashboard_settings() {
		// Save post type defaults
		if ( isset( $_POST['post_type_defaults'] ) && is_array( $_POST['post_type_defaults'] ) ) {
			$defaults = array();
			foreach ( $_POST['post_type_defaults'] as $post_type => $schema_type ) {
				if ( ! empty( $schema_type ) ) {
					$defaults[$post_type] = sanitize_text_field( $schema_type );
				}
			}
			update_option( 'bw_schema_post_type_defaults', $defaults );
		}
		
		// Add success message
		add_settings_error( 'bw_schema_dashboard', 'settings_saved', __( 'Settings saved successfully!', 'bw-ai-schema-pro' ), 'success' );
	}
	
	/**
	 * Save setup wizard data
	 */
	private function save_setup_wizard() {
		$current_step = isset( $_POST['setup_step'] ) ? intval( $_POST['setup_step'] ) : 1;
		
		// Save step 1 - Organization Profile
		if ( $current_step === 1 ) {
			// Get existing org data to preserve sameAs (set in Step 3)
			$existing_org = get_option( 'bw_schema_organization', array() );
			$existing_sameas = isset( $existing_org['sameAs'] ) ? $existing_org['sameAs'] : array();

			// Organization data - preserve existing sameAs
			$org_data = array(
				'name' => sanitize_text_field( $_POST['org_name'] ),
				'url' => esc_url_raw( $_POST['org_url'] ),
				'logo' => esc_url_raw( $_POST['org_logo'] ?? '' ),
				'telephone' => sanitize_text_field( $_POST['org_telephone'] ?? '' ),
				'email' => sanitize_email( $_POST['org_email'] ?? '' ),
				'sameAs' => $existing_sameas,
			);

			// Areas served (comma-separated to array)
			if ( ! empty( $_POST['org_areas_served'] ) ) {
				$areas = array_map( 'trim', explode( ',', sanitize_text_field( $_POST['org_areas_served'] ) ) );
				$org_data['areaServed'] = array_filter( $areas );
			} else {
				$org_data['areaServed'] = array();
			}

			// Services/products offered (comma-separated to array)
			if ( ! empty( $_POST['org_services'] ) ) {
				$services = array_map( 'trim', explode( ',', sanitize_textarea_field( $_POST['org_services'] ) ) );
				$org_data['makesOffer'] = array_filter( $services );
			} else {
				$org_data['makesOffer'] = array();
			}

			update_option( 'bw_schema_organization', $org_data );

			// Business details
			update_option( 'bw_schema_business_type', sanitize_text_field( $_POST['business_type'] ) );
			update_option( 'bw_schema_schema_org_type', sanitize_text_field( $_POST['schema_org_type'] ?? '' ) );
			update_option( 'bw_schema_org_description', sanitize_textarea_field( $_POST['org_description'] ?? '' ) );
			update_option( 'bw_schema_founding_date', sanitize_text_field( $_POST['founding_date'] ?? '' ) );
			update_option( 'bw_schema_employee_count', intval( $_POST['employee_count'] ?? 0 ) );

			// Price range
			update_option( 'bw_schema_enable_price_range', isset( $_POST['enable_price_range'] ) ? 'yes' : 'no' );
			update_option( 'bw_schema_price_range', sanitize_text_field( $_POST['org_price_range'] ?? '' ) );
		}
		
		// Save step 2 - People (v2.0)
		elseif ( $current_step === 2 ) {
			// Team post type configuration
			$team_post_type = sanitize_text_field( $_POST['team_post_type'] ?? '' );
			update_option( 'bw_schema_team_post_type', $team_post_type );

			// Also save to consolidated settings (fixes template clone issue)
			$settings = get_option( 'bw_schema_settings', array() );
			if ( ! isset( $settings['content'] ) ) {
				$settings['content'] = array();
			}
			$settings['content']['team_post_type'] = $team_post_type;
			update_option( 'bw_schema_settings', $settings );

			// Team member flags (Is Author, Is Leader, Linked User)
			if ( $team_post_type ) {
				$team_members = get_posts( array(
					'post_type'      => $team_post_type,
					'posts_per_page' => -1,
					'post_status'    => 'publish',
				) );

				foreach ( $team_members as $tm ) {
					// Is Author
					$is_author = isset( $_POST['team_member_is_author'][ $tm->ID ] ) ? '1' : '';
					update_post_meta( $tm->ID, '_bw_schema_is_author', $is_author );

					// Is Leader
					$is_leader = isset( $_POST['team_member_is_leader'][ $tm->ID ] ) ? '1' : '';
					update_post_meta( $tm->ID, '_bw_schema_is_leader', $is_leader );

					// Linked WordPress User
					$linked_user = isset( $_POST['team_member_linked_user'][ $tm->ID ] ) ? intval( $_POST['team_member_linked_user'][ $tm->ID ] ) : '';
					update_post_meta( $tm->ID, '_bw_schema_linked_user', $linked_user );
				}
			}

			// WordPress User default authors
			if ( isset( $_POST['user_default_author'] ) && is_array( $_POST['user_default_author'] ) ) {
				foreach ( $_POST['user_default_author'] as $user_id => $default_value ) {
					$user_id = intval( $user_id );
					if ( ! $user_id ) continue;

					if ( empty( $default_value ) ) {
						delete_user_meta( $user_id, 'bw_schema_default_author' );
					} else {
						// Parse "type:id" format
						$parts = explode( ':', $default_value, 2 );
						if ( count( $parts ) === 2 ) {
							$author_data = array(
								'type' => sanitize_text_field( $parts[0] ),
								'id'   => $parts[0] === 'team_member' ? intval( $parts[1] ) : sanitize_text_field( $parts[1] ),
							);
							update_user_meta( $user_id, 'bw_schema_default_author', $author_data );
						}
					}
				}
			}

			// Awards & Certifications (organization-level)
			$awards = array_filter( array_map( 'sanitize_text_field', $_POST['awards'] ?? array() ) );
			$certifications = array_filter( array_map( 'sanitize_text_field', $_POST['certifications'] ?? array() ) );

			update_option( 'bw_schema_awards', $awards );
			update_option( 'bw_schema_certifications', $certifications );
		}
		
		// Save step 3 - Contact & Social
		elseif ( $current_step === 3 ) {
			// Get existing org_data with proper defaults
			$org_data = get_option( 'bw_schema_organization', array(
				'name' => get_bloginfo( 'name' ),
				'url' => home_url(),
				'logo' => '',
				'telephone' => '',
				'email' => '',
				'sameAs' => array(),
			) );

			// Ensure we have proper structure
			if ( ! isset( $org_data['name'] ) ) {
				$org_data['name'] = get_bloginfo( 'name' );
			}
			if ( ! isset( $org_data['url'] ) ) {
				$org_data['url'] = home_url();
			}

			// Update sameAs (social profiles)
			$org_data['sameAs'] = array();
			if ( isset( $_POST['org_sameas'] ) && is_array( $_POST['org_sameas'] ) ) {
				foreach ( $_POST['org_sameas'] as $url ) {
					$url = trim( $url );
					if ( ! empty( $url ) ) {
						$org_data['sameAs'][] = esc_url_raw( $url );
					}
				}
			}

			update_option( 'bw_schema_organization', $org_data );
			
			// Physical address
			if ( isset( $_POST['address'] ) && is_array( $_POST['address'] ) ) {
				$address = array(
					'street' => sanitize_text_field( $_POST['address']['street'] ?? '' ),
					'city' => sanitize_text_field( $_POST['address']['city'] ?? '' ),
					'state' => sanitize_text_field( $_POST['address']['state'] ?? '' ),
					'postal' => sanitize_text_field( $_POST['address']['postal'] ?? '' ),
					'country' => sanitize_text_field( $_POST['address']['country'] ?? '' ),
				);
				update_option( 'bw_schema_address', $address );
			}
			
			// Contact points
			$contact_points = array();
			if ( isset( $_POST['contact_points'] ) && is_array( $_POST['contact_points'] ) ) {
				foreach ( $_POST['contact_points'] as $contact ) {
					if ( ! empty( $contact['type'] ) || ! empty( $contact['telephone'] ) || ! empty( $contact['email'] ) ) {
						$contact_points[] = array(
							'type' => sanitize_text_field( $contact['type'] ?? '' ),
							'telephone' => sanitize_text_field( $contact['telephone'] ?? '' ),
							'email' => sanitize_email( $contact['email'] ?? '' ),
						);
					}
				}
			}
			update_option( 'bw_schema_contact_points', $contact_points );
		}
		
		// Save step 4 - Page Mapping
		elseif ( $current_step === 4 ) {
			if ( isset( $_POST['page_mappings'] ) && is_array( $_POST['page_mappings'] ) ) {
				$mappings = array();
				foreach ( $_POST['page_mappings'] as $type => $page_id ) {
					$mappings[$type] = intval( $page_id );
				}
				update_option( 'bw_schema_page_mappings', $mappings );
			}
		}
		
		// Save step 5 - Content Defaults
		elseif ( $current_step === 5 ) {
			// Post type defaults
			if ( isset( $_POST['post_type_defaults'] ) && is_array( $_POST['post_type_defaults'] ) ) {
				$defaults = array();
				foreach ( $_POST['post_type_defaults'] as $post_type => $schema_type ) {
					if ( ! empty( $schema_type ) ) {
						$defaults[$post_type] = sanitize_text_field( $schema_type );
					}
				}
				update_option( 'bw_schema_post_type_defaults', $defaults );
			}

			// Taxonomy-based schema mappings
			// Always update, even if empty (to clear old mappings when all toggles are off)
			$mappings = array();
			if ( isset( $_POST['taxonomy_mappings'] ) && is_array( $_POST['taxonomy_mappings'] ) ) {
				foreach ( $_POST['taxonomy_mappings'] as $post_type => $mapping ) {
					$post_type = sanitize_key( $post_type );
					$taxonomy = sanitize_key( $mapping['taxonomy'] ?? '' );

					if ( empty( $taxonomy ) ) {
						continue; // Skip if no taxonomy selected (toggle unchecked)
					}

					$term_mappings = array();
					if ( isset( $mapping['term_mappings'] ) && is_array( $mapping['term_mappings'] ) ) {
						foreach ( $mapping['term_mappings'] as $term_slug => $schema_type ) {
							$term_slug = sanitize_key( $term_slug );
							$schema_type = sanitize_text_field( $schema_type );
							if ( ! empty( $schema_type ) ) {
								$term_mappings[ $term_slug ] = $schema_type;
							}
						}
					}

					$mappings[ $post_type ] = array(
						'taxonomy' => $taxonomy,
						'term_mappings' => $term_mappings,
					);
				}
			}
			BW_Schema_Core::update_taxonomy_mappings( $mappings );

			// AI Optimization
			update_option( 'bw_schema_publishing_principles', esc_url_raw( $_POST['publishing_principles'] ?? '' ) );
			update_option( 'bw_schema_fact_checking_policy', esc_url_raw( $_POST['fact_checking_policy'] ?? '' ) );
		}
		
		// Save step 6 - Schema Features
		elseif ( $current_step === 6 ) {
			update_option( 'bw_schema_enable_schema', isset( $_POST['enable_schema'] ) ? 'yes' : 'no' );
			update_option( 'bw_schema_enable_breadcrumbs', isset( $_POST['enable_breadcrumbs'] ) ? 'yes' : 'no' );
			update_option( 'bw_schema_enable_sitelinks_search', isset( $_POST['enable_sitelinks_search'] ) ? 'yes' : 'no' );
			update_option( 'bw_schema_enable_cache', isset( $_POST['enable_cache'] ) ? 'yes' : 'no' );

			// Homepage organization schema
			update_option( 'bw_schema_output_org_homepage', isset( $_POST['output_org_homepage'] ) ? 'yes' : 'no' );

			// Note: Team member post type is now configured in Step 2 (People)

			// Conflict management
			$disabled_sources = isset( $_POST['disable_sources'] ) ? array_map( 'sanitize_text_field', $_POST['disable_sources'] ) : array();
			update_option( 'bw_schema_disable_sources', $disabled_sources );
		}
		
		// Save step 7 - Review & Complete
		elseif ( $current_step === 7 ) {
			// Mark setup as complete
			update_option( 'bw_schema_setup_complete', true );
			
			// Clear any existing organization override since we're using proper settings now
			delete_option( 'bw_schema_organization_override' );
			
			// Redirect to dashboard with success message
			if ( isset( $_POST['complete_setup'] ) ) {
				wp_redirect( admin_url( 'options-general.php?page=bw-ai-schema&setup_complete=1' ) );
				exit;
			}
		}

		// Handle navigation
		if ( isset( $_POST['save_and_continue'] ) && $current_step < 7 ) {
			wp_redirect( admin_url( 'options-general.php?page=bw-ai-schema-setup&step=' . ( $current_step + 1 ) ) );
			exit;
		}
	}
	
	/**
	 * Save author
	 */
	private function save_author() {
		$authors = get_option( 'bw_schema_custom_authors', array() );
		
		// Create author data
		$author_data = array(
			'id' => isset( $_POST['author_id'] ) ? sanitize_text_field( $_POST['author_id'] ) : time(),
			'name' => sanitize_text_field( $_POST['author_name'] ),
			'jobTitle' => sanitize_text_field( $_POST['author_job_title'] ?? '' ),
			'credentials' => sanitize_text_field( $_POST['author_credentials'] ?? '' ),
			'description' => sanitize_textarea_field( $_POST['author_description'] ?? '' ),
			'image' => esc_url_raw( $_POST['author_image'] ?? '' ),
			'email' => sanitize_email( $_POST['author_email'] ?? '' ),
			'expertise' => sanitize_text_field( $_POST['author_expertise'] ?? '' ),
			'affiliations' => sanitize_text_field( $_POST['author_affiliations'] ?? '' ),
			'alumniOf' => sanitize_text_field( $_POST['author_alumni'] ?? '' ),
			'social' => array(
				'facebook' => esc_url_raw( $_POST['author_facebook'] ?? '' ),
				'twitter' => esc_url_raw( $_POST['author_twitter'] ?? '' ),
				'linkedin' => esc_url_raw( $_POST['author_linkedin'] ?? '' ),
				'instagram' => esc_url_raw( $_POST['author_instagram'] ?? '' ),
				'website' => esc_url_raw( $_POST['author_website'] ?? '' ),
				'youtube' => esc_url_raw( $_POST['author_youtube'] ?? '' ),
			),
			'teamPageId' => 0,
			'teamPageUrl' => '',
			'isDefault' => isset( $_POST['author_default'] ) ? true : false,
		);
		
		// Handle team page link based on link type
		if ( isset( $_POST['author_link_type'] ) && $_POST['author_link_type'] === 'external' ) {
			// External URL
			$author_data['teamPageUrl'] = esc_url_raw( $_POST['author_team_url'] ?? '' );
			$author_data['teamPageId'] = 'custom'; // Mark as custom URL
		} else {
			// Internal page/post
			$author_data['teamPageId'] = ! empty( $_POST['author_team_page'] ) ? intval( $_POST['author_team_page'] ) : 0;
			$author_data['teamPageUrl'] = ''; // Clear any external URL
		}
		
		// If setting as default, unset all other defaults
		if ( $author_data['isDefault'] ) {
			foreach ( $authors as &$author ) {
				$author['isDefault'] = false;
			}
		}
		
		// Check if updating existing author
		$found = false;
		foreach ( $authors as $key => $author ) {
			if ( $author['id'] == $author_data['id'] ) {
				$authors[$key] = $author_data;
				$found = true;
				break;
			}
		}
		
		// Add new author if not found
		if ( ! $found ) {
			$authors[] = $author_data;
		}
		
		// Save authors
		update_option( 'bw_schema_custom_authors', $authors );
		
		// Save author preference
		if ( isset( $_POST['use_custom_authors'] ) ) {
			update_option( 'bw_schema_use_custom_authors', sanitize_text_field( $_POST['use_custom_authors'] ) );
		}
		
		// Redirect to prevent form resubmission
		wp_redirect( admin_url( 'options-general.php?page=bw-ai-schema-authors&message=saved' ) );
		exit;
	}

	/**
	 * Delete single author
	 */
	private function delete_author( $author_id ) {
		$authors = get_option( 'bw_schema_custom_authors', array() );

		// Remove author
		foreach ( $authors as $key => $author ) {
			if ( $author['id'] == $author_id ) {
				unset( $authors[$key] );
				break;
			}
		}

		// Re-index array
		$authors = array_values( $authors );

		// Save updated authors
		update_option( 'bw_schema_custom_authors', $authors );

		// Redirect
		wp_redirect( admin_url( 'options-general.php?page=bw-ai-schema-authors&message=deleted' ) );
		exit;
	}

	/**
	 * Bulk delete authors
	 */
	private function bulk_delete_authors() {
		if ( ! isset( $_POST['authors'] ) || ! is_array( $_POST['authors'] ) ) {
			return;
		}

		$authors = get_option( 'bw_schema_custom_authors', array() );
		$to_delete = array_map( 'sanitize_text_field', $_POST['authors'] );

		// Remove selected authors
		foreach ( $authors as $key => $author ) {
			if ( in_array( $author['id'], $to_delete ) ) {
				unset( $authors[$key] );
			}
		}

		// Re-index array
		$authors = array_values( $authors );

		// Save updated authors
		update_option( 'bw_schema_custom_authors', $authors );

		// Redirect
		wp_redirect( admin_url( 'options-general.php?page=bw-ai-schema-authors&message=bulk_deleted' ) );
		exit;
	}
	
	/**
	 * Render a single author field for multiple authors (v2.0 architecture)
	 *
	 * Supports three author types:
	 * - team_member: From Team Member CPT (flagged as author)
	 * - external_saved: From plugin's External Authors storage
	 * - external: One-time/ad-hoc author (data stored in post meta)
	 */
	private function render_author_field( $index, $author_data = array() ) {
		// Get team post type and team member authors
		$team_post_type = class_exists( 'BW_Schema_Team_Member' ) ? BW_Schema_Team_Member::get_team_post_type() : null;
		$team_member_authors = array();
		if ( $team_post_type ) {
			$team_member_authors = get_posts( array(
				'post_type'      => $team_post_type,
				'posts_per_page' => -1,
				'meta_query'     => array(
					array(
						'key'   => '_bw_schema_is_author',
						'value' => '1',
					),
				),
				'orderby'        => 'title',
				'order'          => 'ASC',
			) );
		}

		// Get external authors (v2.0 stored externals)
		$external_authors = get_option( 'bw_schema_external_authors', array() );

		// Determine the type - check for existing data first, then apply default
		$type = isset( $author_data['type'] ) ? $author_data['type'] : '';

		// Check if the type has a valid corresponding ID
		// If type is set but ID is missing, treat as invalid and apply fallback
		$has_valid_author = false;
		if ( $type === 'team_member' && ! empty( $author_data['team_member_id'] ) ) {
			$has_valid_author = true;
		} elseif ( $type === 'external_saved' && ! empty( $author_data['external_author_id'] ) ) {
			$has_valid_author = true;
		} elseif ( $type === 'external' && ! empty( $author_data['external']['name'] ) ) {
			$has_valid_author = true;
		} elseif ( $type === 'wordpress' && ! empty( $author_data['wordpress_user_id'] ) ) {
			$has_valid_author = true;
		} elseif ( $type === 'custom' && ! empty( $author_data['custom_author_id'] ) ) {
			$has_valid_author = true;
		}

		// For posts with no valid author (index 0), apply default author chain:
		// 1. User's personal default author
		// 2. Plugin-wide default author
		// 3. First available author type
		if ( ! $has_valid_author && $index === 0 ) {
			// Reset type since it was invalid
			$type = '';
			// Try user's personal default first
			$current_user_id = get_current_user_id();
			$default_author = get_user_meta( $current_user_id, 'bw_schema_default_author', true );
			if ( ! empty( $default_author ) && is_array( $default_author ) ) {
				$type = $default_author['type'];
				// Pre-populate the ID based on default
				if ( $type === 'team_member' && ! isset( $author_data['team_member_id'] ) ) {
					$author_data['team_member_id'] = $default_author['id'];
				} elseif ( $type === 'external_saved' && ! isset( $author_data['external_author_id'] ) ) {
					$author_data['external_author_id'] = $default_author['id'];
				}
			}

			// Fallback to plugin-wide default if no personal default
			if ( empty( $type ) ) {
				$plugin_default = get_option( 'bw_schema_plugin_default_author', array() );
				if ( ! empty( $plugin_default ) && ! empty( $plugin_default['type'] ) && ! empty( $plugin_default['id'] ) ) {
					$plugin_type = $plugin_default['type'];
					$plugin_id   = $plugin_default['id'];

					// Map plugin default types to author field types
					if ( $plugin_type === 'team_member' ) {
						// Validate team member still exists and is an author
						$is_author = get_post_meta( $plugin_id, '_bw_schema_is_author', true );
						if ( $is_author === '1' ) {
							$type = 'team_member';
							$author_data['team_member_id'] = $plugin_id;
						}
					} elseif ( $plugin_type === 'external' ) {
						// Validate external author still exists
						if ( isset( $external_authors[ $plugin_id ] ) ) {
							$type = 'external_saved';
							$author_data['external_author_id'] = $plugin_id;
						}
					}
				}
			}
		}

		// Final fallback: first available author type
		if ( empty( $type ) ) {
			$type = ! empty( $team_member_authors ) ? 'team_member' : 'external';
		}
		?>
		<div class="bw-schema-author-item" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 10px; background: #f9f9f9; position: relative;">
			<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
				<select name="bw_schema_authors[<?php echo $index; ?>][type]" class="bw-schema-author-type">
					<?php if ( ! empty( $team_member_authors ) ) : ?>
					<option value="team_member" <?php selected( $type, 'team_member' ); ?>><?php _e( 'Team Member Author', 'bw-ai-schema-pro' ); ?></option>
					<?php endif; ?>
					<?php if ( ! empty( $external_authors ) ) : ?>
					<option value="external_saved" <?php selected( $type, 'external_saved' ); ?>><?php _e( 'External Author', 'bw-ai-schema-pro' ); ?></option>
					<?php endif; ?>
					<option value="external" <?php selected( $type, 'external' ); ?>><?php _e( 'External (One-time)', 'bw-ai-schema-pro' ); ?></option>
				</select>

				<?php if ( $index > 0 ) : ?>
				<button type="button" class="button bw-schema-remove-author" style="color: #a00;">
					<span class="dashicons dashicons-trash"></span> <?php _e( 'Remove', 'bw-ai-schema-pro' ); ?>
				</button>
				<?php endif; ?>
			</div>

			<!-- Team Member Author Fields -->
			<?php if ( ! empty( $team_member_authors ) ) : ?>
			<div class="bw-schema-author-fields bw-schema-author-team_member" style="display: none;">
				<?php
				// Determine the selected team member ID
				// If no team_member_id is set, use the first team member as default (never allow empty)
				$selected_team_member_id = isset( $author_data['team_member_id'] ) && ! empty( $author_data['team_member_id'] )
					? $author_data['team_member_id']
					: $team_member_authors[0]->ID; // Default to first team member
				?>
				<select name="bw_schema_authors[<?php echo $index; ?>][team_member_id]" class="widefat" required>
					<?php foreach ( $team_member_authors as $member ) :
						$job_title_data = BW_Schema_Team_Member::detect_job_title( $member );
						$job_title      = is_array( $job_title_data ) ? ( $job_title_data['value'] ?? '' ) : $job_title_data;
					?>
						<option value="<?php echo esc_attr( $member->ID ); ?>" <?php selected( $selected_team_member_id, $member->ID ); ?>>
							<?php echo esc_html( $member->post_title ); ?>
							<?php if ( ! empty( $job_title ) ) : ?>
								- <?php echo esc_html( $job_title ); ?>
							<?php endif; ?>
						</option>
					<?php endforeach; ?>
				</select>
				<p class="description" style="margin-top: 5px;">
					<?php printf(
						__( 'Manage team member authors in <a href="%s">Authors settings</a>.', 'bw-ai-schema-pro' ),
						admin_url( 'options-general.php?page=bw-ai-schema-authors' )
					); ?>
				</p>
			</div>
			<?php endif; ?>

			<!-- External Author (Saved) Fields -->
			<?php if ( ! empty( $external_authors ) ) : ?>
			<div class="bw-schema-author-fields bw-schema-author-external_saved" style="display: none;">
				<?php
				// Determine the selected external author ID
				// If no external_author_id is set, use the first external author as default
				$external_author_keys = array_keys( $external_authors );
				$selected_external_author_id = isset( $author_data['external_author_id'] ) && ! empty( $author_data['external_author_id'] )
					? $author_data['external_author_id']
					: $external_author_keys[0]; // Default to first external author
				?>
				<select name="bw_schema_authors[<?php echo $index; ?>][external_author_id]" class="widefat" required>
					<?php foreach ( $external_authors as $author_id => $author ) : ?>
						<option value="<?php echo esc_attr( $author_id ); ?>" <?php selected( $selected_external_author_id, $author_id ); ?>>
							<?php echo esc_html( $author['name'] ); ?>
							<?php if ( ! empty( $author['jobTitle'] ) ) : ?>
								- <?php echo esc_html( $author['jobTitle'] ); ?>
							<?php endif; ?>
						</option>
					<?php endforeach; ?>
				</select>
				<p class="description" style="margin-top: 5px;">
					<?php printf(
						__( 'Manage external authors in <a href="%s">Authors settings</a>.', 'bw-ai-schema-pro' ),
						admin_url( 'options-general.php?page=bw-ai-schema-authors' )
					); ?>
				</p>
			</div>
			<?php endif; ?>

			<!-- External Author (One-time) Fields -->
			<div class="bw-schema-author-fields bw-schema-author-external" style="display: none;">
				<p class="description" style="margin-bottom: 10px; color: #666;">
					<?php _e( 'Enter author details for this post only. For reusable authors, use External Authors in settings.', 'bw-ai-schema-pro' ); ?>
				</p>
				<div class="bw-schema-author-external-basic">
					<p>
						<label><?php _e( 'Name*', 'bw-ai-schema-pro' ); ?></label>
						<input type="text" name="bw_schema_authors[<?php echo $index; ?>][external][name]"
						       value="<?php echo isset( $author_data['external']['name'] ) ? esc_attr( $author_data['external']['name'] ) : ''; ?>"
						       class="widefat" placeholder="<?php _e( 'John Smith', 'bw-ai-schema-pro' ); ?>">
					</p>

					<p>
						<label><?php _e( 'Job Title', 'bw-ai-schema-pro' ); ?></label>
						<input type="text" name="bw_schema_authors[<?php echo $index; ?>][external][job_title]"
						       value="<?php echo isset( $author_data['external']['job_title'] ) ? esc_attr( $author_data['external']['job_title'] ) : ''; ?>"
						       class="widefat" placeholder="<?php _e( 'Industry Expert', 'bw-ai-schema-pro' ); ?>">
					</p>

					<p>
						<label><?php _e( 'Bio/Description', 'bw-ai-schema-pro' ); ?></label>
						<textarea name="bw_schema_authors[<?php echo $index; ?>][external][bio]"
						          class="widefat" rows="3"><?php echo isset( $author_data['external']['bio'] ) ? esc_textarea( $author_data['external']['bio'] ) : ''; ?></textarea>
					</p>
				</div>

				<button type="button" class="button bw-schema-toggle-external-fields" style="margin: 10px 0;">
					<?php _e( 'Show Advanced Fields', 'bw-ai-schema-pro' ); ?>
				</button>

				<div class="bw-schema-author-external-advanced" style="display: none;">
					<p>
						<label><?php _e( 'Profile Image URL', 'bw-ai-schema-pro' ); ?></label>
						<input type="url" name="bw_schema_authors[<?php echo $index; ?>][external][image]"
						       value="<?php echo isset( $author_data['external']['image'] ) ? esc_attr( $author_data['external']['image'] ) : ''; ?>"
						       class="widefat" placeholder="https://example.com/author-photo.jpg">
					</p>

					<p>
						<label><?php _e( 'Email', 'bw-ai-schema-pro' ); ?></label>
						<input type="email" name="bw_schema_authors[<?php echo $index; ?>][external][email]"
						       value="<?php echo isset( $author_data['external']['email'] ) ? esc_attr( $author_data['external']['email'] ) : ''; ?>"
						       class="widefat">
					</p>

					<p>
						<label><?php _e( 'Website', 'bw-ai-schema-pro' ); ?></label>
						<input type="url" name="bw_schema_authors[<?php echo $index; ?>][external][website]"
						       value="<?php echo isset( $author_data['external']['website'] ) ? esc_attr( $author_data['external']['website'] ) : ''; ?>"
						       class="widefat">
					</p>

					<p>
						<label><?php _e( 'LinkedIn', 'bw-ai-schema-pro' ); ?></label>
						<input type="url" name="bw_schema_authors[<?php echo $index; ?>][external][linkedin]"
						       value="<?php echo isset( $author_data['external']['linkedin'] ) ? esc_attr( $author_data['external']['linkedin'] ) : ''; ?>"
						       class="widefat" placeholder="https://linkedin.com/in/username">
					</p>

					<p>
						<label><?php _e( 'Twitter/X', 'bw-ai-schema-pro' ); ?></label>
						<input type="url" name="bw_schema_authors[<?php echo $index; ?>][external][twitter]"
						       value="<?php echo isset( $author_data['external']['twitter'] ) ? esc_attr( $author_data['external']['twitter'] ) : ''; ?>"
						       class="widefat" placeholder="https://twitter.com/username">
					</p>

					<p>
						<label><?php _e( 'Areas of Expertise (comma-separated)', 'bw-ai-schema-pro' ); ?></label>
						<input type="text" name="bw_schema_authors[<?php echo $index; ?>][external][expertise]"
						       value="<?php echo isset( $author_data['external']['expertise'] ) ? esc_attr( $author_data['external']['expertise'] ) : ''; ?>"
						       class="widefat"
						       placeholder="<?php _e( 'e.g., SEO, Content Marketing, Web Development', 'bw-ai-schema-pro' ); ?>">
					</p>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Save external author (v2.0 architecture)
	 */
	private function save_external_author() {
		$external_authors = get_option( 'bw_schema_external_authors', array() );

		// Generate or get existing ID
		$author_id = isset( $_POST['external_author_id'] ) ? sanitize_text_field( $_POST['external_author_id'] ) : 'ext_' . uniqid();

		// Build author data
		$author_data = array(
			'id'          => $author_id,
			'name'        => sanitize_text_field( $_POST['external_name'] ?? '' ),
			'jobTitle'    => sanitize_text_field( $_POST['external_job_title'] ?? '' ),
			'description' => sanitize_textarea_field( $_POST['external_description'] ?? '' ),
			'image'       => esc_url_raw( $_POST['external_image'] ?? '' ),
			'website'     => esc_url_raw( $_POST['external_website'] ?? '' ),
			'credentials' => sanitize_text_field( $_POST['external_credentials'] ?? '' ),
			'social'      => array(
				'linkedin' => esc_url_raw( $_POST['external_linkedin'] ?? '' ),
				'twitter'  => esc_url_raw( $_POST['external_twitter'] ?? '' ),
			),
			'created'     => isset( $external_authors[ $author_id ]['created'] )
				? $external_authors[ $author_id ]['created']
				: current_time( 'mysql' ),
			'modified'    => current_time( 'mysql' ),
		);

		// Save
		$external_authors[ $author_id ] = $author_data;
		update_option( 'bw_schema_external_authors', $external_authors );

		// Add success notice
		add_settings_error(
			'bw_schema_authors',
			'author_saved',
			isset( $_POST['external_author_id'] )
				? __( 'External author updated successfully.', 'bw-ai-schema-pro' )
				: __( 'External author added successfully.', 'bw-ai-schema-pro' ),
			'success'
		);

		// Redirect to clear form if adding new
		if ( ! isset( $_POST['external_author_id'] ) ) {
			wp_redirect( admin_url( 'options-general.php?page=bw-ai-schema-authors' ) );
			exit;
		}
	}

	/**
	 * Delete external author (v2.0 architecture)
	 */
	private function delete_external_author( $author_id ) {
		$external_authors = get_option( 'bw_schema_external_authors', array() );

		if ( isset( $external_authors[ $author_id ] ) ) {
			unset( $external_authors[ $author_id ] );
			update_option( 'bw_schema_external_authors', $external_authors );

			add_settings_error(
				'bw_schema_authors',
				'author_deleted',
				__( 'External author deleted successfully.', 'bw-ai-schema-pro' ),
				'success'
			);
		}

		wp_redirect( admin_url( 'options-general.php?page=bw-ai-schema-authors' ) );
		exit;
	}

	/**
	 * Bulk delete external authors (v2.0 architecture)
	 */
	private function bulk_delete_external_authors() {
		if ( empty( $_POST['external_ids'] ) || empty( $_POST['bulk_action'] ) || $_POST['bulk_action'] !== 'delete' ) {
			return;
		}

		$external_authors = get_option( 'bw_schema_external_authors', array() );
		$deleted_count    = 0;

		foreach ( $_POST['external_ids'] as $author_id ) {
			$author_id = sanitize_text_field( $author_id );
			if ( isset( $external_authors[ $author_id ] ) ) {
				unset( $external_authors[ $author_id ] );
				$deleted_count++;
			}
		}

		update_option( 'bw_schema_external_authors', $external_authors );

		add_settings_error(
			'bw_schema_authors',
			'authors_deleted',
			sprintf(
				_n(
					'%d external author deleted successfully.',
					'%d external authors deleted successfully.',
					$deleted_count,
					'bw-ai-schema-pro'
				),
				$deleted_count
			),
			'success'
		);
	}

	/**
	 * Save plugin-wide default author (v2.0)
	 *
	 * This is the fallback author used when:
	 * 1. A post has no author assigned
	 * 2. The WordPress user has no personal default author set
	 */
	private function save_plugin_default_author() {
		$type = sanitize_text_field( $_POST['bw_schema_plugin_default_type'] ?? '' );
		$id   = '';

		if ( $type === 'team_member' ) {
			$id = absint( $_POST['bw_schema_plugin_default_team_member'] ?? 0 );
			// Validate the team member exists and is flagged as author
			if ( $id ) {
				$is_author = get_post_meta( $id, '_bw_schema_is_author', true );
				if ( $is_author !== '1' ) {
					$id = '';
					$type = '';
				}
			}
		} elseif ( $type === 'external' ) {
			$id = sanitize_text_field( $_POST['bw_schema_plugin_default_external'] ?? '' );
			// Validate the external author exists
			if ( $id ) {
				$external_authors = get_option( 'bw_schema_external_authors', array() );
				if ( ! isset( $external_authors[ $id ] ) ) {
					$id = '';
					$type = '';
				}
			}
		}

		// Save or clear the setting
		if ( $type && $id ) {
			update_option( 'bw_schema_plugin_default_author', array(
				'type' => $type,
				'id'   => $id,
			) );
			add_settings_error(
				'bw_schema_authors',
				'default_saved',
				__( 'Plugin default author saved successfully.', 'bw-ai-schema-pro' ),
				'success'
			);
		} else {
			delete_option( 'bw_schema_plugin_default_author' );
			add_settings_error(
				'bw_schema_authors',
				'default_cleared',
				__( 'Plugin default author cleared.', 'bw-ai-schema-pro' ),
				'info'
			);
		}
	}

	/**
	 * Process legacy author migration to v2.0 architecture
	 */
	private function process_author_migration() {
		$actions = isset( $_POST['migrate_action'] ) ? $_POST['migrate_action'] : array();
		$targets = isset( $_POST['migrate_target'] ) ? $_POST['migrate_target'] : array();

		if ( empty( $actions ) ) {
			return;
		}

		$legacy_authors    = get_option( 'bw_schema_custom_authors', array() );
		$external_authors  = get_option( 'bw_schema_external_authors', array() );
		$migrated_count    = 0;
		$deleted_count     = 0;
		$posts_updated     = 0;
		$authors_to_remove = array();

		foreach ( $actions as $author_id => $action ) {
			$author_id = sanitize_text_field( $author_id );
			$action    = sanitize_text_field( $action );

			// Find the legacy author
			$legacy_author = null;
			$legacy_index  = null;
			foreach ( $legacy_authors as $idx => $author ) {
				if ( ( $author['id'] ?? '' ) === $author_id ) {
					$legacy_author = $author;
					$legacy_index  = $idx;
					break;
				}
			}

			if ( ! $legacy_author ) {
				continue;
			}

			switch ( $action ) {
				case 'link_team':
					// Link to team member and update post references
					$team_member_id = isset( $targets[ $author_id ] ) ? intval( $targets[ $author_id ] ) : 0;
					if ( $team_member_id ) {
						// Mark team member as author if not already
						update_post_meta( $team_member_id, '_bw_schema_is_author', '1' );

						// Update all posts using this custom author
						$this->update_post_author_references(
							array( 'type' => 'custom', 'custom_author_id' => $author_id ),
							array( 'type' => 'team_member', 'team_member_id' => $team_member_id )
						);

						$authors_to_remove[] = $legacy_index;
						$migrated_count++;
					}
					break;

				case 'to_external':
					// Convert to external author
					$ext_id = 'ext_' . time() . '_' . wp_rand( 1000, 9999 );
					$external_authors[ $ext_id ] = array(
						'name'        => $legacy_author['name'] ?? '',
						'jobTitle'    => $legacy_author['jobTitle'] ?? '',
						'description' => $legacy_author['description'] ?? '',
						'image'       => $legacy_author['image'] ?? '',
						'website'     => $legacy_author['social']['website'] ?? '',
						'email'       => $legacy_author['email'] ?? '',
						'created'     => current_time( 'mysql' ),
					);

					// Update all posts using this custom author
					$this->update_post_author_references(
						array( 'type' => 'custom', 'custom_author_id' => $author_id ),
						array( 'type' => 'external_saved', 'external_author_id' => $ext_id )
					);

					$authors_to_remove[] = $legacy_index;
					$migrated_count++;
					break;

				case 'delete':
					// Just remove the legacy author (posts will lose this author)
					$authors_to_remove[] = $legacy_index;
					$deleted_count++;
					break;

				case 'skip':
				default:
					// Do nothing
					break;
			}
		}

		// Remove migrated/deleted authors from legacy list
		if ( ! empty( $authors_to_remove ) ) {
			// Sort in reverse order to remove from end first
			rsort( $authors_to_remove );
			foreach ( $authors_to_remove as $idx ) {
				array_splice( $legacy_authors, $idx, 1 );
			}
			update_option( 'bw_schema_custom_authors', $legacy_authors );
		}

		// Save external authors if any were created
		if ( $external_authors !== get_option( 'bw_schema_external_authors', array() ) ) {
			update_option( 'bw_schema_external_authors', $external_authors );
		}

		// Show success message
		if ( $migrated_count > 0 || $deleted_count > 0 ) {
			$message = sprintf(
				__( 'Migration complete: %d authors migrated, %d deleted.', 'bw-ai-schema-pro' ),
				$migrated_count,
				$deleted_count
			);

			if ( empty( $legacy_authors ) ) {
				$message .= ' ' . __( 'All legacy authors have been processed.', 'bw-ai-schema-pro' );
			}

			add_settings_error(
				'bw_schema_authors',
				'migration_complete',
				$message,
				'success'
			);
		}
	}

	/**
	 * Update post author references from old format to new format
	 *
	 * @param array $old_ref The old author reference to find
	 * @param array $new_ref The new author reference to replace with
	 * @return int Number of posts updated
	 */
	private function update_post_author_references( $old_ref, $new_ref ) {
		$updated = 0;

		// Find posts with multiple_authors meta
		$posts = get_posts( array(
			'post_type'      => 'any',
			'posts_per_page' => -1,
			'post_status'    => 'any',
			'meta_query'     => array(
				array(
					'key'     => '_bw_schema_multiple_authors',
					'compare' => 'EXISTS',
				),
			),
		) );

		foreach ( $posts as $post ) {
			$multiple_authors = get_post_meta( $post->ID, '_bw_schema_multiple_authors', true );

			if ( ! is_array( $multiple_authors ) ) {
				continue;
			}

			$changed = false;
			foreach ( $multiple_authors as $idx => $author ) {
				// Check if this matches the old reference
				if ( $this->author_ref_matches( $author, $old_ref ) ) {
					$multiple_authors[ $idx ] = $new_ref;
					$changed = true;
				}
			}

			if ( $changed ) {
				update_post_meta( $post->ID, '_bw_schema_multiple_authors', $multiple_authors );
				$updated++;
			}
		}

		return $updated;
	}

	/**
	 * Check if an author reference matches criteria
	 *
	 * @param array $author The author reference to check
	 * @param array $criteria The criteria to match
	 * @return bool
	 */
	private function author_ref_matches( $author, $criteria ) {
		if ( ! is_array( $author ) || ! is_array( $criteria ) ) {
			return false;
		}

		// Check type
		if ( isset( $criteria['type'] ) && ( $author['type'] ?? '' ) !== $criteria['type'] ) {
			return false;
		}

		// Check custom_author_id
		if ( isset( $criteria['custom_author_id'] ) && ( $author['custom_author_id'] ?? '' ) !== $criteria['custom_author_id'] ) {
			return false;
		}

		return true;
	}
}