<?php
/**
 * Unified Settings Page — renders and handles the consolidated Wisewand settings form.
 *
 * Extracted from Admin_Manager to isolate all settings-page concerns in a
 * dedicated class: rendering the HTML form, processing form submissions,
 * propagating global RSS settings to inheriting feeds, and providing helper
 * utilities (plugin-status detection, API-key masking, persona lookup).
 *
 * @package Wisewand
 * @since 2.8.2
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Admin;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Utils\Options;
use Wisewand\Utils\Wisewand_API_Client;
use Wisewand\Utils\Publish_Mode_Migrator;
use Wisewand\Utils\Schedule_Validator;
use Wisewand\Logging\Logger;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log -- error_log() only used within WP_DEBUG conditionals

/**
 * Unified Settings Page controller.
 *
 * Responsible for rendering the Wisewand Settings admin page and processing
 * all form submissions. Also propagates global RSS settings to feeds that
 * inherit from global defaults.
 *
 * @package Wisewand
 * @since 2.8.2
 */
class Settings_Page {

	/**
	 * Options wrapper.
	 *
	 * @var Options
	 */
	private $options;

	/**
	 * Logger instance.
	 *
	 * @var Logger
	 */
	private $logger;

	/**
	 * Constructor.
	 *
	 * @since 2.8.2
	 *
	 * @param Options $options Options wrapper.
	 * @param Logger  $logger  Logger instance.
	 */
	public function __construct( Options $options, Logger $logger ) {
		$this->options = $options;
		$this->logger  = $logger;
	}

	/**
	 * Render the unified settings page.
	 *
	 * Entry point called by the WordPress add_submenu_page() callback.
	 * Processes any form submission before rendering, then outputs the
	 * full settings form wrapped in a standard WP admin .wrap container.
	 *
	 * @since 2.8.2
	 */
	public function unified_settings_page() {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification performed in handle_unified_settings_form()
		if ( isset( $_POST['submit'] ) ) {
			$this->handle_unified_settings_form();
		}

		echo '<div class="wrap wisewand-unified-settings">';
		echo '<h1>' . esc_html__( 'Wisewand Settings', 'wisewand-ai-content-writer-seo-content-generator' ) . '</h1>';

		settings_errors( 'wisewand_unified_settings' );

		// Render main settings
		// Render main settings
		$this->render_unified_settings_content();

		echo '</div>';
	}

	/**
	 * Render the main settings form HTML.
	 *
	 * Outputs the full HTML form including API credentials, server diagnostics,
	 * content settings, calendar defaults, persona/author mappings, RSS automation,
	 * and system health sections.
	 *
	 * @since 2.8.2
	 */
	public function render_unified_settings_content() {
		$api_key           = Wisewand_API_Client::get_stored_api_key();
		$is_api_configured = Wisewand_API_Client::is_api_key_configured();
		$security_settings = $this->options->get_security_settings();
		$media_settings    = $this->options->get_media_settings();

		// Get plugin detection info
		$plugin_status = $this->get_plugin_status();
		?>
		<form method="post" action="">
			<?php wp_nonce_field( 'wisewand_unified_settings' ); ?>

			<!-- API Configuration -->
			<div class="wisewand-settings-section">
				<h2><?php esc_html_e( '🔑 API & Integrations', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<p class="description" style="margin-bottom: 20px;">
					<?php esc_html_e( 'Connect external services to power your content generation.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</p>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Wisewand API Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="password" name="api_key" value="<?php echo esc_attr( $api_key ); ?>" class="regular-text" placeholder="<?php esc_html_e( 'Enter your Wisewand API key...', 'wisewand-ai-content-writer-seo-content-generator' ); ?>" />
							<?php if ( $is_api_configured ) : ?>
							<br><small><?php esc_html_e( 'Current key:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <code><?php echo esc_html( Wisewand_API_Client::get_masked_api_key() ); ?></code></small>
							<?php endif; ?>
							<p class="description">
								<?php esc_html_e( 'Get your API key from your Wisewand dashboard:', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<a href="https://app.wisewand.ai/api" target="_blank" rel="noopener noreferrer" style="font-weight: 600;">
									<?php esc_html_e( 'Get API Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?> →
								</a>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'DataForSEO Credentials', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="color: #999; font-weight: 400;">(<?php esc_html_e( 'Optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></th>
						<td>
							<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; max-width: 600px;">
								<div>
									<label for="dataforseo_login"><?php esc_html_e( 'Login/Email', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="text" id="dataforseo_login" name="dataforseo_login" value="<?php echo esc_attr( $this->options->get( 'wisewand_dataforseo_login', '' ) ); ?>" class="regular-text" placeholder="<?php esc_html_e( 'DataForSEO login', 'wisewand-ai-content-writer-seo-content-generator' ); ?>" />
								</div>
								<div>
									<label for="dataforseo_password"><?php esc_html_e( 'Password', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
									<input type="password" id="dataforseo_password" name="dataforseo_password" value="<?php echo esc_attr( $this->options->get( 'wisewand_dataforseo_password', '' ) ); ?>" class="regular-text" placeholder="<?php esc_html_e( 'DataForSEO password', 'wisewand-ai-content-writer-seo-content-generator' ); ?>" />
								</div>
							</div>
							<?php if ( $this->options->get( 'wisewand_dataforseo_login' ) ) : ?>
							<br><small><?php esc_html_e( 'Current login:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <code><?php echo esc_html( $this->options->get( 'wisewand_dataforseo_login' ) ); ?></code></small>
							<?php endif; ?>
							<p class="description">
								<?php esc_html_e( 'DataForSEO uses login/password authentication for SEO intelligence features.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<a href="https://app.dataforseo.com/api-access?aff=176745" target="_blank" rel="noopener noreferrer" style="font-weight: 600;">
									<?php esc_html_e( 'Get API Credentials', 'wisewand-ai-content-writer-seo-content-generator' ); ?> →
								</a>
							</p>
						</td>
					</tr>

					<tr>
						<th scope="row">🤖 <?php esc_html_e( 'OpenAI API Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="color: #999; font-weight: 400;">(<?php esc_html_e( 'Optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></th>
						<td>
							<?php
							$openai_key        = get_option( 'wisewand_openai_api_key', '' );
							$openai_configured = ! empty( $openai_key ) && strlen( $openai_key ) > 20;
							$openai_masked     = $openai_configured ? substr( $openai_key, 0, 7 ) . '...' . substr( $openai_key, -4 ) : '';
							?>
							<input type="password"
									id="wisewand_openai_api_key"
									name="wisewand_openai_api_key"
									value="<?php echo esc_attr( $openai_key ); ?>"
									class="regular-text"
									placeholder="sk-proj-..." />

							<?php if ( $openai_configured ) : ?>
							<br><small class="openai-key-info">
								<?php esc_html_e( 'Current key:', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <code><?php echo esc_html( $openai_masked ); ?></code>
								<button type="button" class="button-link" id="toggle-openai-key" style="margin-left: 8px;">
									<?php esc_html_e( 'Show/Hide', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</button>
							</small>
							<?php endif; ?>

							<p class="description">
								<strong>🤖 <?php esc_html_e( 'AI-Powered Features:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong><br>
								• <?php esc_html_e( 'Category Matching - Auto-match keywords to WordPress categories', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
								• <?php esc_html_e( 'Image Metadata - Generate alt text, captions, descriptions (see below)', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br><br>
								<?php esc_html_e( 'Get your API key from:', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<a href="https://platform.openai.com/settings/organization/api-keys" target="_blank" rel="noopener noreferrer" style="font-weight: 600;">
									<?php esc_html_e( 'OpenAI Dashboard', 'wisewand-ai-content-writer-seo-content-generator' ); ?> →
								</a><br>
								<strong><?php esc_html_e( 'Model:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> gpt-4o-mini (temperature: 0.3 for consistent results)<br>
								<strong><?php esc_html_e( 'Cost:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> ~$0.001 per image, ~$0.25 per 1,000 keywords
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row">🖼️ <?php esc_html_e( 'AI Image Metadata', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="color: #999; font-weight: 400;">(<?php esc_html_e( 'Optional', 'wisewand-ai-content-writer-seo-content-generator' ); ?>)</span></th>
						<td>
							<label>
								<input type="checkbox" name="wisewand_generate_ai_image_metadata" value="1" <?php checked( $this->options->get( 'wisewand_generate_ai_image_metadata', false ), true ); ?>>
								<?php esc_html_e( 'Generate AI-powered image metadata (alt text, captions, descriptions)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</label>
							<p class="description">
								<?php esc_html_e( 'When enabled, OpenAI will automatically generate:', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
								• <strong><?php esc_html_e( 'Alt Text:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'SEO-optimized, accessible descriptions for screen readers', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
								• <strong><?php esc_html_e( 'Title:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Hover tooltip text', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
								• <strong><?php esc_html_e( 'Caption:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Engaging text displayed below images', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
								• <strong><?php esc_html_e( 'Description:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Detailed metadata for media library and SEO', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br><br>
								<strong><?php esc_html_e( 'Applies to:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Featured images, gallery images, and inline images', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
								<strong><?php esc_html_e( 'Fallback:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Uses meta-title if OpenAI fails or is disabled', 'wisewand-ai-content-writer-seo-content-generator' ); ?><br>
								<strong><?php esc_html_e( 'Cost:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( '~$0.001 per image (~600 tokens @ gpt-4o-mini pricing)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
							<p class="description" style="color: #2563eb;">
								💡 <strong><?php esc_html_e( 'Benefits:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Improves SEO, accessibility (WCAG compliance), and user experience. Essential for image search rankings.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'AI Instructions', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="wisewand_default_auto_generate_instructions" value="1" <?php checked( $this->options->get( 'wisewand_default_auto_generate_instructions', false ), true ); ?>>
								<?php esc_html_e( 'Auto-generate AI Instructions during roadmap generation', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</label>
							<p class="description">
								<?php esc_html_e( 'When enabled, roadmap will automatically generate Search Intention, Additional Instructions, and Avoid Information fields. When disabled, fields remain blank - you can generate them manually in Edit Publication modal using templates or ChatGPT.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
							<p class="description" style="color: #3b82f6;">
								💡 <strong><?php esc_html_e( 'Recommended:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'Leave unchecked for full control. Use the AI Generate button in Edit Publication for better, context-aware instructions.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>

			<!-- Server Requirements Diagnostic -->
			<div class="wisewand-settings-section">
				<h2>🖥️ <?php esc_html_e( 'Server Requirements & Diagnostics', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<p class="description" style="margin-bottom: 16px;">
					<?php esc_html_e( 'Check if your server meets recommended requirements for importing articles with multiple images and AI-powered features.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</p>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'PHP Version', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php
							$php_version   = PHP_VERSION;
							$php_meets_req = version_compare( $php_version, '7.4', '>=' );
							?>
							<strong><?php echo esc_html( $php_version ); ?></strong>
							<?php if ( $php_meets_req ) : ?>
								<span style="color: #10b981; margin-left: 8px;">✅ <?php esc_html_e( 'Good', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							<?php else : ?>
								<span style="color: #ef4444; margin-left: 8px;">⚠️ <?php esc_html_e( 'Outdated', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							<?php endif; ?>
							<p class="description">
								<?php esc_html_e( 'Recommended: PHP 7.4 or higher', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Memory Limit', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php
							$memory_limit     = ini_get( 'memory_limit' );
							$memory_bytes     = wp_convert_hr_to_bytes( $memory_limit );
							$memory_meets_req = ( $memory_bytes >= 268435456 ); // 256MB
							?>
							<strong><?php echo esc_html( $memory_limit ); ?></strong>
							<?php if ( $memory_meets_req ) : ?>
								<span style="color: #10b981; margin-left: 8px;">✅ <?php esc_html_e( 'Good', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							<?php else : ?>
								<span style="color: #f59e0b; margin-left: 8px;">⚠️ <?php esc_html_e( 'Low', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							<?php endif; ?>
							<p class="description">
								<?php esc_html_e( 'Recommended: 256MB or higher for processing multiple images and AI metadata generation', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<?php if ( ! $memory_meets_req ) : ?>
									<br><strong style="color: #ef4444;">
										<?php esc_html_e( 'Your server may encounter 500 errors when importing articles with multiple inline images. Contact your hosting provider to increase the memory limit.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</strong>
								<?php endif; ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Max Execution Time', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php
							$max_execution_time = ini_get( 'max_execution_time' );
							$time_meets_req     = ( $max_execution_time == 0 || $max_execution_time >= 120 );
							?>
							<strong><?php echo $max_execution_time == 0 ? esc_html__( 'Unlimited', 'wisewand-ai-content-writer-seo-content-generator' ) : esc_html( $max_execution_time ) . 's'; ?></strong>
							<?php if ( $time_meets_req ) : ?>
								<span style="color: #10b981; margin-left: 8px;">✅ <?php esc_html_e( 'Good', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							<?php else : ?>
								<span style="color: #f59e0b; margin-left: 8px;">⚠️ <?php esc_html_e( 'Low', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							<?php endif; ?>
							<p class="description">
								<?php esc_html_e( 'Recommended: 120 seconds or higher. With 10 inline images + AI metadata, imports can take 30-60 seconds.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<?php if ( ! $time_meets_req ) : ?>
									<br><strong style="color: #ef4444;">
										<?php esc_html_e( 'Imports may timeout with multiple images. The plugin increases this to 300s during imports, but some hosts block set_time_limit(). Contact your hosting provider if you experience timeouts.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</strong>
								<?php endif; ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Upload Max Filesize', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php
							$upload_max       = ini_get( 'upload_max_filesize' );
							$upload_bytes     = wp_convert_hr_to_bytes( $upload_max );
							$upload_meets_req = ( $upload_bytes >= 10485760 ); // 10MB
							?>
							<strong><?php echo esc_html( $upload_max ); ?></strong>
							<?php if ( $upload_meets_req ) : ?>
								<span style="color: #10b981; margin-left: 8px;">✅ <?php esc_html_e( 'Good', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							<?php else : ?>
								<span style="color: #f59e0b; margin-left: 8px;">⚠️ <?php esc_html_e( 'Low', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
							<?php endif; ?>
							<p class="description">
								<?php esc_html_e( 'Recommended: 10MB or higher for downloading generated images', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'cURL Support', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php $curl_available = function_exists( 'curl_version' ); ?>
							<?php if ( $curl_available ) : ?>
								<?php $curl_info = curl_version(); ?>
								<span style="color: #10b981;">✅ <?php esc_html_e( 'Enabled', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								<span style="margin-left: 8px; color: #6b7280; font-size: 12px;">
									(<?php echo esc_html( $curl_info['version'] ?? 'unknown' ); ?>)
								</span>
							<?php else : ?>
								<span style="color: #ef4444;">❌ <?php esc_html_e( 'Disabled', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
								<p class="description" style="color: #ef4444;">
									<strong><?php esc_html_e( 'cURL is required for Wisewand API communication. Contact your hosting provider.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
								</p>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Overall Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php
							$all_requirements_met = $php_meets_req && $memory_meets_req && $time_meets_req && $upload_meets_req && $curl_available;
							?>
							<?php if ( $all_requirements_met ) : ?>
								<div style="padding: 12px; background: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;">
									<strong style="color: #065f46;">✅ <?php esc_html_e( 'All requirements met!', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
									<p style="margin: 8px 0 0 0; color: #047857;">
										<?php esc_html_e( 'Your server is properly configured for importing articles with multiple images and AI features.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</p>
								</div>
							<?php else : ?>
								<div style="padding: 12px; background: #fef3c7; border-left: 4px solid #f59e0b; border-radius: 4px;">
									<strong style="color: #92400e;">⚠️ <?php esc_html_e( 'Some requirements not met', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
									<p style="margin: 8px 0 0 0; color: #92400e;">
										<?php esc_html_e( 'Your server may experience issues importing articles, especially with multiple inline images or AI metadata generation. If you see "500 Internal Server Error", contact your hosting provider to increase the highlighted limits.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</p>
								</div>
							<?php endif; ?>
						</td>
					</tr>
				</table>
			</div>

			<!-- Essential Settings -->
			<div class="wisewand-settings-section">
				<h2><?php esc_html_e( 'Content Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Default Post Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="default_post_status">
								<option value="draft" <?php selected( $this->options->get( 'wisewand_default_post_status' ), 'draft' ); ?>><?php esc_html_e( 'Draft', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="pending" <?php selected( $this->options->get( 'wisewand_default_post_status' ), 'pending' ); ?>><?php esc_html_e( 'Pending Review', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="publish" <?php selected( $this->options->get( 'wisewand_default_post_status' ), 'publish' ); ?>><?php esc_html_e( 'Published', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</select>
							<p class="description"><?php esc_html_e( 'Default status for imported content. "Pending Review" requires manual approval before publishing.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Add Audio Player', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="checkbox" name="add_audio_player" value="1" <?php checked( $media_settings['add_audio_player'] ); ?> />
							<span><?php esc_html_e( 'Add audio player to posts when available', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Remove H1 Tags', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="checkbox" name="remove_h1_tags" value="1" <?php checked( $media_settings['remove_h1_tags'] ); ?> />
							<span><?php esc_html_e( 'Remove H1 tags to avoid title duplication', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						</td>
					</tr>
					<?php if ( $plugin_status['multilingual']['available'] ) : ?>
					<tr>
						<th scope="row"><?php esc_html_e( 'Multilingual Default Language', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="wpml_default_lang">
								<option value=""><?php esc_html_e( 'Auto-detect from Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<?php
								global $sitepress;
								if ( $sitepress ) {
									$languages = $sitepress->get_active_languages();
									foreach ( $languages as $code => $lang ) {
										echo '<option value="' . esc_attr( $code ) . '" ' . selected( $this->options->get( 'wisewand_wpml_default_lang' ), $code, false ) . '>' . esc_html( $lang['display_name'] ) . '</option>';
									}
								}
								?>
							</select>
							<p class="description">
								<?php
								/* translators: %s: Multilingual plugin name (e.g., 'WPML', 'Polylang') */
								printf( esc_html__( 'Using %s for multilingual support. Fallback when Wisewand language not recognized.', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $plugin_status['multilingual']['plugin'] ) );
								?>
							</p>
						</td>
					</tr>
					<?php endif; ?>
				</table>
			</div>

			<!-- Plugin Status -->
			<div class="wisewand-settings-section">
				<h2><?php esc_html_e( 'Plugin Integration Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Multilingual Support', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php if ( $plugin_status['multilingual']['available'] ) : ?>
								<span class="wisewand-status-badge wisewand-status-success">
									<?php echo esc_html( '✓ ' . $plugin_status['multilingual']['plugin'] ); ?>
								</span>
								<small>(
								<?php
									/* translators: %d: Number of active languages in the multilingual plugin */
									printf( esc_html__( '%d languages available', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $plugin_status['multilingual']['languages_count'] ) );
								?>
								)</small>
							<?php else : ?>
								<span class="wisewand-status-badge wisewand-status-warning">
									⚠ <?php esc_html_e( 'No multilingual plugin detected', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</span>
								<small><?php esc_html_e( 'Language column will be hidden', 'wisewand-ai-content-writer-seo-content-generator' ); ?></small>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'SEO Plugin', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php if ( $plugin_status['seo']['available'] ) : ?>
								<span class="wisewand-status-badge wisewand-status-success">
									<?php echo esc_html( '✓ ' . $plugin_status['seo']['plugin'] ); ?>
								</span>
								<small>(v<?php echo esc_html( $plugin_status['seo']['version'] ); ?>)</small>
							<?php else : ?>
								<span class="wisewand-status-badge wisewand-status-warning">
									⚠ <?php esc_html_e( 'No SEO plugin detected', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</span>
								<small><?php esc_html_e( 'SEO fields will use fallback meta', 'wisewand-ai-content-writer-seo-content-generator' ); ?></small>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'E-commerce', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php if ( $plugin_status['ecommerce']['available'] ) : ?>
								<span class="wisewand-status-badge wisewand-status-success">
									<?php echo esc_html( '✓ ' . $plugin_status['ecommerce']['plugin'] ); ?>
								</span>
								<small>(
								<?php
									/* translators: %d: Total number of products in WooCommerce */
									printf( esc_html__( '%d products available', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $plugin_status['ecommerce']['product_count'] ) );
								?>
								)</small>
							<?php else : ?>
								<span class="wisewand-status-badge wisewand-status-info">
									ℹ <?php esc_html_e( 'WooCommerce not active', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</span>
								<small><?php esc_html_e( 'Product import will use posts/pages', 'wisewand-ai-content-writer-seo-content-generator' ); ?></small>
							<?php endif; ?>
						</td>
					</tr>
				</table>
			</div>

			<!-- Security (simplified) -->
			<div class="wisewand-settings-section">
				<h2><?php esc_html_e( 'Webhook Security', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'HMAC Secret', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="text" name="hmac_secret" value="<?php echo esc_attr( $this->options->get( 'wisewand_hmac_secret' ) ); ?>" class="regular-text" readonly />
							<button type="button" class="button" id="generate-secret"><?php esc_html_e( 'Generate New', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
							<p class="description"><?php esc_html_e( 'Used for webhook signature verification.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
				</table>
			</div>

			<!-- Calendar Defaults -->
			<div class="wisewand-settings-section">
				<h2>📅 <?php esc_html_e( 'Calendar Defaults & Automation', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<p class="description"><?php esc_html_e( 'Configure default settings for automated content generation. These settings apply to all calendar entries created via roadmap generation.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>

				<h3 style="margin-top: 30px; border-top: 1px solid #e2e8f0; padding-top: 20px;">🗓️ <?php esc_html_e( 'Editorial Calendar & Core Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<p class="description" style="margin-bottom: 20px;">
					<?php esc_html_e( 'Configure your publication schedule, author personas, and operational hours.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</p>
				<table class="form-table">
					<tr>
						<th scope="row">
							<?php esc_html_e( 'Default Wisewand Project', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							<span style="color: red;">*</span>
						</th>
						<td>
							<select name="wisewand_default_project_id" id="default-project-select" class="regular-text" style="min-width: 400px;">
								<option value=""><?php esc_html_e( 'Loading projects...', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</select>
							<p class="description">
								<?php esc_html_e( 'Required for roadmap generation. All automated articles will use this project.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<strong><?php esc_html_e( 'The project\'s brief will be automatically applied by Wisewand.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Daily CRON Time', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="wisewand_cron_daily_hour">
								<?php
								$current_hour = $this->options->get( 'wisewand_cron_daily_hour', 2 );
								for ( $i = 0; $i < 24; $i++ ) {
									$label = sprintf( '%02d:00', $i );
									echo '<option value="' . esc_attr( $i ) . '" ' . selected( $current_hour, $i, false ) . '>' . esc_html( $label ) . '</option>';
								}
								?>
							</select>
							<p class="description">
								<?php esc_html_e( 'Hour of the day (server time) when the daily content generation and publishing CRON runs. Default is 02:00.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr id="project-brief-row" style="display: none;">
						<th scope="row"><?php esc_html_e( 'Project Brief', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<textarea readonly rows="6" id="project-brief-display" class="large-text code" style="background: #f8fafc; border: 1px solid #e2e8f0;"></textarea>
							<p class="description">
								<span id="brief-char-count" style="font-weight: 600;">0</span> <?php esc_html_e( 'characters', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<span id="brief-warning" style="color: #f59e0b; display: none; margin-left: 12px;">
									⚠️ <?php esc_html_e( 'Brief is long (500+ chars). Consider shortening in Wisewand project settings.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</span>
							</p>
							<p class="description" style="background: #eff6ff; padding: 12px; border-left: 3px solid #3b82f6; border-radius: 4px;">
								ℹ️ <?php esc_html_e( 'This brief is automatically used by Wisewand when generating content. You don\'t need to manually add it to additional_information - Wisewand handles it via the project_id.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Fallback Language', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="wisewand_fallback_language">
								<?php
								$current_fallback_lang = $this->options->get( 'wisewand_fallback_language', 'en' );
								foreach ( \Wisewand\Config\Supported_Options::get_languages() as $code => $lang ) {
									echo '<option value="' . esc_attr( $code ) . '" ' . selected( $current_fallback_lang, $code, false ) . '>' . esc_html( $lang['flag'] . ' ' . $lang['name'] ) . '</option>';
								}
								?>
							</select>
							<p class="description"><?php esc_html_e( 'Used only if keyword has no language_code. Each keyword\'s language is used first.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Fallback Country', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="wisewand_fallback_country">
								<?php
								$current_fallback_country = $this->options->get( 'wisewand_fallback_country', 'us' );
								foreach ( \Wisewand\Config\Supported_Options::get_countries() as $code => $country ) {
									echo '<option value="' . esc_attr( $code ) . '" ' . selected( $current_fallback_country, $code, false ) . '>' . esc_html( $country['flag'] . ' ' . $country['name'] ) . '</option>';
								}
								?>
							</select>
							<p class="description"><?php esc_html_e( 'Used only if keyword has no location_code. Each keyword\'s country is determined from its location first.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
				</table>

				<h3 style="margin-top: 30px; border-top: 1px solid #e2e8f0; padding-top: 20px;">👤 <?php esc_html_e( 'Persona & Author Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<table class="form-table">
					<?php
					$users = get_users(
						array(
							'capability' => 'edit_posts',
							'orderby'    => 'display_name',
						)
					);
					foreach ( \Wisewand\Config\Supported_Options::get_languages() as $lang_code => $lang_info ) :
					?>
					<tr>
						<th scope="row">
							<?php
							/* translators: %s: Language name (e.g., 'English', 'French') */
							printf( esc_html__( '%s Content', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $lang_info['name'] ) );
							?>
						</th>
						<td>
							<label><strong><?php esc_html_e( 'Persona:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong></label><br>
							<select name="wisewand_default_persona_<?php echo esc_attr( $lang_code ); ?>" id="persona-<?php echo esc_attr( $lang_code ); ?>-select" class="regular-text" style="min-width: 400px;">
								<option value=""><?php esc_html_e( 'Loading personas...', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</select>
							<br><br>
							<label><strong><?php esc_html_e( 'WordPress Author:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong></label><br>
							<select name="wisewand_default_author_<?php echo esc_attr( $lang_code ); ?>">
								<?php
								foreach ( $users as $user ) {
									$sel = selected( $this->options->get( 'wisewand_default_author_' . $lang_code, 1 ), $user->ID, false );
									echo '<option value="' . esc_attr( $user->ID ) . '" ' . esc_attr( $sel ) . '>' . esc_html( $user->display_name ) . ' (ID: ' . esc_html( $user->ID ) . ')</option>';
								}
								?>
							</select>
							<p class="description">
								<?php
								/* translators: %s: Language name (e.g., 'English', 'French') */
								printf( esc_html__( '%s articles will use this persona and be authored by this WordPress user when imported.', 'wisewand-ai-content-writer-seo-content-generator' ), esc_html( $lang_info['name'] ) );
								?>
							</p>
						</td>
					</tr>
					<?php endforeach; ?>
				</table>


				<!-- WiseWand Project Brief Migration Notice -->
				<div style="margin: 30px 0; padding: 24px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px; box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3); border: 2px solid rgba(255, 255, 255, 0.1);">
					<div style="display: flex; align-items: start; gap: 20px;">
						<div style="flex-shrink: 0; width: 60px; height: 60px; background: rgba(255, 255, 255, 0.2); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 32px; backdrop-filter: blur(10px);">
							✨
						</div>
						<div style="flex: 1; color: white;">
							<h2 style="margin: 0 0 12px 0; color: white; font-size: 22px; font-weight: 600;">
								<?php esc_html_e( 'Content Settings Moved to Project Brief', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</h2>
							<p style="margin: 0 0 16px 0; font-size: 15px; line-height: 1.6; color: rgba(255, 255, 255, 0.95);">
								<?php esc_html_e( 'As of Wisewand 2.8.0, all content generation settings (TOC, FAQ, images, audio, internal links, etc.) are now managed through your Wisewand Project Brief for better consistency and centralized control.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
							<div style="display: flex; gap: 12px; flex-wrap: wrap;">
								<a href="https://app.wisewand.ai/projects" target="_blank" class="button button-primary" style="background: white; color: #667eea; border: none; font-weight: 600; padding: 10px 20px; text-decoration: none; border-radius: 6px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); transition: transform 0.2s;">
									🚀 <?php esc_html_e( 'Configure Project Brief', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</a>
							</div>
							<div style="margin-top: 16px; padding: 12px; background: rgba(255, 255, 255, 0.1); border-radius: 6px; backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.2);">
								<p style="margin: 0; font-size: 13px; line-height: 1.5; color: rgba(255, 255, 255, 0.9);">
									<strong>📝 <?php esc_html_e( 'Note:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
									<?php esc_html_e( 'Existing calendar entries will be automatically migrated to use your project brief configuration. No data will be lost.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</p>
							</div>
						</div>
					</div>
				</div>

				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Publication Time Range', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php $current_time_range = $this->options->get( 'wisewand_calendar_time_range', 'random' ); ?>
							<label style="display: block; margin-bottom: 8px;">
								<input type="radio" name="wisewand_calendar_time_range" value="random" <?php checked( $current_time_range, 'random' ); ?>>
								<strong><?php esc_html_e( '🔀 Random (9 AM - 8 PM)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							</label>
							<label style="display: block; margin-bottom: 8px;">
								<input type="radio" name="wisewand_calendar_time_range" value="morning" <?php checked( $current_time_range, 'morning' ); ?>>
								<strong><?php esc_html_e( '🌅 Morning (9 AM - 12 PM)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							</label>
							<label style="display: block; margin-bottom: 8px;">
								<input type="radio" name="wisewand_calendar_time_range" value="afternoon" <?php checked( $current_time_range, 'afternoon' ); ?>>
								<strong><?php esc_html_e( '☀️ Afternoon (12 PM - 5 PM)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							</label>
							<label style="display: block; margin-bottom: 8px;">
								<input type="radio" name="wisewand_calendar_time_range" value="evening" <?php checked( $current_time_range, 'evening' ); ?>>
								<strong><?php esc_html_e( '🌆 Evening (5 PM - 8 PM)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							</label>
							<p class="description">
								<?php esc_html_e( 'Default time range for automated roadmap generation. A random time within this range will be assigned to each post.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Time of Day', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="time" name="rss_default_import_time" value="<?php echo esc_attr( $this->options->get( 'wisewand_rss_default_import_time', '09:00' ) ); ?>" class="regular-text" />
							<p class="description">
								<?php esc_html_e( 'Used when Import Frequency is set to "Daily".', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Allowed Publication Days', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php
							$allowed_days = $this->options->get( 'wisewand_allowed_publication_days', array( '1', '2', '3', '4', '5' ) );
							if ( ! is_array( $allowed_days ) ) {
								$allowed_days = array( '1', '2', '3', '4', '5' );
							}
							$days_labels = array(
								'1' => __( 'Monday', 'wisewand-ai-content-writer-seo-content-generator' ),
								'2' => __( 'Tuesday', 'wisewand-ai-content-writer-seo-content-generator' ),
								'3' => __( 'Wednesday', 'wisewand-ai-content-writer-seo-content-generator' ),
								'4' => __( 'Thursday', 'wisewand-ai-content-writer-seo-content-generator' ),
								'5' => __( 'Friday', 'wisewand-ai-content-writer-seo-content-generator' ),
								'6' => __( 'Saturday', 'wisewand-ai-content-writer-seo-content-generator' ),
								'7' => __( 'Sunday', 'wisewand-ai-content-writer-seo-content-generator' ),
							);
							?>
							<?php foreach ( $days_labels as $day_num => $day_label ) : ?>
								<label style="display: inline-block; margin-right: 16px; margin-bottom: 8px;">
									<input type="checkbox"
											name="wisewand_allowed_publication_days[]"
											value="<?php echo esc_attr( $day_num ); ?>"
											<?php checked( in_array( $day_num, $allowed_days ), true ); ?>>
									<?php echo esc_html( $day_label ); ?>
								</label>
							<?php endforeach; ?>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Cannibalization Handling', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label><?php esc_html_e( 'When roadmap detects existing content for keyword:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<select name="wisewand_cannibalization_default_action" class="regular-text">
								<option value="create" <?php selected( $this->options->get( 'wisewand_cannibalization_default_action', 'create' ), 'create' ); ?>><?php esc_html_e( 'Create New Content (Recommended - Safe)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="update" <?php selected( $this->options->get( 'wisewand_cannibalization_default_action' ), 'update' ); ?>><?php esc_html_e( 'Update Existing Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="skip" <?php selected( $this->options->get( 'wisewand_cannibalization_default_action' ), 'skip' ); ?>><?php esc_html_e( 'Skip Conflicting Keywords', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</select>
							<p class="description">
								<?php esc_html_e( 'Default action when the roadmap generator detects you already have content for a keyword. You can always override this per-keyword in the roadmap preview.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Content Update Strategy', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label><?php esc_html_e( 'When updating existing posts:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<select name="wisewand_default_content_merge_strategy">
								<option value="append" <?php selected( $this->options->get( 'wisewand_default_content_merge_strategy', 'append' ), 'append' ); ?>><?php esc_html_e( 'Append to End (Recommended - Safe)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="prepend" <?php selected( $this->options->get( 'wisewand_default_content_merge_strategy' ), 'prepend' ); ?>><?php esc_html_e( 'Prepend to Beginning', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="replace" <?php selected( $this->options->get( 'wisewand_default_content_merge_strategy' ), 'replace' ); ?>><?php esc_html_e( 'Replace Entire Content (Destructive)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</select>
							<p class="description">
								<?php esc_html_e( 'How to merge new content with existing posts. Only applies when updating existing content (not creating new).', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
							<p class="description" style="color: #dc2626;">
								⚠️ <strong><?php esc_html_e( 'Warning:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( '"Replace Entire Content" will permanently delete existing content. Use with caution.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>

			<!-- System Health & Debugging (Split Part B) -->
			<div class="wisewand-settings-section">
				<h3 style="margin-top: 30px; border-top: 1px solid #e2e8f0; padding-top: 20px;">🛠️ <?php esc_html_e( 'System Health & Debugging', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<p class="description" style="margin-bottom: 20px;">
					<?php esc_html_e( 'Monitor plugin performance, manage logs, and perform system maintenance.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</p>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Log Retention (Days)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="number" name="wisewand_log_retention_days" value="<?php echo esc_attr( $this->options->get( 'wisewand_log_retention_days', 30 ) ); ?>" min="1" max="365" class="small-text" />
							<p class="description"><?php esc_html_e( 'Number of days to keep logs before auto-deleting.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Max Log Entries', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="number" name="wisewand_log_max_entries" value="<?php echo esc_attr( $this->options->get( 'wisewand_log_max_entries', 1000 ) ); ?>" min="100" max="10000" class="regular-text" />
							<p class="description"><?php esc_html_e( 'Maximum number of log entries to store.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Maintenance', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<button type="button" class="button button-secondary" id="wisewand-purge-logs">
								<?php esc_html_e( 'Purge All Logs', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</button>
							<p class="description"><?php esc_html_e( 'Manually clear all stored logs.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
				</table>
			</div>

			<div class="wisewand-settings-actions">
				<?php submit_button( __( 'Save Settings', 'wisewand-ai-content-writer-seo-content-generator' ), 'primary' ); ?>
				<?php if ( $is_api_configured ) : ?>
				<button type="button" class="button button-secondary" id="test-api"><?php esc_html_e( 'Test API Connection', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
				<button type="button" class="button button-secondary" id="debug-projects"><?php esc_html_e( 'Debug Projects', 'wisewand-ai-content-writer-seo-content-generator' ); ?></button>
				<?php endif; ?>
			</div>

		<script type="text/javascript">
		jQuery(document).ready(function($) {
			// Show/hide time input based on selected publish mode
			function toggleGlobalScheduleTime() {
				const selectedMode = $('input[name="global_rss_publish_mode"]:checked').val();
				const timeRow = $('#global-schedule-time-row-settings');

				if (selectedMode === 'scheduled') {
					timeRow.fadeIn(300);
				} else {
					timeRow.fadeOut(300);
				}
			}

			// Run on page load
			toggleGlobalScheduleTime();

			// Run on change
			$('input[name="global_rss_publish_mode"]').on('change', toggleGlobalScheduleTime);
		});
		</script>
		</form>
		<?php
	}

	/**
	 * Process the unified settings form submission.
	 *
	 * Verifies the admin nonce, checks capabilities, sanitizes all POST fields,
	 * persists updated options, and calls propagate_global_rss_settings() to
	 * notify feeds that inherit from global defaults.
	 *
	 * @since 2.8.2
	 */
	public function handle_unified_settings_form() {
		check_admin_referer( 'wisewand_unified_settings' );

		if ( ! current_user_can( 'manage_options' ) ) {
			add_settings_error( 'wisewand_unified_settings', 'insufficient_permissions', __( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ), 'error' );
			return;
		}

		// API Keys
		$api_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';
		if ( ! empty( $api_key ) ) {
			Wisewand_API_Client::store_api_key( $api_key );
		}

		$dataforseo_login    = isset( $_POST['dataforseo_login'] ) ? sanitize_text_field( wp_unslash( $_POST['dataforseo_login'] ) ) : '';
		$dataforseo_password = isset( $_POST['dataforseo_password'] ) ? sanitize_text_field( wp_unslash( $_POST['dataforseo_password'] ) ) : '';
		if ( ! empty( $dataforseo_login ) && ! empty( $dataforseo_password ) ) {
			if ( ! class_exists( 'Wisewand\\Utils\\DataForSEO_Universal' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/DataForSEO_Universal.php';
			}
			\Wisewand\Utils\DataForSEO_Universal::store_credentials( $dataforseo_login, $dataforseo_password );
		}

		// OpenAI API key
		$openai_key = isset( $_POST['wisewand_openai_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_openai_api_key'] ) ) : '';
		if ( ! empty( $openai_key ) ) {
			update_option( 'wisewand_openai_api_key', $openai_key );
		} elseif ( isset( $_POST['wisewand_openai_api_key'] ) ) {
			// Remove if explicitly cleared
			delete_option( 'wisewand_openai_api_key' );
		}

		// OpenAI AI Image Metadata generation: use rest_sanitize_boolean
		$generate_ai_metadata = isset( $_POST['wisewand_generate_ai_image_metadata'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['wisewand_generate_ai_image_metadata'] ) ) : false;
		$this->options->set( 'wisewand_generate_ai_image_metadata', $generate_ai_metadata );

		// Content settings: already properly sanitized for text fields
		$this->options->set( 'wisewand_default_post_status', isset( $_POST['default_post_status'] ) ? sanitize_text_field( wp_unslash( $_POST['default_post_status'] ) ) : 'draft' );

		// Boolean settings: use rest_sanitize_boolean
		$add_audio_player = isset( $_POST['add_audio_player'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['add_audio_player'] ) ) : false;
		$this->options->set( 'wisewand_add_audio_player', $add_audio_player );

		$use_audio = isset( $_POST['wisewand_default_use_audio'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['wisewand_default_use_audio'] ) ) : false;
		$this->options->set( 'wisewand_default_use_audio', $use_audio );

		$remove_h1_tags = isset( $_POST['remove_h1_tags'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['remove_h1_tags'] ) ) : false;
		$this->options->set( 'wisewand_remove_h1_tags', $remove_h1_tags );

		// WPML
		if ( $this->options->is_wpml_active() ) {
			$this->options->set( 'wisewand_wpml_default_lang', isset( $_POST['wpml_default_lang'] ) ? sanitize_text_field( wp_unslash( $_POST['wpml_default_lang'] ) ) : '' );
		}

		// HMAC Secret
		if ( ! empty( $_POST['hmac_secret'] ) ) {
			$this->options->set( 'wisewand_hmac_secret', sanitize_text_field( wp_unslash( $_POST['hmac_secret'] ) ) );
		}

		// Calendar Defaults - Tier 1: Essential
		$new_project_id = isset( $_POST['wisewand_default_project_id'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_project_id'] ) ) : '';
		if ( ! empty( $new_project_id ) ) {
			$this->options->set( 'wisewand_default_project_id', $new_project_id );
			// Invalidate project brief cache when project changes.
			delete_transient( 'wisewand_project_brief' );
			wp_cache_delete( 'wisewand_project_brief', 'wisewand' );
		}
		$this->options->set( 'wisewand_fallback_language', isset( $_POST['wisewand_fallback_language'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_fallback_language'] ) ) : 'en' );
		$this->options->set( 'wisewand_fallback_country', isset( $_POST['wisewand_fallback_country'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_fallback_country'] ) ) : 'us' );

		// CRON Daily Hour
		$old_hour = $this->options->get( 'wisewand_cron_daily_hour', 2 );
		$new_hour = isset( $_POST['wisewand_cron_daily_hour'] ) ? absint( $_POST['wisewand_cron_daily_hour'] ) : 2;
		$new_hour = max( 0, min( 23, $new_hour ) ); // Ensure 0-23

		if ( $old_hour !== $new_hour ) {
			$this->options->set( 'wisewand_cron_daily_hour', $new_hour );
			// Clear the scheduled hook so it gets rescheduled with the new time on next page load/init
			wp_clear_scheduled_hook( 'wisewand_editorial_calendar_cron' );
		}

		// Persona & Author Mapping: loop over all supported languages
		foreach ( \Wisewand\Config\Supported_Options::get_language_codes() as $lang_code ) {
			$persona_key = 'wisewand_default_persona_' . $lang_code;
			$this->options->set( $persona_key, isset( $_POST[ $persona_key ] ) ? sanitize_text_field( wp_unslash( $_POST[ $persona_key ] ) ) : '' );

			$author_key     = 'wisewand_default_author_' . $lang_code;
			$default_author = isset( $_POST[ $author_key ] ) ? absint( $_POST[ $author_key ] ) : 1;
			$default_author = max( 1, $default_author );
			$this->options->set( $author_key, $default_author );
		}

		// Tier 2: Content Settings: already properly sanitized for text fields
		$this->options->set( 'wisewand_default_length', isset( $_POST['wisewand_default_length'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_length'] ) ) : 'auto' );

		// REMOVED: 26 deprecated content feature settings (v2.8.0)
		// - Content features: use_toc, use_faq, use_bulletlist, use_infotable, use_boldkeywords,
		//   use_externalsources, use_summary, use_blockquotes, use_social
		// - Media settings: use_image, use_inlineimages, inline_images_count, inline_images_ratio,
		//   inline_images_use_palette, inline_images_primary_color, inline_images_secondary_color
		// - Featured image: image_ratio, image_use_palette, image_primary_color, image_secondary_color
		// - Audio settings: add_audio_player, audio_voice_fr, audio_voice_en
		// - Internal links: use_internallinks, use_indexed_pages_internal_links, internal_links_wp_status
		// These settings are now handled per-entry via calendar modal AI instructions.

		$remove_h1_tags = isset( $_POST['remove_h1_tags'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['remove_h1_tags'] ) ) : false;
		$this->options->set( 'wisewand_remove_h1_tags', $remove_h1_tags );

		// System Health & Logs (Log settings)
		$this->options->set( 'wisewand_log_retention_days', isset( $_POST['wisewand_log_retention_days'] ) ? absint( $_POST['wisewand_log_retention_days'] ) : 30 );
		$this->options->set( 'wisewand_log_max_entries', isset( $_POST['wisewand_log_max_entries'] ) ? absint( $_POST['wisewand_log_max_entries'] ) : 1000 );

		// AI Instructions: use rest_sanitize_boolean
		$auto_generate_instructions = isset( $_POST['wisewand_default_auto_generate_instructions'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['wisewand_default_auto_generate_instructions'] ) ) : false;
		$this->options->set( 'wisewand_default_auto_generate_instructions', $auto_generate_instructions );

		// Publication Scheduling Settings
		$time_range        = isset( $_POST['wisewand_calendar_time_range'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_calendar_time_range'] ) ) : 'random';
		$valid_time_ranges = array( 'random', 'morning', 'afternoon', 'evening' );
		if ( ! in_array( $time_range, $valid_time_ranges ) ) {
			$time_range = 'random';
		}
		$this->options->set( 'wisewand_calendar_time_range', $time_range );

		// Allowed publication days (validate at least one day selected)
		if ( isset( $_POST['wisewand_allowed_publication_days'] ) && is_array( $_POST['wisewand_allowed_publication_days'] ) ) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Array is sanitized with array_map below after unslashing
			$raw_days     = wp_unslash( $_POST['wisewand_allowed_publication_days'] );
			$allowed_days = array_map( 'sanitize_text_field', $raw_days );
			// Validate: only days 1-7
			$allowed_days = array_filter(
				$allowed_days,
				function ( $day ) {
					return in_array( $day, array( '1', '2', '3', '4', '5', '6', '7' ) );
				}
			);
			// Ensure at least one day is selected
			if ( empty( $allowed_days ) ) {
				$allowed_days = array( '1', '2', '3', '4', '5' ); // Fallback to Mon-Fri
			}
			$this->options->set( 'wisewand_allowed_publication_days', array_values( $allowed_days ) );
		} else {
			// No days selected - use Mon-Fri default
			$this->options->set( 'wisewand_allowed_publication_days', array( '1', '2', '3', '4', '5' ) );
		}

		$this->options->set( 'wisewand_cannibalization_default_action', isset( $_POST['wisewand_cannibalization_default_action'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_cannibalization_default_action'] ) ) : 'create' );
		$this->options->set( 'wisewand_default_content_merge_strategy', isset( $_POST['wisewand_default_content_merge_strategy'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_content_merge_strategy'] ) ) : 'append' );

		// RSS v2.1.4: Unified Publish Mode Settings
		// Auto-migrate old settings before saving
		Publish_Mode_Migrator::maybe_migrate_global_mode();

		// Get and validate unified publish mode
		$unified_publish_mode = isset( $_POST['rss_publish_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['rss_publish_mode'] ) ) : 'draft';
		$mode_validation      = Schedule_Validator::validate_publish_mode( $unified_publish_mode );

		if ( is_wp_error( $mode_validation ) ) {
			add_settings_error(
				'wisewand_unified_settings',
				'invalid_publish_mode',
				$mode_validation->get_error_message(),
				'error'
			);
			$unified_publish_mode = 'draft'; // Fallback to safe default
		}

		$this->options->set( 'wisewand_rss_publish_mode', $unified_publish_mode );

		// Get and validate publish time (only used if mode is 'scheduled')
		$publish_time    = isset( $_POST['rss_publish_time'] ) ? sanitize_text_field( wp_unslash( $_POST['rss_publish_time'] ) ) : '09:00';
		$time_validation = Schedule_Validator::validate_time_format( $publish_time );

		if ( is_wp_error( $time_validation ) ) {
			add_settings_error(
				'wisewand_unified_settings',
				'invalid_publish_time',
				$time_validation->get_error_message(),
				'error'
			);
			$publish_time = '09:00'; // Fallback to safe default
		}

		$this->options->set( 'wisewand_rss_publish_time', $publish_time );

		// RSS Automation Settings (Missing Logic Fixed)
		$this->options->set( 'wisewand_rss_default_auto_import', isset( $_POST['rss_default_auto_import'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['rss_default_auto_import'] ) ) : false );
		$this->options->set( 'wisewand_rss_default_import_frequency', isset( $_POST['rss_default_import_frequency'] ) ? sanitize_text_field( wp_unslash( $_POST['rss_default_import_frequency'] ) ) : 'every_6_hours' );
		$this->options->set( 'wisewand_rss_default_import_time', isset( $_POST['rss_default_import_time'] ) ? sanitize_text_field( wp_unslash( $_POST['rss_default_import_time'] ) ) : '09:00' );
		$this->options->set( 'wisewand_rss_default_max_articles', isset( $_POST['rss_default_max_articles'] ) ? absint( $_POST['rss_default_max_articles'] ) : 5 );
		// Note: wisewand_rss_default_publish_mode is no longer used - replaced by wisewand_rss_publish_mode above
		$this->options->set( 'wisewand_rss_default_target_author', isset( $_POST['rss_default_target_author'] ) ? absint( $_POST['rss_default_target_author'] ) : 0 );
		$this->options->set( 'wisewand_rss_default_ai_category_matching', isset( $_POST['rss_default_ai_category_matching'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['rss_default_ai_category_matching'] ) ) : false );

		// ACF Settings (Missing Logic Fixed)
		$this->options->set( 'wisewand_acf_enabled', isset( $_POST['wisewand_acf_enabled'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['wisewand_acf_enabled'] ) ) : false );
		$this->options->set( 'wisewand_acf_mode', isset( $_POST['wisewand_acf_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_acf_mode'] ) ) : 'field_key' );

		add_settings_error( 'wisewand_unified_settings', 'settings_saved', __( 'Settings saved successfully!', 'wisewand-ai-content-writer-seo-content-generator' ), 'updated' );

		// Phase 5: Propagate global RSS settings to inheriting feeds
		$this->propagate_global_rss_settings();
	}

	/**
	 * Propagate global RSS settings to feeds with inheritance enabled.
	 *
	 * When global RSS settings are changed, this method notifies the user
	 * how many feeds were automatically updated via inheritance.
	 *
	 * @since 2.1.5
	 */
	public function propagate_global_rss_settings() {
		global $wpdb;

		// Track which settings changed and count affected feeds
		$propagation_messages = array();

		// 1. Import Frequency
		$old_freq = $this->options->get( 'wisewand_rss_default_import_frequency' );
		$new_freq = isset( $_POST['rss_default_import_frequency'] )
			? sanitize_text_field( wp_unslash( $_POST['rss_default_import_frequency'] ) )
			: '';

		if ( ! empty( $new_freq ) && $old_freq !== $new_freq ) {
			$count = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM %i WHERE inherit_import_frequency = %d",
					$wpdb->prefix . 'wisewand_rss_feeds',
					1
				)
			);
			if ( $count > 0 ) {
				$propagation_messages[] = sprintf(
					/* translators: 1: number of feeds, 2: new frequency value */
					__( 'Import frequency updated for %1$d feed(s) to: %2$s', 'wisewand-ai-content-writer-seo-content-generator' ),
					$count,
					esc_html( $new_freq )
				);
			}
		}

		// 2. Max Articles
		$old_max = $this->options->get( 'wisewand_rss_default_max_articles' );
		$new_max = isset( $_POST['rss_default_max_articles'] )
			? absint( $_POST['rss_default_max_articles'] )
			: 0;

		if ( $new_max > 0 && $old_max !== $new_max ) {
			$count = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM %i WHERE inherit_max_articles = %d",
					$wpdb->prefix . 'wisewand_rss_feeds',
					1
				)
			);
			if ( $count > 0 ) {
				$propagation_messages[] = sprintf(
					/* translators: 1: number of feeds, 2: new max articles value */
					__( 'Max articles updated for %1$d feed(s) to: %2$d', 'wisewand-ai-content-writer-seo-content-generator' ),
					$count,
					$new_max
				);
			}
		}

		// 3. Publish Mode
		$old_mode = $this->options->get( 'wisewand_rss_publish_mode' );
		$new_mode = isset( $_POST['rss_publish_mode'] )
			? sanitize_text_field( wp_unslash( $_POST['rss_publish_mode'] ) )
			: '';

		if ( ! empty( $new_mode ) && $old_mode !== $new_mode ) {
			$count = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM %i WHERE inherit_publish_mode = %d",
					$wpdb->prefix . 'wisewand_rss_feeds',
					1
				)
			);
			if ( $count > 0 ) {
				$propagation_messages[] = sprintf(
					/* translators: 1: number of feeds, 2: new publish mode */
					__( 'Publish mode updated for %1$d feed(s) to: %2$s', 'wisewand-ai-content-writer-seo-content-generator' ),
					$count,
					esc_html( $new_mode )
				);
			}
		}

		// 4. Target Author
		$old_author = $this->options->get( 'wisewand_rss_default_target_author' );
		$new_author = isset( $_POST['rss_default_target_author'] )
			? absint( $_POST['rss_default_target_author'] )
			: 0;

		if ( $old_author !== $new_author ) {
			$count = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM %i WHERE inherit_author = %d",
					$wpdb->prefix . 'wisewand_rss_feeds',
					1
				)
			);
			if ( $count > 0 ) {
				$author_obj  = get_user_by( 'ID', $new_author );
				$author_name = $author_obj ? $author_obj->display_name : __( 'default', 'wisewand-ai-content-writer-seo-content-generator' );
				$propagation_messages[] = sprintf(
					/* translators: 1: number of feeds, 2: new author name */
					__( 'Author updated for %1$d feed(s) to: %2$s', 'wisewand-ai-content-writer-seo-content-generator' ),
					$count,
					esc_html( $author_name )
				);
			}
		}

		// 5. AI Category Matching
		$old_ai = $this->options->get( 'wisewand_rss_default_ai_category_matching' );
		$new_ai = isset( $_POST['rss_default_ai_category_matching'] )
			? rest_sanitize_boolean( wp_unslash( $_POST['rss_default_ai_category_matching'] ) )
			: false;

		if ( $old_ai !== $new_ai ) {
			$count = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM %i WHERE inherit_ai_categories = %d",
					$wpdb->prefix . 'wisewand_rss_feeds',
					1
				)
			);
			if ( $count > 0 ) {
				$status = $new_ai
					? __( 'enabled', 'wisewand-ai-content-writer-seo-content-generator' )
					: __( 'disabled', 'wisewand-ai-content-writer-seo-content-generator' );
				$propagation_messages[] = sprintf(
					/* translators: 1: number of feeds, 2: enabled or disabled */
					__( 'AI category matching updated for %1$d feed(s): %2$s', 'wisewand-ai-content-writer-seo-content-generator' ),
					$count,
					esc_html( $status )
				);
			}
		}

		// Display propagation messages
		if ( ! empty( $propagation_messages ) ) {
			foreach ( $propagation_messages as $message ) {
				add_settings_error(
					'wisewand_unified_settings',
					'rss_propagated',
					'🔄 ' . $message,
					'success'
				);
			}
		}
	}

	/**
	 * Detect active third-party plugins and return a status summary.
	 *
	 * Uses Plugin_Detector utility when available; falls back to direct
	 * Options wrapper checks for multilingual, SEO, and e-commerce plugins.
	 *
	 * @since 2.8.2
	 *
	 * @return array {
	 *     Plugin status keyed by category.
	 *
	 *     @type array $multilingual {
	 *         @type bool   $available       Whether a multilingual plugin is active.
	 *         @type string $plugin          Plugin name (e.g., 'WPML').
	 *         @type int    $languages_count Number of active languages.
	 *     }
	 *     @type array $seo {
	 *         @type bool   $available Whether an SEO plugin is active.
	 *         @type string $plugin    Plugin name.
	 *         @type string $version   Plugin version string.
	 *     }
	 *     @type array $ecommerce {
	 *         @type bool   $available     Whether WooCommerce is active.
	 *         @type string $plugin        Plugin name.
	 *         @type int    $product_count Total WooCommerce products.
	 *     }
	 * }
	 */
	public function get_plugin_status() {
		// Load Plugin_Detector if not already loaded
		if ( ! class_exists( 'Wisewand\\Utils\\Plugin_Detector' ) ) {
			$detector_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Plugin_Detector.php';
			if ( file_exists( $detector_file ) ) {
				require_once $detector_file;
			}
		}

		if ( class_exists( 'Wisewand\\Utils\\Plugin_Detector' ) ) {
			return \Wisewand\Utils\Plugin_Detector::get_plugin_status_summary();
		}

		// Fallback detection
		return array(
			'multilingual' => array(
				'available'       => $this->options->is_wpml_active(),
				'plugin'          => $this->options->is_wpml_active() ? 'WPML' : 'None',
				'languages_count' => 0,
			),
			'seo'          => array(
				'available' => $this->options->is_yoast_active() || $this->options->is_rankmath_active(),
				'plugin'    => $this->options->is_yoast_active() ? 'Yoast SEO' : ( $this->options->is_rankmath_active() ? 'Rank Math' : 'None' ),
				'version'   => 'Unknown',
			),
			'ecommerce'    => array(
				'available'     => class_exists( 'WooCommerce' ),
				'plugin'        => class_exists( 'WooCommerce' ) ? 'WooCommerce' : 'None',
				'product_count' => 0,
			),
		);
	}

	/**
	 * Mask an API key for display, showing only the first 8 characters.
	 *
	 * @since 2.8.2
	 *
	 * @param string $key Raw API key.
	 * @return string Masked key or empty string if key is empty.
	 */
	public function mask_api_key( $key ) {
		if ( empty( $key ) ) {
			return '';
		}
		return substr( $key, 0, 8 ) . str_repeat( '*', max( 0, strlen( $key ) - 8 ) );
	}

	/**
	 * Get all persona settings indexed by language code.
	 *
	 * Iterates over every supported language code and retrieves the stored
	 * persona option for each.
	 *
	 * @since 2.8.2
	 *
	 * @return array<string, string> Language-code-keyed persona ID/name values.
	 */
	public function get_all_persona_settings() {
		$personas = array();
		foreach ( \Wisewand\Config\Supported_Options::get_language_codes() as $code ) {
			$personas[ $code ] = $this->options->get( 'wisewand_default_persona_' . $code, '' );
		}
		return $personas;
	}

	/**
	 * Detect active SEO plugins and return their details.
	 *
	 * Checks for Yoast SEO and Rank Math via Options wrapper helpers.
	 *
	 * @since 2.8.2
	 *
	 * @return array<string, array> Keyed by plugin slug ('yoast', 'rankmath').
	 *                              Each entry contains 'name' and 'version'.
	 */
	public function get_detected_seo_plugins() {
		$plugins = array();

		if ( $this->options->is_yoast_active() ) {
			$plugins['yoast'] = array(
				'name'    => 'Yoast SEO',
				'version' => defined( 'WPSEO_VERSION' ) ? WPSEO_VERSION : 'unknown',
			);
		}

		if ( $this->options->is_rankmath_active() ) {
			$plugins['rankmath'] = array(
				'name'    => 'Rank Math',
				'version' => defined( 'RANK_MATH_VERSION' ) ? RANK_MATH_VERSION : 'unknown',
			);
		}

		return $plugins;
	}
}
