<?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\Utils\Publish_Mode_Migrator;
use Wisewand\Utils\Timezone_Helper;
use Wisewand\Utils\Schedule_Validator;
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;
use Wisewand\Admin\Settings_Page;
use Wisewand\Admin\Traits\AJAX_Security;

class Admin_Manager {

	use AJAX_Security;

	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;
	private $settings_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 );
		$this->settings_page           = new Settings_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_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' ) );

		// CRON Settings
		register_setting( 'wisewand_cron', 'wisewand_cron_daily_hour', array( 'sanitize_callback' => 'absint' ) );

		// RSS Global Defaults
		register_setting( 'wisewand_rss_defaults', 'wisewand_rss_default_import_frequency', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'wisewand_rss_defaults', 'wisewand_rss_default_max_articles', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_rss_defaults', 'wisewand_rss_default_publish_mode', array( 'sanitize_callback' => 'sanitize_key' ) );
		register_setting( 'wisewand_rss_defaults', 'wisewand_rss_default_target_author', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'wisewand_rss_defaults', 'wisewand_rss_default_ai_category_matching', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
		register_setting( 'wisewand_rss_defaults', 'wisewand_rss_default_auto_import', array( 'sanitize_callback' => 'rest_sanitize_boolean' ) );
	}

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



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

		// Editorial Calendar page specific scripts
		if ( strpos( $hook, 'editorial-calendar' ) !== false && $this->editorial_calendar_page ) {
			$this->editorial_calendar_page->enqueue_assets();
		}

		// 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', '' ),
					'currentPersonas'    => $this->get_all_persona_settings(),
					'supportedLanguages' => \Wisewand\Config\Supported_Options::get_languages(),
					'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_wpml_active() ) : ?>
									<span class="wisewand-plugin-badge">WPML</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();
		?>
		<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="immediate" <?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 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() {
		$this->verify_ajax_request( 'wisewand_admin', 'manage_options' );

		// 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() {
		$this->verify_ajax_request( 'wisewand_admin', 'manage_options' );

		$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() {
		$this->verify_ajax_request( 'wisewand_admin', 'manage_options' );

		$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() {
		$this->verify_ajax_request( 'wisewand_admin', 'manage_options' );

		$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',
			'updated'
		);

		// ==========================================
		// RSS Defaults (Merged)
		// ==========================================
		$this->options->set( 'wisewand_rss_default_auto_import', isset( $_POST['rss_default_auto_import'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['rss_default_auto_import'] ) ) : false );
		$this->options->set( 'wisewand_rss_default_import_frequency', isset( $_POST['rss_default_import_frequency'] ) ? sanitize_text_field( wp_unslash( $_POST['rss_default_import_frequency'] ) ) : 'every_6_hours' );
		$this->options->set( 'wisewand_rss_default_max_articles', isset( $_POST['rss_default_max_articles'] ) ? absint( $_POST['rss_default_max_articles'] ) : 5 );
		$this->options->set( 'wisewand_rss_default_publish_mode', isset( $_POST['rss_default_publish_mode'] ) ? sanitize_key( wp_unslash( $_POST['rss_default_publish_mode'] ) ) : 'draft' );
		$this->options->set( 'wisewand_rss_default_target_author', isset( $_POST['rss_default_target_author'] ) ? absint( $_POST['rss_default_target_author'] ) : 0 );
		$this->options->set( 'wisewand_rss_default_ai_category_matching', isset( $_POST['rss_default_ai_category_matching'] ) ? rest_sanitize_boolean( wp_unslash( $_POST['rss_default_ai_category_matching'] ) ) : false );
		$this->options->set( 'wisewand_rss_default_import_time', isset( $_POST['rss_default_import_time'] ) ? sanitize_text_field( wp_unslash( $_POST['rss_default_import_time'] ) ) : '09:00' );
	}

	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_all_persona_settings() {
		return $this->settings_page->get_all_persona_settings();
	}

	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() {
		return $this->settings_page->get_detected_seo_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() {
		$this->settings_page->unified_settings_page();
	}



	private function render_unified_settings_content() {
		$this->settings_page->render_unified_settings_content();
	}

	private function handle_unified_settings_form() {
		$this->settings_page->handle_unified_settings_form();
	}
	/**
	 * Propagate global RSS settings to feeds with inheritance enabled
	 *
	 * @since 2.1.5
	 */
	private function propagate_global_rss_settings() {
		$this->settings_page->propagate_global_rss_settings();
	}

	public function ajax_debug_projects() {
		$this->verify_ajax_request( 'wisewand_debug', 'manage_options' );

		$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() {
		return $this->settings_page->get_plugin_status();
	}

	// 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 ) {
		return $this->settings_page->mask_api_key( $key );
	}

	/**
	 * 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;
	}
}