<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @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\Logging\Logger;
use Wisewand\Admin\Wisewand_Articles_Page;
use Wisewand\Admin\Wisewand_API_Settings_Page;
use Wisewand\Admin\Wisewand_Projects_Page;
use Wisewand\Admin\SEO_Intelligence_Real;
use Wisewand\Admin\Editorial_Calendar;

class Admin_Manager {

	private $options;
	private $logger;
	private $articles_page;
	private $api_settings_page;
	private $projects_page;
	private $seo_intelligence_page;
	private $editorial_calendar_page;
	private $dashboard_page;
	private $rss_page;

	public function __construct( Options $options, Logger $logger ) {
		$this->options = $options;
		$this->logger  = $logger;

		// Initialize sub-pages
		$this->dashboard_page          = new Dashboard_Page( $options, $logger );
		$this->articles_page           = new Wisewand_Articles_Page( $options, $logger );
		$this->api_settings_page       = new Wisewand_API_Settings_Page( $options, $logger );
		$this->projects_page           = new Wisewand_Projects_Page( $options, $logger );
		$this->seo_intelligence_page   = new SEO_Intelligence_Real( $options, $logger );
		$this->editorial_calendar_page = new Editorial_Calendar( $options, $logger );
		$this->rss_page                = new Wisewand_RSS_Page( $options, $logger );
	}

	public function add_admin_pages() {
		// Main menu page - Dashboard
		add_menu_page(
			__( 'Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ),
			__( 'Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ),
			'edit_posts',
			'wisewand-dashboard',
			array( $this->dashboard_page, 'render_page' ),
			'dashicons-networking',
			30
		);

		// Dashboard submenu (first item, same as parent to avoid duplicate)
		add_submenu_page(
			'wisewand-dashboard',
			__( 'Dashboard', 'wisewand-ai-content-writer-seo-content-generator' ),
			__( '📊 Dashboard', 'wisewand-ai-content-writer-seo-content-generator' ),
			'edit_posts',
			'wisewand-dashboard',
			array( $this->dashboard_page, 'render_page' )
		);

		// Contents submenu
		add_submenu_page(
			'wisewand-dashboard',
			__( 'Contents', 'wisewand-ai-content-writer-seo-content-generator' ),
			__( '📝 Contents', 'wisewand-ai-content-writer-seo-content-generator' ),
			'edit_posts',
			'wisewand-articles',
			array( $this->articles_page, 'render_page' )
		);

		// Keywords intelligence
		add_submenu_page(
			'wisewand-dashboard',
			__( 'Keywords', 'wisewand-ai-content-writer-seo-content-generator' ),
			__( '🎯 Keywords', 'wisewand-ai-content-writer-seo-content-generator' ),
			'edit_posts',
			'wisewand-seo-intelligence',
			array( $this->seo_intelligence_page, 'render_page' )
		);

		// Editorial Calendar (automation & scheduling)
		add_submenu_page(
			'wisewand-dashboard',
			__( 'Editorial Calendar', 'wisewand-ai-content-writer-seo-content-generator' ),
			__( '📅 Calendar', 'wisewand-ai-content-writer-seo-content-generator' ),
			'edit_posts',
			'wisewand-editorial-calendar',
			array( $this->editorial_calendar_page, 'render_page' )
		);

		// RSS Feeds (automated content from RSS sources)
		add_submenu_page(
			'wisewand-dashboard',
			__( 'RSS Feeds', 'wisewand-ai-content-writer-seo-content-generator' ),
			__( '📡 RSS Feeds', 'wisewand-ai-content-writer-seo-content-generator' ),
			'edit_posts',
			'wisewand-rss-feeds',
			array( $this->rss_page, 'render_page' )
		);

		// Settings (consolidated: API + essential settings)
		add_submenu_page(
			'wisewand-dashboard',
			__( 'Wisewand Settings', 'wisewand-ai-content-writer-seo-content-generator' ),
			__( '⚙️ Settings', 'wisewand-ai-content-writer-seo-content-generator' ),
			'manage_options',
			'wisewand-settings',
			array( $this, 'unified_settings_page' )
		);
	}

	public function init_settings() {
		// Register settings groups with sanitization callbacks
		register_setting( 'wisewand_security', 'wisewand_hmac_secret', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'wisewand_security', 'wisewand_timestamp_skew', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_security', 'wisewand_ip_whitelist', array( 'sanitize_callback' => array( $this, 'sanitize_ip_whitelist' ) ) );
		register_setting( 'wisewand_security', 'wisewand_rate_limit_enabled', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_security', 'wisewand_rate_limit_requests', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_security', 'wisewand_rate_limit_window', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_security', 'wisewand_enable_app_passwords', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );

		register_setting( 'wisewand_mapping', 'wisewand_allowed_post_types', array( 'sanitize_callback' => array( $this, 'sanitize_array' ) ) );
		register_setting( 'wisewand_mapping', 'wisewand_default_post_status', array( 'sanitize_callback' => 'sanitize_key' ) );
		register_setting( 'wisewand_mapping', 'wisewand_fallback_author', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_mapping', 'wisewand_auto_create_categories', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_mapping', 'wisewand_auto_create_tags', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_mapping', 'wisewand_allow_slug_override', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_mapping', 'wisewand_media_max_size', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_mapping', 'wisewand_media_timeout', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_mapping', 'wisewand_allowed_mime_types', array( 'sanitize_callback' => array( $this, 'sanitize_array' ) ) );
		register_setting( 'wisewand_mapping', 'wisewand_download_inline_images', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_mapping', 'wisewand_default_inline_images_count', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_mapping', 'wisewand_default_inline_images_ratio', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'wisewand_mapping', 'wisewand_default_inline_images_use_palette', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_mapping', 'wisewand_default_inline_images_primary_color', array( 'sanitize_callback' => 'sanitize_hex_color' ) );
		register_setting( 'wisewand_mapping', 'wisewand_default_inline_images_secondary_color', array( 'sanitize_callback' => 'sanitize_hex_color' ) );
		register_setting( 'wisewand_mapping', 'wisewand_allowed_domains', array( 'sanitize_callback' => array( $this, 'sanitize_allowed_domains' ) ) );
		register_setting( 'wisewand_mapping', 'wisewand_acf_enabled', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_mapping', 'wisewand_acf_mode', array( 'sanitize_callback' => 'sanitize_key' ) );
		register_setting( 'wisewand_mapping', 'wisewand_acf_mapping', array( 'sanitize_callback' => array( $this, 'sanitize_json_array' ) ) );
		register_setting( 'wisewand_mapping', 'wisewand_custom_fields_whitelist', array( 'sanitize_callback' => array( $this, 'sanitize_array' ) ) );

		register_setting( 'wisewand_seo', 'wisewand_seo_mode', array( 'sanitize_callback' => 'sanitize_key' ) );
		register_setting( 'wisewand_seo', 'wisewand_seo_meta_mapping', array( 'sanitize_callback' => array( $this, 'sanitize_json_array' ) ) );

		register_setting( 'wisewand_wpml', 'wisewand_wpml_enabled', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_wpml', 'wisewand_wpml_lang_mapping', array( 'sanitize_callback' => array( $this, 'sanitize_json_array' ) ) );
		register_setting( 'wisewand_wpml', 'wisewand_wpml_default_lang', array( 'sanitize_callback' => 'sanitize_text_field' ) );

		register_setting( 'wisewand_logging', 'wisewand_logging_enabled', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_logging', 'wisewand_debug_mode', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_logging', 'wisewand_log_max_entries', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_logging', 'wisewand_log_retention_days', array( 'sanitize_callback' => 'absint' ) );

		register_setting( 'wisewand_pull', 'wisewand_pull_api_key', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'wisewand_pull', 'wisewand_pull_base_url', array( 'sanitize_callback' => 'esc_url_raw' ) );
		register_setting( 'wisewand_pull', 'wisewand_pull_timeout', array( 'sanitize_callback' => 'absint' ) );
	}

	public function enqueue_admin_assets( $hook ) {
		// Only load on Wisewand pages
		if ( strpos( $hook, 'wisewand' ) === false ) {
			return;
		}

		wp_enqueue_style(
			'wisewand-admin',
			WISEWAND_PLUGIN_URL . 'assets/css/admin.css',
			array(),
			WISEWAND_PLUGIN_VERSION
		);

		// Load SEO Intelligence CSS on SEO Intelligence page
		if ( strpos( $hook, 'wisewand-seo-intelligence' ) !== false ) {
			wp_enqueue_style(
				'wisewand-seo-intelligence',
				WISEWAND_PLUGIN_URL . 'assets/css/seo-intelligence.css',
				array( 'wisewand-admin' ),
				WISEWAND_PLUGIN_VERSION
			);
		}

		wp_enqueue_script(
			'wisewand-admin',
			WISEWAND_PLUGIN_URL . 'assets/js/admin.js',
			array( 'jquery' ),
			WISEWAND_PLUGIN_VERSION,
			true
		);

		wp_localize_script(
			'wisewand-admin',
			'wisewandAdmin',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'wisewand_admin' ),
				'strings' => array(
					'testConnection'    => __( 'Testing connection...', 'wisewand-ai-content-writer-seo-content-generator' ),
					'connectionSuccess' => __( 'Connection successful!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'connectionFailed'  => __( 'Connection failed:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'pullingArticle'    => __( 'Pulling article...', 'wisewand-ai-content-writer-seo-content-generator' ),
					'pullSuccess'       => __( 'Article pulled successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
					'pullFailed'        => __( 'Pull failed:', 'wisewand-ai-content-writer-seo-content-generator' ),
					'confirmPurge'      => __( 'Are you sure you want to purge all logs? This action cannot be undone.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'secretGenerated'   => __( 'New secret generated successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
				),
			)
		);

		// Load Settings page specific scripts
		if ( strpos( $hook, 'wisewand-settings' ) !== false ) {
			wp_enqueue_script(
				'wisewand-settings-admin',
				WISEWAND_PLUGIN_URL . 'assets/js/admin/wisewand-settings-admin.js',
				array( 'jquery' ),
				WISEWAND_PLUGIN_VERSION,
				true
			);

			wp_localize_script(
				'wisewand-settings-admin',
				'wisewandSettings',
				array(
					'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
					'nonces'           => array(
						'apiTest'  => wp_create_nonce( 'wisewand_api_test' ),
						'debug'    => wp_create_nonce( 'wisewand_debug' ),
						'calendar' => wp_create_nonce( 'wisewand_calendar' ),
						'settings' => wp_create_nonce( 'wisewand_settings' ),
					),
					'currentProjectId' => $this->options->get( 'wisewand_default_project_id', '' ),
					'currentPersonaFr' => $this->options->get( 'wisewand_default_persona_fr', '' ),
					'currentPersonaEn' => $this->options->get( 'wisewand_default_persona_en', '' ),
					'i18n'             => array(
						'images'        => esc_js( __( 'images', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'credits'       => esc_js( __( 'credits', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'testing'       => esc_js( __( 'Testing...', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'testApi'       => esc_js( __( 'Test API Connection', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'apiSuccess'    => esc_js( __( 'API connection successful!', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'apiFailed'     => esc_js( __( 'API connection failed:', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'debugging'     => esc_js( __( 'Debugging...', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'debugProjects' => esc_js( __( 'Debug Projects', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'debugFailed'   => esc_js( __( 'Debug failed:', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'selectProject' => esc_js( __( '-- Select Project --', 'wisewand-ai-content-writer-seo-content-generator' ) ),
						'selectPersona' => esc_js( __( '-- Select Persona --', 'wisewand-ai-content-writer-seo-content-generator' ) ),
					),
				)
			);
		}
	}

	public function dashboard_page() {
		$this->render_page_header( __( 'Wisewand Dashboard', 'wisewand-ai-content-writer-seo-content-generator' ) );
		$this->render_dashboard_content();
	}

	public function security_page() {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification performed in handle_security_form_submission()
		if ( isset( $_POST['submit'] ) ) {
			$this->handle_security_form_submission();
		}

		$this->render_page_header( __( 'Security & Authentication', 'wisewand-ai-content-writer-seo-content-generator' ) );
		$this->render_security_content();
	}

	public function mapping_page() {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification performed in handle_mapping_form_submission()
		if ( isset( $_POST['submit'] ) ) {
			$this->handle_mapping_form_submission();
		}

		$this->render_page_header( __( 'Mapping & Fields', 'wisewand-ai-content-writer-seo-content-generator' ) );
		$this->render_mapping_content();
	}

	public function seo_page() {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification performed in handle_seo_form_submission()
		if ( isset( $_POST['submit'] ) ) {
			$this->handle_seo_form_submission();
		}

		$this->render_page_header( __( 'SEO Settings', 'wisewand-ai-content-writer-seo-content-generator' ) );
		$this->render_seo_content();
	}

	public function wpml_page() {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification performed in handle_wpml_form_submission()
		if ( isset( $_POST['submit'] ) ) {
			$this->handle_wpml_form_submission();
		}

		$this->render_page_header( __( 'Languages (WPML)', 'wisewand-ai-content-writer-seo-content-generator' ) );
		$this->render_wpml_content();
	}

	public function logs_page() {
		$this->render_page_header( __( 'Logs & Diagnostics', 'wisewand-ai-content-writer-seo-content-generator' ) );
		$this->render_logs_content();
	}

	public function pull_page() {
		$this->render_page_header( __( 'Pull from Wisewand', 'wisewand-ai-content-writer-seo-content-generator' ) );
		$this->render_pull_content();
	}

	private function render_page_header( $title ) {
		echo '<div class="wrap wisewand-admin">';
		echo '<h1>' . esc_html( $title ) . '</h1>';
	}

	private function render_dashboard_content() {
		$diagnostics = $this->get_system_diagnostics();
		?>
		<div class="wisewand-dashboard">
			<div class="wisewand-cards">
				<div class="wisewand-card">
					<h2><?php esc_html_e( 'System Status', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
					<div class="wisewand-status-grid">
						<?php foreach ( $diagnostics['checks'] as $check => $result ) : ?>
						<div class="wisewand-status-item">
							<span class="wisewand-status-icon <?php echo $result ? 'success' : 'error'; ?>">
								<?php echo esc_html( $result ? '✓' : '✗' ); ?>
							</span>
							<span class="wisewand-status-label"><?php echo esc_html( $this->get_check_label( $check ) ); ?></span>
						</div>
						<?php endforeach; ?>
					</div>
				</div>

				<div class="wisewand-card">
					<h2><?php esc_html_e( 'API Endpoints', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
					<div class="wisewand-endpoints">
						<div class="wisewand-endpoint">
							<strong>POST</strong>
							<code><?php echo esc_url( rest_url( 'wisewand/v1/publish' ) ); ?></code>
							<span class="wisewand-endpoint-desc"><?php esc_html_e( 'Main webhook endpoint', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						</div>
						<div class="wisewand-endpoint">
							<strong>GET</strong>
							<code><?php echo esc_url( rest_url( 'wisewand/v1/diagnose' ) ); ?></code>
							<span class="wisewand-endpoint-desc"><?php esc_html_e( 'System diagnostics', 'wisewand-ai-content-writer-seo-content-generator' ); ?></span>
						</div>
					</div>
				</div>

				<div class="wisewand-card">
					<h2><?php esc_html_e( 'Quick Actions', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
					<div class="wisewand-actions">
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-articles' ) ); ?>" class="button button-primary">
							<?php esc_html_e( 'Browse Articles', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</a>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-settings' ) ); ?>" class="button button-secondary">
							<?php esc_html_e( 'Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</a>
						<button type="button" class="button button-secondary" id="test-connection">
							<?php esc_html_e( 'Test Webhook', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
						</button>
					</div>
				</div>

				<div class="wisewand-card">
					<h2><?php esc_html_e( 'Plugin Information', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
					<table class="wisewand-info-table">
						<tr>
							<td><?php esc_html_e( 'Plugin Version', 'wisewand-ai-content-writer-seo-content-generator' ); ?></td>
							<td><?php echo esc_html( WISEWAND_PLUGIN_VERSION ); ?></td>
						</tr>
						<tr>
							<td><?php esc_html_e( 'WordPress Version', 'wisewand-ai-content-writer-seo-content-generator' ); ?></td>
							<td><?php echo esc_html( get_bloginfo( 'version' ) ); ?></td>
						</tr>
						<tr>
							<td><?php esc_html_e( 'PHP Version', 'wisewand-ai-content-writer-seo-content-generator' ); ?></td>
							<td><?php echo esc_html( PHP_VERSION ); ?></td>
						</tr>
						<tr>
							<td><?php esc_html_e( 'Active Plugins', 'wisewand-ai-content-writer-seo-content-generator' ); ?></td>
							<td>
								<?php if ( $this->options->is_yoast_active() ) : ?>
									<span class="wisewand-plugin-badge">Yoast SEO</span>
								<?php endif; ?>
								<?php if ( $this->options->is_rankmath_active() ) : ?>
									<span class="wisewand-plugin-badge">Rank Math</span>
								<?php endif; ?>
								<?php if ( $this->options->is_wpml_active() ) : ?>
									<span class="wisewand-plugin-badge">WPML</span>
								<?php endif; ?>
								<?php if ( $this->options->is_acf_active() ) : ?>
									<span class="wisewand-plugin-badge">ACF</span>
								<?php endif; ?>
							</td>
						</tr>
						<tr>
							<td><?php esc_html_e( 'Wisewand API', 'wisewand-ai-content-writer-seo-content-generator' ); ?></td>
							<td>
								<?php if ( Wisewand_API_Client::is_api_key_configured() ) : ?>
									<span class="wisewand-status-badge wisewand-status-success">
										<?php esc_html_e( 'Configured', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</span>
									<small><?php echo esc_html( Wisewand_API_Client::get_masked_api_key() ); ?></small>
								<?php else : ?>
									<span class="wisewand-status-badge wisewand-status-warning">
										<?php esc_html_e( 'Not Configured', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</span>
									<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-settings' ) ); ?>" class="button button-small">
										<?php esc_html_e( 'Configure', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</a>
								<?php endif; ?>
							</td>
						</tr>
					</table>
				</div>
			</div>
		</div>
		</div>
		<?php
	}

	private function render_security_content() {
		$security_settings = $this->options->get_security_settings();
		?>
		<form method="post" action="">
			<?php wp_nonce_field( 'wisewand_security_settings' ); ?>

			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'HMAC Authentication', '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="password" name="hmac_secret"
									value="<?php echo esc_attr( $security_settings['hmac_secret'] ); ?>"
									class="regular-text" readonly />
							<button type="button" class="button" id="generate-secret">
								<?php esc_html_e( 'Generate New Secret', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</button>
							<p class="description">
								<?php esc_html_e( 'This secret is used to verify webhook signatures from Wisewand.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Timestamp Skew (seconds)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="number" name="timestamp_skew"
									value="<?php echo esc_attr( $security_settings['timestamp_skew'] ); ?>"
									min="30" max="3600" class="small-text" />
							<p class="description">
								<?php esc_html_e( 'Maximum allowed time difference for replay attack prevention.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>

			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'IP Whitelist', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Allowed IP Addresses', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<textarea name="ip_whitelist" rows="5" cols="50" class="large-text">
							<?php
								echo esc_textarea( $security_settings['ip_whitelist'] );
							?>
							</textarea>
							<p class="description">
								<?php esc_html_e( 'One IP address or CIDR range per line. Leave empty to allow all IPs.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>

			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'Rate Limiting', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Enable Rate Limiting', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="checkbox" name="rate_limit_enabled" value="1"
									<?php checked( $security_settings['rate_limit_enabled'] ); ?> />
							<p class="description">
								<?php esc_html_e( 'Protect against abuse by limiting requests per IP.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Max Requests', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="number" name="rate_limit_requests"
									value="<?php echo esc_attr( $security_settings['rate_limit_requests'] ); ?>"
									min="1" max="1000" class="small-text" />
							<p class="description">
								<?php esc_html_e( 'Maximum number of requests allowed in the time window.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Time Window (seconds)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="number" name="rate_limit_window"
									value="<?php echo esc_attr( $security_settings['rate_limit_window'] ); ?>"
									min="60" max="3600" class="small-text" />
							<p class="description">
								<?php esc_html_e( 'Time window for rate limiting in seconds.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>

			<?php submit_button(); ?>
		</form>
		</div>
		<?php
	}

	private function render_mapping_content() {
		$content_settings = $this->options->get_content_settings();
		$media_settings   = $this->options->get_media_settings();
		$acf_settings     = $this->options->get_acf_settings();
		?>
		<form method="post" action="">
			<?php wp_nonce_field( 'wisewand_mapping_settings' ); ?>

			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'Post Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Allowed Post Types', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php
							$post_types = get_post_types( array( 'public' => true ), 'objects' );
							foreach ( $post_types as $post_type ) :
								?>
							<label>
								<input type="checkbox" name="allowed_post_types[]"
										value="<?php echo esc_attr( $post_type->name ); ?>"
										<?php checked( in_array( $post_type->name, $content_settings['allowed_post_types'] ) ); ?> />
								<?php echo esc_html( $post_type->label ); ?>
							</label><br>
							<?php endforeach; ?>
						</td>
					</tr>
					<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( $content_settings['default_post_status'], 'draft' ); ?>>
									<?php esc_html_e( 'Draft', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
								<option value="publish" <?php selected( $content_settings['default_post_status'], 'publish' ); ?>>
									<?php esc_html_e( 'Published', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
								<option value="pending" <?php selected( $content_settings['default_post_status'], 'pending' ); ?>>
									<?php esc_html_e( 'Pending Review', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
								<option value="private" <?php selected( $content_settings['default_post_status'], 'private' ); ?>>
									<?php esc_html_e( 'Private', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
							</select>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Fallback Author', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<?php
							wp_dropdown_users(
								array(
									'name'             => 'fallback_author',
									'selected'         => $content_settings['fallback_author'],
									'show_option_none' => __( 'Select Author', 'wisewand-ai-content-writer-seo-content-generator' ),
								)
							);
							?>
						</td>
					</tr>
				</table>
			</div>

			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'Taxonomy Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Auto-create Categories', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="checkbox" name="auto_create_categories" value="1"
									<?php checked( $content_settings['auto_create_categories'] ); ?> />
							<p class="description">
								<?php esc_html_e( 'Automatically create categories if they don\'t exist.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Auto-create Tags', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="checkbox" name="auto_create_tags" value="1"
									<?php checked( $content_settings['auto_create_tags'] ); ?> />
							<p class="description">
								<?php esc_html_e( 'Automatically create tags if they don\'t exist.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Allow Slug Override', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="checkbox" name="allow_slug_override" value="1"
									<?php checked( $content_settings['allow_slug_override'] ); ?> />
							<p class="description">
								<?php esc_html_e( 'Allow Wisewand to set custom post slugs.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>

			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'Media Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Max File Size (MB)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="number" name="media_max_size_mb"
									value="<?php echo esc_attr( $media_settings['max_size'] / 1048576 ); ?>"
									min="1" max="100" step="0.1" class="small-text" />
							<p class="description">
								<?php esc_html_e( 'Maximum file size for media downloads.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Download Timeout (seconds)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="number" name="media_timeout"
									value="<?php echo esc_attr( $media_settings['timeout'] ); ?>"
									min="5" max="120" class="small-text" />
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Download Inline Images', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="checkbox" name="download_inline_images" value="1"
									<?php checked( $media_settings['download_inline_images'] ); ?> />
							<p class="description">
								<?php esc_html_e( 'Download and replace external images in content.', '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'] ); ?> />
							<p class="description">
								<?php esc_html_e( 'Add audio player to post content when audio is available.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Audio Player Position', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="audio_player_position">
								<option value="top" <?php selected( $media_settings['audio_player_position'], 'top' ); ?>><?php esc_html_e( 'Top of Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="bottom" <?php selected( $media_settings['audio_player_position'], 'bottom' ); ?>><?php esc_html_e( 'Bottom of Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="none" <?php selected( $media_settings['audio_player_position'], 'none' ); ?>><?php esc_html_e( 'Do Not Add', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</select>
							<p class="description">
								<?php esc_html_e( 'Where to place the audio player in post content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</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'] ); ?> />
							<p class="description">
								<?php esc_html_e( 'Remove H1 tags from content to avoid duplication with WordPress post title.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Allowed Domains', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<textarea name="allowed_domains" rows="3" cols="50" class="large-text">
							<?php
								echo esc_textarea( $media_settings['allowed_domains'] );
							?>
							</textarea>
							<p class="description">
								<?php esc_html_e( 'One domain per line (e.g., cdn.wisewand.ai). Use *.domain.com for subdomains. Leave empty to allow all domains.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>

			<?php if ( $this->options->is_acf_active() ) : ?>
			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'ACF Integration', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Enable ACF Integration', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<input type="checkbox" name="acf_enabled" value="1"
									<?php checked( $acf_settings['enabled'] ); ?> />
							<p class="description">
								<?php esc_html_e( 'Allow Wisewand to update ACF fields.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'ACF Mode', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="acf_mode">
								<option value="field_key" <?php selected( $acf_settings['mode'], 'field_key' ); ?>>
									<?php esc_html_e( 'Field Key (Recommended)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
								<option value="field_name" <?php selected( $acf_settings['mode'], 'field_name' ); ?>>
									<?php esc_html_e( 'Field Name', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
							</select>
							<p class="description">
								<?php esc_html_e( 'How to match ACF fields from Wisewand data.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>
			<?php endif; ?>

			<?php submit_button(); ?>
		</form>
		</div>
		<?php
	}

	private function render_seo_content() {
		$seo_settings     = $this->options->get_seo_settings();
		$detected_plugins = $this->get_detected_seo_plugins();
		?>
		<form method="post" action="">
			<?php wp_nonce_field( 'wisewand_seo_settings' ); ?>

			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'Detected SEO Plugins', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<div class="wisewand-seo-plugins">
					<?php if ( empty( $detected_plugins ) ) : ?>
					<p class="wisewand-notice">
						<?php esc_html_e( 'No SEO plugins detected. SEO data will be stored in Wisewand meta fields.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
					</p>
					<?php else : ?>
						<?php foreach ( $detected_plugins as $plugin ) : ?>
					<div class="wisewand-plugin-detected">
						<span class="wisewand-plugin-icon"><?php echo esc_html( '✓' ); ?></span>
						<strong><?php echo esc_html( $plugin['name'] ); ?></strong>
						<span class="wisewand-plugin-version">v<?php echo esc_html( $plugin['version'] ); ?></span>
					</div>
					<?php endforeach; ?>
					<?php endif; ?>
				</div>
			</div>

			<div class="wisewand-form-section">
				<h2><?php esc_html_e( 'SEO Integration Mode', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Mode', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="seo_mode" id="seo_mode">
								<option value="auto" <?php selected( $seo_settings['mode'], 'auto' ); ?>>
									<?php esc_html_e( 'Auto (Recommended)', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
								<?php if ( isset( $detected_plugins['yoast'] ) ) : ?>
								<option value="yoast_api" <?php selected( $seo_settings['mode'], 'yoast_api' ); ?>>
									<?php esc_html_e( 'Yoast SEO API', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
								<?php endif; ?>
								<?php if ( isset( $detected_plugins['rankmath'] ) ) : ?>
								<option value="rankmath_api" <?php selected( $seo_settings['mode'], 'rankmath_api' ); ?>>
									<?php esc_html_e( 'Rank Math API', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
								<?php endif; ?>
								<option value="meta_mapping" <?php selected( $seo_settings['mode'], 'meta_mapping' ); ?>>
									<?php esc_html_e( 'Custom Meta Mapping', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</option>
							</select>
							<p class="description">
								<?php esc_html_e( 'How to integrate with SEO plugins. Auto mode selects the best available option.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</td>
					</tr>
				</table>
			</div>

			<div class="wisewand-form-section" id="meta_mapping_section"
				style="<?php echo $seo_settings['mode'] === 'meta_mapping' ? '' : 'display:none;'; ?>">
				<h2><?php esc_html_e( 'Meta Field Mapping', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<p class="description">
					<?php esc_html_e( 'Map Wisewand SEO fields to WordPress meta keys. Leave empty to disable a field.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</p>
				<table class="wisewand-seo-mapping">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Wisewand Field', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
							<th><?php esc_html_e( 'WordPress Meta Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php
						$mapping_fields = array(
							'title'               => __( 'SEO Title', 'wisewand-ai-content-writer-seo-content-generator' ),
							'description'         => __( 'Meta Description', 'wisewand-ai-content-writer-seo-content-generator' ),
							'canonical_url'       => __( 'Canonical URL', 'wisewand-ai-content-writer-seo-content-generator' ),
							'focus_keyword'       => __( 'Focus Keyword', 'wisewand-ai-content-writer-seo-content-generator' ),
							'og_title'            => __( 'OpenGraph Title', 'wisewand-ai-content-writer-seo-content-generator' ),
							'og_description'      => __( 'OpenGraph Description', 'wisewand-ai-content-writer-seo-content-generator' ),
							'og_image'            => __( 'OpenGraph Image', 'wisewand-ai-content-writer-seo-content-generator' ),
							'twitter_title'       => __( 'Twitter Title', 'wisewand-ai-content-writer-seo-content-generator' ),
							'twitter_description' => __( 'Twitter Description', 'wisewand-ai-content-writer-seo-content-generator' ),
							'twitter_image'       => __( 'Twitter Image', 'wisewand-ai-content-writer-seo-content-generator' ),
						);

						foreach ( $mapping_fields as $field => $label ) :
							?>
						<tr>
							<td><?php echo esc_html( $label ); ?></td>
							<td>
								<input type="text" name="seo_meta_mapping[<?php echo esc_attr( $field ); ?>]"
										value="<?php echo esc_attr( $seo_settings['meta_mapping'][ $field ] ?? '' ); ?>"
										class="regular-text"
										placeholder="_wisewand_seo_<?php echo esc_attr( $field ); ?>" />
							</td>
						</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>

			<?php submit_button(); ?>
		</form>
		</div>
		<?php
	}

	// AJAX handlers and form processing methods

	public function ajax_test_connection() {
		check_ajax_referer( 'wisewand_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		// Test REST API endpoint
		$test_url = rest_url( 'wisewand/v1/test' );
		$response = wp_remote_post(
			$test_url,
			array(
				'body'    => wp_json_encode( array( 'test_type' => 'ping' ) ),
				'headers' => array( 'Content-Type' => 'application/json' ),
				'timeout' => 10,
			)
		);

		if ( is_wp_error( $response ) ) {
			wp_send_json_error(
				array(
					'message' => $response->get_error_message(),
				)
			);
		}

		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		if ( json_last_error() !== JSON_ERROR_NONE ) {
			wp_send_json_error(
				array(
					'message' => __( 'Invalid JSON response', 'wisewand-ai-content-writer-seo-content-generator' ),
				)
			);
		}

		wp_send_json_success( $data );
	}

	public function ajax_pull_article() {
		check_ajax_referer( 'wisewand_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		$article_id   = isset( $_POST['article_id'] ) ? sanitize_text_field( wp_unslash( $_POST['article_id'] ) ) : '';
		$output_index = absint( $_POST['output_index'] ?? 0 );

		if ( empty( $article_id ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'Article ID is required', 'wisewand-ai-content-writer-seo-content-generator' ),
				)
			);
		}

		// Use REST API to pull the article
		$pull_url = rest_url( 'wisewand/v1/pull' );
		$response = wp_remote_post(
			$pull_url,
			array(
				'body'    => wp_json_encode(
					array(
						'article_id'   => $article_id,
						'output_index' => $output_index,
					)
				),
				'headers' => array(
					'Content-Type'  => 'application/json',
					'Authorization' => 'Bearer ' . wp_create_nonce( 'wp_rest' ),
				),
				'timeout' => 30,
			)
		);

		if ( is_wp_error( $response ) ) {
			wp_send_json_error(
				array(
					'message' => $response->get_error_message(),
				)
			);
		}

		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		if ( json_last_error() !== JSON_ERROR_NONE ) {
			wp_send_json_error(
				array(
					'message' => __( 'Invalid JSON response', 'wisewand-ai-content-writer-seo-content-generator' ),
				)
			);
		}

		if ( isset( $data['success'] ) && $data['success'] ) {
			wp_send_json_success( $data );
		} else {
			wp_send_json_error( $data );
		}
	}

	public function ajax_export_logs() {
		check_ajax_referer( 'wisewand_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		$format = isset( $_POST['format'] ) ? sanitize_text_field( wp_unslash( $_POST['format'] ) ) : 'json';
		$limit  = absint( $_POST['limit'] ?? 1000 );

		$export_data = $this->logger->export_logs( $format, $limit );

		// Validate export data is non-empty string
		if ( empty( $export_data ) || ! is_string( $export_data ) ) {
			wp_die( esc_html__( 'Export data is invalid', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		// For JSON format, validate it's valid JSON
		if ( $format === 'json' ) {
			json_decode( $export_data );
			if ( json_last_error() !== JSON_ERROR_NONE ) {
				wp_die( esc_html__( 'Export data is not valid JSON', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}
		}

		$filename     = 'wisewand-logs-' . gmdate( 'Y-m-d-H-i-s' );
		$content_type = $format === 'csv' ? 'text/csv' : 'application/json';
		$extension    = $format === 'csv' ? 'csv' : 'json';

		header( 'Content-Type: ' . $content_type );
		header( 'Content-Disposition: attachment; filename="' . $filename . '.' . $extension . '"' );
		header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
		header( 'Expires: 0' );

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Validated JSON/CSV data from logger export, safe for file download
		echo $export_data;
		exit;
	}

	public function ajax_purge_logs() {
		check_ajax_referer( 'wisewand_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		$result = $this->logger->purge_logs();

		if ( $result !== false ) {
			wp_send_json_success(
				array(
					'message' => __( 'Logs purged successfully', 'wisewand-ai-content-writer-seo-content-generator' ),
				)
			);
		} else {
			wp_send_json_error(
				array(
					'message' => __( 'Failed to purge logs', 'wisewand-ai-content-writer-seo-content-generator' ),
				)
			);
		}
	}

	// Form submission handlers

	private function handle_security_form_submission() {
		check_admin_referer( 'wisewand_security_settings' );

		// Timestamp skew: validate range 60-3600 seconds (1 minute - 1 hour)
		$timestamp_skew = isset( $_POST['timestamp_skew'] ) ? absint( $_POST['timestamp_skew'] ) : 300;
		$timestamp_skew = max( 60, min( 3600, $timestamp_skew ) );
		$this->options->set( 'wisewand_timestamp_skew', $timestamp_skew );

		// IP whitelist: already properly sanitized
		$this->options->set( 'wisewand_ip_whitelist', isset( $_POST['ip_whitelist'] ) ? sanitize_textarea_field( wp_unslash( $_POST['ip_whitelist'] ) ) : '' );

		// Rate limit enabled: use rest_sanitize_boolean for proper sanitization
		$rate_limit_enabled = isset( $_POST['rate_limit_enabled'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['rate_limit_enabled'] ) ) : false;
		$this->options->set( 'wisewand_rate_limit_enabled', $rate_limit_enabled );

		// Rate limit requests: validate range 10-1000 requests
		$rate_limit_requests = isset( $_POST['rate_limit_requests'] ) ? absint( $_POST['rate_limit_requests'] ) : 60;
		$rate_limit_requests = max( 10, min( 1000, $rate_limit_requests ) );
		$this->options->set( 'wisewand_rate_limit_requests', $rate_limit_requests );

		// Rate limit window: validate range 60-3600 seconds (1 minute - 1 hour)
		$rate_limit_window = isset( $_POST['rate_limit_window'] ) ? absint( $_POST['rate_limit_window'] ) : 600;
		$rate_limit_window = max( 60, min( 3600, $rate_limit_window ) );
		$this->options->set( 'wisewand_rate_limit_window', $rate_limit_window );

		// App passwords: use rest_sanitize_boolean
		$enable_app_passwords = isset( $_POST['enable_app_passwords'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['enable_app_passwords'] ) ) : false;
		$this->options->set( 'wisewand_enable_app_passwords', $enable_app_passwords );

		add_settings_error(
			'wisewand_settings',
			'settings_updated',
			__( 'Security settings saved.', 'wisewand-ai-content-writer-seo-content-generator' ),
			'updated'
		);
	}

	private function handle_mapping_form_submission() {
		check_admin_referer( 'wisewand_mapping_settings' );

		// Post types: already properly sanitized
		$allowed_post_types = isset( $_POST['allowed_post_types'] ) ? array_map( 'sanitize_text_field', map_deep( wp_unslash( $_POST['allowed_post_types'] ), 'sanitize_text_field' ) ) : array();
		$this->options->set( 'wisewand_allowed_post_types', $allowed_post_types );

		// Default post status: already properly sanitized
		$this->options->set( 'wisewand_default_post_status', isset( $_POST['default_post_status'] ) ? sanitize_text_field( wp_unslash( $_POST['default_post_status'] ) ) : 'draft' );

		// Fallback author: validate user ID exists
		$fallback_author = isset( $_POST['fallback_author'] ) ? absint( $_POST['fallback_author'] ) : 1;
		$fallback_author = max( 1, $fallback_author ); // Ensure at least 1
		$this->options->set( 'wisewand_fallback_author', $fallback_author );

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

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

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

		// Media settings: validate max size 1-100 MB
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Cast to float is sufficient sanitization
		$media_max_size_mb = isset( $_POST['media_max_size_mb'] ) ? (float) wp_unslash( $_POST['media_max_size_mb'] ) : 5.0;
		$media_max_size_mb = max( 1.0, min( 100.0, $media_max_size_mb ) ); // Clamp 1-100 MB
		$this->options->set( 'wisewand_media_max_size', $media_max_size_mb * 1048576 );

		// Media timeout: validate range 5-300 seconds
		$media_timeout = isset( $_POST['media_timeout'] ) ? absint( $_POST['media_timeout'] ) : 10;
		$media_timeout = max( 5, min( 300, $media_timeout ) );
		$this->options->set( 'wisewand_media_timeout', $media_timeout );

		// Download inline images: use rest_sanitize_boolean
		$download_inline_images = isset( $_POST['download_inline_images'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['download_inline_images'] ) ) : false;
		$this->options->set( 'wisewand_download_inline_images', $download_inline_images );

		// Allowed domains: already properly sanitized
		$this->options->set( 'wisewand_allowed_domains', isset( $_POST['allowed_domains'] ) ? sanitize_textarea_field( wp_unslash( $_POST['allowed_domains'] ) ) : '' );

		// Add audio player: 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 );

		// Audio player position: already properly sanitized
		$this->options->set( 'wisewand_audio_player_position', isset( $_POST['audio_player_position'] ) ? sanitize_text_field( wp_unslash( $_POST['audio_player_position'] ) ) : 'top' );

		// Remove H1 tags: use rest_sanitize_boolean
		$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 );

		// ACF settings
		if ( $this->options->is_acf_active() ) {
			$acf_enabled = isset( $_POST['acf_enabled'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['acf_enabled'] ) ) : false;
			$this->options->set( 'wisewand_acf_enabled', $acf_enabled );

			$this->options->set( 'wisewand_acf_mode', isset( $_POST['acf_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['acf_mode'] ) ) : 'field_key' );
		}

		add_settings_error(
			'wisewand_settings',
			'settings_updated',
			__( 'Mapping settings saved.', 'wisewand-ai-content-writer-seo-content-generator' ),
			'updated'
		);
	}

	private function handle_seo_form_submission() {
		check_admin_referer( 'wisewand_seo_settings' );

		$this->options->set( 'wisewand_seo_mode', isset( $_POST['seo_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['seo_mode'] ) ) : 'auto' );

		// Handle meta mapping
		if ( isset( $_POST['seo_meta_mapping'] ) && is_array( $_POST['seo_meta_mapping'] ) ) {
			$mapping          = array();
			$seo_meta_mapping = map_deep( wp_unslash( $_POST['seo_meta_mapping'] ), 'sanitize_text_field' );
			foreach ( $seo_meta_mapping as $field => $meta_key ) {
				$mapping[ sanitize_key( $field ) ] = sanitize_text_field( $meta_key );
			}
			$this->options->set( 'wisewand_seo_meta_mapping', $mapping );
		}

		add_settings_error(
			'wisewand_settings',
			'settings_updated',
			__( 'SEO settings saved.', 'wisewand-ai-content-writer-seo-content-generator' ),
			'updated'
		);
	}

	private function handle_wpml_form_submission() {
		check_admin_referer( 'wisewand_wpml_settings' );

		// WPML enabled: use rest_sanitize_boolean
		$wpml_enabled = isset( $_POST['wpml_enabled'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['wpml_enabled'] ) ) : false;
		$this->options->set( 'wisewand_wpml_enabled', $wpml_enabled );

		// WPML default language: already properly sanitized
		$this->options->set( 'wisewand_wpml_default_lang', isset( $_POST['wpml_default_lang'] ) ? sanitize_text_field( wp_unslash( $_POST['wpml_default_lang'] ) ) : '' );

		// Handle language mapping
		if ( isset( $_POST['wpml_lang_mapping'] ) && is_array( $_POST['wpml_lang_mapping'] ) ) {
			$mapping           = array();
			$wpml_lang_mapping = map_deep( wp_unslash( $_POST['wpml_lang_mapping'] ), 'sanitize_text_field' );
			foreach ( $wpml_lang_mapping as $wisewand_code => $wpml_code ) {
				$mapping[ sanitize_text_field( $wisewand_code ) ] = sanitize_text_field( $wpml_code );
			}
			$this->options->set( 'wisewand_wpml_lang_mapping', $mapping );
		}

		add_settings_error(
			'wisewand_settings',
			'settings_updated',
			__( 'WPML settings saved.', 'wisewand-ai-content-writer-seo-content-generator' ),
			'updated'
		);
	}

	// Utility methods

	private function get_system_diagnostics() {
		return array(
			'checks' => array(
				'rest_api'    => rest_url() !== false,
				'permalinks'  => get_option( 'permalink_structure' ) !== '',
				'wp_cron'     => ! defined( 'DISABLE_WP_CRON' ) || ! DISABLE_WP_CRON,
				'hmac_secret' => ! empty( $this->options->get( 'wisewand_hmac_secret' ) ),
				'php_version' => version_compare( PHP_VERSION, '8.0', '>=' ),
				'wp_version'  => version_compare( get_bloginfo( 'version' ), '6.0', '>=' ),
			),
		);
	}

	private function get_check_label( $check ) {
		$labels = array(
			'rest_api'    => __( 'REST API Available', 'wisewand-ai-content-writer-seo-content-generator' ),
			'permalinks'  => __( 'Permalinks Enabled', 'wisewand-ai-content-writer-seo-content-generator' ),
			'wp_cron'     => __( 'WP-Cron Enabled', 'wisewand-ai-content-writer-seo-content-generator' ),
			'hmac_secret' => __( 'HMAC Secret Configured', 'wisewand-ai-content-writer-seo-content-generator' ),
			'php_version' => __( 'PHP 8.0+', 'wisewand-ai-content-writer-seo-content-generator' ),
			'wp_version'  => __( 'WordPress 6.0+', 'wisewand-ai-content-writer-seo-content-generator' ),
		);

		return $labels[ $check ] ?? $check;
	}

	private 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;
	}

	// Additional content rendering methods for logs and WPML pages
	private function render_logs_content() {
		// Implementation for logs page
		echo '<div id="wisewand-logs-content">Logs content here...</div>';
		echo '</div>';
	}

	private function render_wpml_content() {
		// Implementation for WPML page
		echo '<div id="wisewand-wpml-content">WPML content here...</div>';
		echo '</div>';
	}

	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' );

		$this->render_unified_settings_content();
		echo '</div>';
	}

	private 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 Configuration', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h2>
				<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( 'Tier 1: Essential Settings (Required)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<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 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">
								<option value="en" <?php selected( $this->options->get( 'wisewand_fallback_language', 'en' ), 'en' ); ?>>🇺🇸 <?php esc_html_e( 'English', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="fr" <?php selected( $this->options->get( 'wisewand_fallback_language' ), 'fr' ); ?>>🇫🇷 <?php esc_html_e( 'French', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="de" <?php selected( $this->options->get( 'wisewand_fallback_language' ), 'de' ); ?>>🇩🇪 <?php esc_html_e( 'German', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="es" <?php selected( $this->options->get( 'wisewand_fallback_language' ), 'es' ); ?>>🇪🇸 <?php esc_html_e( 'Spanish', 'wisewand-ai-content-writer-seo-content-generator' ); ?></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">
								<option value="us" <?php selected( $this->options->get( 'wisewand_fallback_country', 'us' ), 'us' ); ?>>🇺🇸 <?php esc_html_e( 'United States', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="fr" <?php selected( $this->options->get( 'wisewand_fallback_country' ), 'fr' ); ?>>🇫🇷 <?php esc_html_e( 'France', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="gb" <?php selected( $this->options->get( 'wisewand_fallback_country' ), 'gb' ); ?>>🇬🇧 <?php esc_html_e( 'United Kingdom', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="ca" <?php selected( $this->options->get( 'wisewand_fallback_country' ), 'ca' ); ?>>🇨🇦 <?php esc_html_e( 'Canada', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="de" <?php selected( $this->options->get( 'wisewand_fallback_country' ), 'de' ); ?>>🇩🇪 <?php esc_html_e( 'Germany', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="es" <?php selected( $this->options->get( 'wisewand_fallback_country' ), 'es' ); ?>>🇪🇸 <?php esc_html_e( 'Spain', 'wisewand-ai-content-writer-seo-content-generator' ); ?></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">
					<tr>
						<th scope="row"><?php esc_html_e( 'French Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label><strong><?php esc_html_e( 'Persona:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong></label><br>
							<select name="wisewand_default_persona_fr" id="persona-fr-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_fr">
								<?php
								$users = get_users(
									array(
										'capability' => 'edit_posts',
										'orderby'    => 'display_name',
									)
								);
								foreach ( $users as $user ) {
									$selected = selected( $this->options->get( 'wisewand_default_author_fr', 1 ), $user->ID, false );
									echo '<option value="' . esc_attr( $user->ID ) . '" ' . esc_attr( $selected ) . '>' . esc_html( $user->display_name ) . ' (ID: ' . esc_html( $user->ID ) . ')</option>';
								}
								?>
							</select>
							<p class="description"><?php esc_html_e( 'French articles will use this persona and be authored by this WordPress user when imported.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'English Content', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label><strong><?php esc_html_e( 'Persona:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong></label><br>
							<select name="wisewand_default_persona_en" id="persona-en-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_en">
								<?php
								foreach ( $users as $user ) {
									$selected = selected( $this->options->get( 'wisewand_default_author_en', 1 ), $user->ID, false );
									echo '<option value="' . esc_attr( $user->ID ) . '" ' . esc_attr( $selected ) . '>' . esc_html( $user->display_name ) . ' (ID: ' . esc_html( $user->ID ) . ')</option>';
								}
								?>
							</select>
							<p class="description"><?php esc_html_e( 'English articles will use this persona and be authored by this WordPress user when imported.', '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( 'Tier 2: Content & Media Defaults', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Default Article Length', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<select name="wisewand_default_length">
								<option value="auto" <?php selected( $this->options->get( 'wisewand_default_length', 'auto' ), 'auto' ); ?>><?php esc_html_e( 'Auto (Recommended)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="800" <?php selected( $this->options->get( 'wisewand_default_length' ), '800' ); ?>>~800 <?php esc_html_e( 'words', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="1000" <?php selected( $this->options->get( 'wisewand_default_length' ), '1000' ); ?>>~1,000 <?php esc_html_e( 'words', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="1500" <?php selected( $this->options->get( 'wisewand_default_length' ), '1500' ); ?>>~1,500 <?php esc_html_e( 'words', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="2000" <?php selected( $this->options->get( 'wisewand_default_length' ), '2000' ); ?>>~2,000 <?php esc_html_e( 'words', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="3000" <?php selected( $this->options->get( 'wisewand_default_length' ), '3000' ); ?>>~3,000 <?php esc_html_e( 'words', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="5000" <?php selected( $this->options->get( 'wisewand_default_length' ), '5000' ); ?>>~5,000 <?php esc_html_e( 'words', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</select>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Default Content Features', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label><input type="checkbox" name="wisewand_default_use_toc" value="1" <?php checked( $this->options->get( 'wisewand_default_use_toc', true ), true ); ?>> <?php esc_html_e( 'Table of Contents', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_use_faq" value="1" <?php checked( $this->options->get( 'wisewand_default_use_faq', true ), true ); ?>> <?php esc_html_e( 'FAQ Section', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_use_bulletlist" value="1" <?php checked( $this->options->get( 'wisewand_default_use_bulletlist', true ), true ); ?>> <?php esc_html_e( 'Bullet Lists', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_use_infotable" value="1" <?php checked( $this->options->get( 'wisewand_default_use_infotable', false ), true ); ?>> <?php esc_html_e( 'Info Tables', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_use_boldkeywords" value="1" <?php checked( $this->options->get( 'wisewand_default_use_boldkeywords', true ), true ); ?>> <?php esc_html_e( 'Bold Keywords', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_use_externalsources" value="1" <?php checked( $this->options->get( 'wisewand_default_use_externalsources', true ), true ); ?>> <?php esc_html_e( 'External Sources', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_use_summary" value="1" <?php checked( $this->options->get( 'wisewand_default_use_summary', true ), true ); ?>> <?php esc_html_e( 'Article Summary', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_use_blockquotes" value="1" <?php checked( $this->options->get( 'wisewand_default_use_blockquotes', true ), true ); ?>> <?php esc_html_e( 'Blockquotes', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Default Media Features', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <br><small style="color: #f59e0b;"><?php esc_html_e( '(Costs Credits)', 'wisewand-ai-content-writer-seo-content-generator' ); ?></small></th>
						<td>
							<label><input type="checkbox" name="wisewand_default_use_image" value="1" <?php checked( $this->options->get( 'wisewand_default_use_image', true ), true ); ?>> <?php esc_html_e( 'Featured Image', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="color: #92400e; background: #fef3c7; padding: 2px 6px; border-radius: 4px; font-size: 11px; font-weight: 700;">+0.5</span></label><br>
							<label>
								<input type="checkbox" name="wisewand_default_use_inlineimages" id="toggle-inline-images-setting" value="1" <?php checked( $this->options->get( 'wisewand_default_use_inlineimages', false ), true ); ?>>
								<?php esc_html_e( 'Inline Images', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								<span id="settings-inline-cost" style="color: #92400e; background: #fef3c7; padding: 2px 6px; border-radius: 4px; font-size: 11px; font-weight: 700;">+<?php echo esc_html( number_format( $this->options->get( 'wisewand_default_inline_images_count', 1 ) * 0.25, 2 ) ); ?></span>
							</label>
							<div id="settings-inline-count-config" style="<?php echo ! $this->options->get( 'wisewand_default_use_inlineimages', false ) ? 'display:none;' : ''; ?> margin-left: 24px; margin-top: 12px; margin-bottom: 12px; padding: 12px; background: rgba(59, 130, 246, 0.05); border-left: 3px solid #3b82f6; border-radius: 4px;">
								<label style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
									<span style="font-size: 13px; color: #374151; font-weight: 500; min-width: 80px;">
										<?php esc_html_e( 'Count:', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</span>
									<input type="range" name="wisewand_default_inline_images_count"
											id="settings-inline-count-slider"
											min="1" max="10" step="1"
											oninput="document.getElementById('settings-inline-count-value').innerText = this.value + ' <?php esc_html_e( 'images', 'wisewand-ai-content-writer-seo-content-generator' ); ?>'; document.getElementById('settings-inline-count-cost').innerHTML = this.value + ' &times; 0.25 = ' + (this.value * 0.25).toFixed(2) + ' <?php esc_html_e( 'credits', 'wisewand-ai-content-writer-seo-content-generator' ); ?>';"
											value="<?php echo esc_attr( $this->options->get( 'wisewand_default_inline_images_count', 1 ) ); ?>"
											style="flex: 1; max-width: 200px;">
									<span id="settings-inline-count-value" style="font-size: 14px; font-weight: 600; color: #3b82f6; min-width: 60px; text-align: center;">
										<?php echo esc_html( $this->options->get( 'wisewand_default_inline_images_count', 1 ) ); ?> <?php esc_html_e( 'images', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</span>
								</label>
								<label style="margin-top: 8px; display: block;"><?php esc_html_e( 'Inline Images Ratio:', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									<select name="wisewand_default_inline_images_ratio">
										<option value="landscape" <?php selected( $this->options->get( 'wisewand_default_inline_images_ratio', 'landscape' ), 'landscape' ); ?>><?php esc_html_e( 'Landscape', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
										<option value="portrait" <?php selected( $this->options->get( 'wisewand_default_inline_images_ratio' ), 'portrait' ); ?>><?php esc_html_e( 'Portrait', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
										<option value="square" <?php selected( $this->options->get( 'wisewand_default_inline_images_ratio' ), 'square' ); ?>><?php esc_html_e( 'Square', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
									</select>
								</label>
								<label style="margin-top: 8px; display: block;">
									<input type="checkbox" name="wisewand_default_inline_images_use_palette" id="toggle-inline-images-palette" value="1" <?php checked( $this->options->get( 'wisewand_default_inline_images_use_palette', false ), true ); ?>>
									<?php esc_html_e( 'Use Brand Colors for Inline Images', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
								</label>
								<div id="settings-inline-colors-config" style="<?php echo ! $this->options->get( 'wisewand_default_inline_images_use_palette', false ) ? 'display:none;' : ''; ?> margin-top: 8px;">
									<input type="color" name="wisewand_default_inline_images_primary_color" value="<?php echo esc_attr( $this->options->get( 'wisewand_default_inline_images_primary_color', '#3b82f6' ) ); ?>" />
									<input type="color" name="wisewand_default_inline_images_secondary_color" value="<?php echo esc_attr( $this->options->get( 'wisewand_default_inline_images_secondary_color', '#1e3a8a' ) ); ?>" />
								</div>
								<p style="font-size: 11px; color: #6b7280; margin: 0; padding-left: 92px;">
									<span id="settings-inline-count-cost" style="color: #92400e; font-weight: 600; background: #fef3c7; padding: 2px 8px; border-radius: 8px; display: inline-block;">
										<?php
										$count = $this->options->get( 'wisewand_default_inline_images_count', 1 );
										echo esc_html( $count ) . ' × 0.25 = ' . esc_html( number_format( $count * 0.25, 2 ) ) . ' ' . esc_html__( 'credits', 'wisewand-ai-content-writer-seo-content-generator' );
										?>
									</span>
									<span style="margin-left: 8px; color: #9ca3af;">
										<?php esc_html_e( 'API supports 1-10 inline images per article', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
									</span>
								</p>
							</div><br>
							<label><input type="checkbox" name="wisewand_default_use_social" value="1" <?php checked( $this->options->get( 'wisewand_default_use_social', false ), true ); ?>> <?php esc_html_e( 'Social Media Posts', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="color: #92400e; background: #fef3c7; padding: 2px 6px; border-radius: 4px; font-size: 11px; font-weight: 700;">+0.5</span></label><br>
							<label><input type="checkbox" name="wisewand_default_use_audio" value="1" <?php checked( $this->options->get( 'wisewand_default_use_audio', false ), true ); ?>> <?php esc_html_e( 'Audio Version', 'wisewand-ai-content-writer-seo-content-generator' ); ?> <span style="color: #92400e; background: #fed7aa; padding: 2px 6px; border-radius: 4px; font-size: 11px; font-weight: 700;">+1.0</span></label>
							<p class="description"><?php esc_html_e( 'Enable media features by default. Cost depends on inline images count. Max with all enabled: 0.5 + (10 × 0.25) + 0.5 + 1.0 = 4.5 credits', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Image Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label><?php esc_html_e( 'Default Ratio:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<select name="wisewand_default_image_ratio">
								<option value="landscape" <?php selected( $this->options->get( 'wisewand_default_image_ratio', 'landscape' ), 'landscape' ); ?>><?php esc_html_e( 'Landscape', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
								<option value="portrait" <?php selected( $this->options->get( 'wisewand_default_image_ratio' ), 'portrait' ); ?>><?php esc_html_e( 'Portrait', 'wisewand-ai-content-writer-seo-content-generator' ); ?></option>
							</select>
							<br><br>
							<label><input type="checkbox" name="wisewand_default_image_use_palette" value="1" <?php checked( $this->options->get( 'wisewand_default_image_use_palette', false ), true ); ?>> <?php esc_html_e( 'Use Brand Colors', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<br><br>
							<label><?php esc_html_e( 'Primary Color:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<input type="color" name="wisewand_default_image_primary_color" value="<?php echo esc_attr( $this->options->get( 'wisewand_default_image_primary_color', '#3b82f6' ) ); ?>" />
							<label style="margin-left: 20px;"><?php esc_html_e( 'Secondary Color:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<input type="color" name="wisewand_default_image_secondary_color" value="<?php echo esc_attr( $this->options->get( 'wisewand_default_image_secondary_color', '#1e3a8a' ) ); ?>" />
						</td>
					</tr>
				</table>

				<h3 style="margin-top: 30px; border-top: 1px solid #e2e8f0; padding-top: 20px;">🎧 <?php esc_html_e( 'Tier 3: Advanced Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<table class="form-table">
					<tr>
						<th scope="row"><?php esc_html_e( 'Audio Voice Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label><strong><?php esc_html_e( 'French Content:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong></label><br>
			<select name="wisewand_default_audio_voice_fr" class="regular-text" style="min-width: 400px;">
				<?php
				if ( ! class_exists( 'Wisewand\\Config\\Audio_Voices' ) ) {
					require_once WISEWAND_PLUGIN_DIR . 'includes/Config/Audio_Voices.php';
				}
				$all_voices       = \Wisewand\Config\Audio_Voices::get_all_voices();
				$current_voice_fr = $this->options->get( 'wisewand_default_audio_voice_fr', 'jSrrwmj13CIlQAXPpk4X' );

				// Group by language
				$voices_by_lang = array();
				foreach ( $all_voices as $voice ) {
					$voices_by_lang[ $voice['language'] ][] = $voice;
				}

				// Render with optgroups
				foreach ( $voices_by_lang as $lang => $voices ) {
					$lang_label = $lang === 'fr' ? '🇫🇷 French' : '🇬🇧 English';
					echo '<optgroup label="' . esc_attr( $lang_label ) . '">';
					foreach ( $voices as $voice ) {
						$selected = selected( $current_voice_fr, $voice['id'], false );
						echo '<option value="' . esc_attr( $voice['id'] ) . '" ' . esc_attr( $selected ) . '>' . esc_html( \Wisewand\Config\Audio_Voices::format_voice_name( $voice ) ) . '</option>';
					}
					echo '</optgroup>';
				}
				?>
			</select>
							<br><br>
							<label><strong><?php esc_html_e( 'English Content:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong></label><br>
			<select name="wisewand_default_audio_voice_en" class="regular-text" style="min-width: 400px;">
				<?php
				$current_voice_en = $this->options->get( 'wisewand_default_audio_voice_en', 'EXAVITQu4vr4xnSDxMaL' );

				// Reuse the same $all_voices and $voices_by_lang from above
				foreach ( $voices_by_lang as $lang => $voices ) {
					$lang_label = $lang === 'fr' ? '🇫🇷 French' : '🇬🇧 English';
					echo '<optgroup label="' . esc_attr( $lang_label ) . '">';
					foreach ( $voices as $voice ) {
						$selected = selected( $current_voice_en, $voice['id'], false );
						echo '<option value="' . esc_attr( $voice['id'] ) . '" ' . esc_attr( $selected ) . '>' . esc_html( \Wisewand\Config\Audio_Voices::format_voice_name( $voice ) ) . '</option>';
					}
					echo '</optgroup>';
				}
				?>
			</select>
							<p class="description"><?php esc_html_e( 'Default voice for audio generation, selected automatically based on article language.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Internal Links Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?></th>
						<td>
							<label><input type="checkbox" name="wisewand_default_use_internallinks" value="1" <?php checked( $this->options->get( 'wisewand_default_use_internallinks', true ), true ); ?>> <?php esc_html_e( 'Use Internal Links', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_use_indexed_pages_internal_links" value="1" <?php checked( $this->options->get( 'wisewand_default_use_indexed_pages_internal_links', true ), true ); ?>> <?php esc_html_e( 'From Indexed Pages', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<br><br>
							<label><?php esc_html_e( 'WordPress Post Status Filter:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label><br>
							<label><input type="checkbox" name="wisewand_default_internal_links_wp_status[]" value="publish" <?php checked( in_array( 'publish', $this->options->get( 'wisewand_default_internal_links_wp_status', array( 'publish' ) ) ), true ); ?>> <?php esc_html_e( 'Published', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<label style="margin-left: 12px;"><input type="checkbox" name="wisewand_default_internal_links_wp_status[]" value="draft" <?php checked( in_array( 'draft', $this->options->get( 'wisewand_default_internal_links_wp_status', array( 'publish' ) ) ), true ); ?>> <?php esc_html_e( 'Draft', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
							<label style="margin-left: 12px;"><input type="checkbox" name="wisewand_default_internal_links_wp_status[]" value="future" <?php checked( in_array( 'future', $this->options->get( 'wisewand_default_internal_links_wp_status', array( 'publish' ) ) ), true ); ?>> <?php esc_html_e( 'Scheduled', 'wisewand-ai-content-writer-seo-content-generator' ); ?></label>
						</td>
					</tr>
					<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( '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; ?>
							<p class="description">
								<?php esc_html_e( 'Roadmap will only schedule posts on selected days. Posts are randomly distributed across your selected days each week for natural scheduling patterns. If you request more posts per week than allowed days, they will automatically spread across multiple weeks.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
							<p class="description" style="color: #dc2626;">
								⚠️ <strong><?php esc_html_e( 'Important:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong> <?php esc_html_e( 'At least one day must be selected.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</p>
						</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>

			<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>
		</form>
		<?php
	}

	private 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 ) ) {
			// Load DataForSEO_Client to use the store method
			if ( ! class_exists( 'Wisewand\\Utils\\DataForSEO_Client' ) ) {
				$client_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/DataForSEO_Client.php';
				if ( file_exists( $client_file ) ) {
					require_once $client_file;
				}
			}

			if ( class_exists( 'Wisewand\\Utils\\DataForSEO_Client' ) ) {
				\Wisewand\Utils\DataForSEO_Client::store_credentials( $dataforseo_login, $dataforseo_password );
			} else {
				// Fallback storage
				$this->options->set( 'wisewand_dataforseo_login', $dataforseo_login );
				$this->options->set( 'wisewand_dataforseo_password', $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 );

		$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
		$this->options->set( 'wisewand_default_project_id', isset( $_POST['wisewand_default_project_id'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_project_id'] ) ) : '' );
		$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' );

		// Persona & Author Mapping: already properly sanitized for personas
		$this->options->set( 'wisewand_default_persona_fr', isset( $_POST['wisewand_default_persona_fr'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_persona_fr'] ) ) : '' );
		$this->options->set( 'wisewand_default_persona_en', isset( $_POST['wisewand_default_persona_en'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_persona_en'] ) ) : '' );

		// Author IDs: validate they are positive integers
		$default_author_fr = isset( $_POST['wisewand_default_author_fr'] ) ? absint( $_POST['wisewand_default_author_fr'] ) : 1;
		$default_author_fr = max( 1, $default_author_fr ); // Ensure at least 1
		$this->options->set( 'wisewand_default_author_fr', $default_author_fr );

		$default_author_en = isset( $_POST['wisewand_default_author_en'] ) ? absint( $_POST['wisewand_default_author_en'] ) : 1;
		$default_author_en = max( 1, $default_author_en ); // Ensure at least 1
		$this->options->set( 'wisewand_default_author_en', $default_author_en );

		// 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' );

		// Content feature boolean settings: use rest_sanitize_boolean
		$use_toc = isset( $_POST['wisewand_default_use_toc'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['wisewand_default_use_toc'] ) ) : false;
		$this->options->set( 'wisewand_default_use_toc', $use_toc );

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

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

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

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

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

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

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

		// Media Settings: boolean settings use rest_sanitize_boolean
		$use_image = isset( $_POST['wisewand_default_use_image'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['wisewand_default_use_image'] ) ) : false;
		$this->options->set( 'wisewand_default_use_image', $use_image );

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

		// Inline images count: validate range 1-10
		$inline_images_count = isset( $_POST['wisewand_default_inline_images_count'] ) ? absint( $_POST['wisewand_default_inline_images_count'] ) : 1;
		$inline_images_count = max( 1, min( 10, $inline_images_count ) ); // Clamp 1-10
		$this->options->set( 'wisewand_default_inline_images_count', $inline_images_count );

		$inline_images_ratio = isset( $_POST['wisewand_default_inline_images_ratio'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_inline_images_ratio'] ) ) : 'landscape';
		$this->options->set( 'wisewand_default_inline_images_ratio', $inline_images_ratio );

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

		$inline_images_primary = isset( $_POST['wisewand_default_inline_images_primary_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['wisewand_default_inline_images_primary_color'] ) ) : '#3b82f6';
		$this->options->set( 'wisewand_default_inline_images_primary_color', $inline_images_primary );

		$inline_images_secondary = isset( $_POST['wisewand_default_inline_images_secondary_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['wisewand_default_inline_images_secondary_color'] ) ) : '#1e3a8a';
		$this->options->set( 'wisewand_default_inline_images_secondary_color', $inline_images_secondary );

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

		$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 );

		// Image settings: already properly sanitized for text/color fields
		$this->options->set( 'wisewand_default_image_ratio', isset( $_POST['wisewand_default_image_ratio'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_image_ratio'] ) ) : 'landscape' );

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

		$this->options->set( 'wisewand_default_image_primary_color', isset( $_POST['wisewand_default_image_primary_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['wisewand_default_image_primary_color'] ) ) : '#3b82f6' );
		$this->options->set( 'wisewand_default_image_secondary_color', isset( $_POST['wisewand_default_image_secondary_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['wisewand_default_image_secondary_color'] ) ) : '#1e3a8a' );

		// 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' ) );
		}

		// Tier 3: Advanced: already properly sanitized for text fields
		$this->options->set( 'wisewand_default_audio_voice_fr', isset( $_POST['wisewand_default_audio_voice_fr'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_audio_voice_fr'] ) ) : 'jSrrwmj13CIlQAXPpk4X' );
		$this->options->set( 'wisewand_default_audio_voice_en', isset( $_POST['wisewand_default_audio_voice_en'] ) ? sanitize_text_field( wp_unslash( $_POST['wisewand_default_audio_voice_en'] ) ) : 'EXAVITQu4vr4xnSDxMaL' );

		// Internal links boolean settings: use rest_sanitize_boolean
		$use_internallinks = isset( $_POST['wisewand_default_use_internallinks'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['wisewand_default_use_internallinks'] ) ) : false;
		$this->options->set( 'wisewand_default_use_internallinks', $use_internallinks );

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

		// Internal links WP status (array)
		if ( isset( $_POST['wisewand_default_internal_links_wp_status'] ) && is_array( $_POST['wisewand_default_internal_links_wp_status'] ) ) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Array is sanitized with array_map below after unslashing
			$raw_array                = wp_unslash( $_POST['wisewand_default_internal_links_wp_status'] );
			$internal_links_wp_status = array_map( 'sanitize_text_field', $raw_array );
		} else {
			$internal_links_wp_status = array( 'publish' );
		}
		$this->options->set( 'wisewand_default_internal_links_wp_status', $internal_links_wp_status );

		// Cannibalization handling settings (Change 3: Safe defaults)
		$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' );

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

	public function ajax_debug_projects() {
		check_ajax_referer( 'wisewand_debug', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$api_key = Wisewand_API_Client::get_stored_api_key();
		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => __( 'No API key configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$api_client   = new Wisewand_API_Client( $api_key, $this->logger );
		$debug_result = $api_client->debug_projects();

		if ( is_wp_error( $debug_result ) ) {
			wp_send_json_error( array( 'message' => $debug_result->get_error_message() ) );
		}

		wp_send_json_success( $debug_result );
	}

	private 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,
			),
		);
	}

	// Getter methods for sub-pages
	public function get_articles_page() {
		return $this->articles_page;
	}

	public function get_api_settings_page() {
		return $this->api_settings_page;
	}

	public function get_projects_page() {
		return $this->projects_page;
	}

	public function get_seo_intelligence_page() {
		return $this->seo_intelligence_page;
	}

	public function get_editorial_calendar_page() {
		return $this->editorial_calendar_page;
	}

	public function get_rss_page() {
		return $this->rss_page;
	}

	public function get_dashboard_page() {
		return $this->dashboard_page;
	}

	private function mask_api_key( $key ) {
		if ( empty( $key ) ) {
			return '';
		}
		return substr( $key, 0, 8 ) . str_repeat( '*', max( 0, strlen( $key ) - 8 ) );
	}

	/**
	 * Sanitize IP whitelist textarea
	 *
	 * @param string $value Raw IP whitelist value
	 * @return string Sanitized IP whitelist
	 */
	public function sanitize_ip_whitelist( $value ) {
		if ( empty( $value ) ) {
			return '';
		}

		// Split by newlines and sanitize each IP
		$ips           = explode( "\n", $value );
		$sanitized_ips = array();

		foreach ( $ips as $ip ) {
			$ip = trim( $ip );
			if ( empty( $ip ) ) {
				continue;
			}

			// Allow CIDR notation (IP/mask)
			if ( strpos( $ip, '/' ) !== false ) {
				list($ip_part, $mask_part) = explode( '/', $ip, 2 );
				$ip_part                   = trim( $ip_part );
				$mask_part                 = trim( $mask_part );

				// Validate IP and mask
				if ( filter_var( $ip_part, FILTER_VALIDATE_IP ) && is_numeric( $mask_part ) ) {
					$mask = absint( $mask_part );
					if ( $mask >= 0 && $mask <= 32 ) {
						$sanitized_ips[] = $ip_part . '/' . $mask;
					}
				}
			} else {
				// Validate single IP
				if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) {
					$sanitized_ips[] = $ip;
				}
			}
		}

		return implode( "\n", $sanitized_ips );
	}

	/**
	 * Sanitize array values
	 *
	 * @param mixed $value Raw array value
	 * @return array Sanitized array
	 */
	public function sanitize_array( $value ) {
		if ( ! is_array( $value ) ) {
			return array();
		}

		return array_map( 'sanitize_text_field', $value );
	}

	/**
	 * Sanitize allowed domains textarea
	 *
	 * @param string $value Raw allowed domains value
	 * @return string Sanitized allowed domains
	 */
	public function sanitize_allowed_domains( $value ) {
		if ( empty( $value ) ) {
			return '';
		}

		// Split by newlines and sanitize each domain
		$domains           = explode( "\n", $value );
		$sanitized_domains = array();

		foreach ( $domains as $domain ) {
			$domain = trim( $domain );
			if ( empty( $domain ) ) {
				continue;
			}

			// Sanitize domain (allow wildcards like *.example.com)
			$domain = sanitize_text_field( $domain );

			// Basic domain validation (allow wildcards)
			if ( preg_match( '/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i', $domain ) ) {
				$sanitized_domains[] = $domain;
			}
		}

		return implode( "\n", $sanitized_domains );
	}

	/**
	 * Sanitize JSON array field
	 *
	 * @param mixed $value Raw JSON value (can be string or array)
	 * @return array Sanitized array
	 */
	public function sanitize_json_array( $value ) {
		// If already an array, sanitize it
		if ( is_array( $value ) ) {
			return $this->sanitize_array_recursive( $value );
		}

		// If string, try to decode JSON
		if ( is_string( $value ) ) {
			$decoded = json_decode( $value, true );
			if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
				return $this->sanitize_array_recursive( $decoded );
			}
		}

		return array();
	}

	/**
	 * Recursively sanitize array values
	 *
	 * @param array $array Raw array
	 * @return array Sanitized array
	 */
	private function sanitize_array_recursive( $array ) {
		$sanitized = array();

		foreach ( $array as $key => $value ) {
			$key = sanitize_key( $key );

			if ( is_array( $value ) ) {
				$sanitized[ $key ] = $this->sanitize_array_recursive( $value );
			} elseif ( is_string( $value ) ) {
				$sanitized[ $key ] = sanitize_text_field( $value );
			} elseif ( is_numeric( $value ) ) {
				$sanitized[ $key ] = $value;
			} elseif ( is_bool( $value ) ) {
				$sanitized[ $key ] = $value;
			}
		}

		return $sanitized;
	}
}