<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_Admin {

	public function __construct() {
		$this->register_hooks();
	}

	private function register_hooks() {
		add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_init', array( $this, 'handle_settings_post' ) );
		add_action( 'admin_init', array( $this, 'handle_lockdown_action' ) );
		add_action( 'admin_init', array( $this, 'handle_export_action' ) );
		add_action( 'admin_init', array( $this, 'handle_branding_save' ) );

		$ajax_actions = array(
			'zacls_save_settings',
			'zacls_unblock_ip',
			'zacls_block_ip',
			'zacls_whitelist_ip',
			'zacls_clear_logs',
			'zacls_dismiss_onboarding',
			'zacls_activate_lockdown',
			'zacls_deactivate_lockdown',
			'zacls_fetch_cloudflare_ips',
			'zacls_clear_audit_logs',
			'zacls_save_wizard_step',
			'zacls_terminate_session',
			'zacls_apply_recommended',
			'zacls_get_analytics',
			'zacls_run_file_scan',
			'zacls_run_vuln_scan',
		);

		foreach ( $ajax_actions as $action ) {
			add_action( "wp_ajax_{$action}", array( $this, str_replace( 'zacls_', 'ajax_', $action ) ) );
		}
	}

	public function add_admin_menu() {
		add_menu_page(
			esc_html__( 'ZA Creative Login Shield', 'za-creative-login-shield' ),
			esc_html__( 'Login Shield', 'za-creative-login-shield' ),
			'manage_options',
			'zacls',
			array( $this, 'render_admin_page' ),
			'dashicons-shield-alt',
			80
		);

		$sections = array(
			'dashboard' => array(
				'title' => esc_html__( 'Dashboard', 'za-creative-login-shield' ),
				'icon'  => 'dashicons-dashboard',
				'tab'   => 'dashboard',
			),
		);

		foreach ( $sections as $key => $s ) {
			add_submenu_page(
				'zacls',
				$s['title'],
				$s['title'],
				'manage_options',
				'zacls' . ( $s['tab'] !== 'dashboard' ? '&tab=' . $s['tab'] : '' ),
				$s['tab'] === 'dashboard' ? array( $this, 'render_admin_page' ) : '__return_null'
			);
		}
	}

	private function get_sections() {
		$onboarding_completed = 'yes' === get_option( 'zacls_onboarding_completed', 'no' );

		$sections = array(
			'dashboard' => array(
				'label' => esc_html__( 'Dashboard', 'za-creative-login-shield' ),
				'icon'  => 'dashicons-dashboard',
				'items' => array(
					'dashboard' => array( 'label' => esc_html__( 'Overview', 'za-creative-login-shield' ), 'icon' => 'dashicons-dashboard' ),
				),
			),
			'protection' => array(
				'label' => esc_html__( 'Protection', 'za-creative-login-shield' ),
				'icon'  => 'dashicons-shield',
				'items' => array(
					'lockdown'      => array( 'label' => esc_html__( 'Lockdown', 'za-creative-login-shield' ), 'icon' => 'dashicons-lock' ),
					'blocked-ips'   => array( 'label' => esc_html__( 'Blocked IPs', 'za-creative-login-shield' ), 'icon' => 'dashicons-block-default' ),
					'whitelist'     => array( 'label' => esc_html__( 'Whitelist', 'za-creative-login-shield' ), 'icon' => 'dashicons-yes-alt' ),
					'risk-scoring'  => array( 'label' => esc_html__( 'Risk Scoring', 'za-creative-login-shield' ), 'icon' => 'dashicons-warning' ),
				),
			),
			'authentication' => array(
				'label' => esc_html__( 'Authentication', 'za-creative-login-shield' ),
				'icon'  => 'dashicons-lock',
				'items' => array(
					'2fa-status'  => array( 'label' => esc_html__( 'Two-Factor Auth', 'za-creative-login-shield' ), 'icon' => 'dashicons-shield' ),
					'webauthn'    => array( 'label' => esc_html__( 'Passkeys', 'za-creative-login-shield' ), 'icon' => 'dashicons-smartphone' ),
					'sessions'    => array( 'label' => esc_html__( 'Sessions', 'za-creative-login-shield' ), 'icon' => 'dashicons-groups' ),
				),
			),
			'monitoring' => array(
				'label' => esc_html__( 'Monitoring', 'za-creative-login-shield' ),
				'icon'  => 'dashicons-search',
				'items' => array(
					'logs'          => array( 'label' => esc_html__( 'Login Logs', 'za-creative-login-shield' ), 'icon' => 'dashicons-list-view' ),
					'file-monitor'  => array( 'label' => esc_html__( 'File Monitor', 'za-creative-login-shield' ), 'icon' => 'dashicons-media-document' ),
					'vulnerability' => array( 'label' => esc_html__( 'Vulnerabilities', 'za-creative-login-shield' ), 'icon' => 'dashicons-warning' ),
					'notifications' => array( 'label' => esc_html__( 'Notifications', 'za-creative-login-shield' ), 'icon' => 'dashicons-bell' ),
				),
			),
			'reports' => array(
				'label' => esc_html__( 'Reports', 'za-creative-login-shield' ),
				'icon'  => 'dashicons-chart-line',
				'items' => array(
					'health'        => array( 'label' => esc_html__( 'Health', 'za-creative-login-shield' ), 'icon' => 'dashicons-heart' ),
					'analytics'     => array( 'label' => esc_html__( 'Analytics', 'za-creative-login-shield' ), 'icon' => 'dashicons-chart-bar' ),
					'audit-trail'   => array( 'label' => esc_html__( 'Audit Trail', 'za-creative-login-shield' ), 'icon' => 'dashicons-list-view' ),
					'performance'   => array( 'label' => esc_html__( 'Performance', 'za-creative-login-shield' ), 'icon' => 'dashicons-dashboard' ),
				),
			),
			'tools' => array(
				'label' => esc_html__( 'Tools', 'za-creative-login-shield' ),
				'icon'  => 'dashicons-admin-tools',
				'items' => array(
					'ai-assistant'  => array( 'label' => esc_html__( 'AI Assistant', 'za-creative-login-shield' ), 'icon' => 'dashicons-lightbulb' ),
					'branding'      => array( 'label' => esc_html__( 'Branding', 'za-creative-login-shield' ), 'icon' => 'dashicons-art' ),
				),
			),
			'settings' => array(
				'label' => esc_html__( 'Settings', 'za-creative-login-shield' ),
				'icon'  => 'dashicons-admin-settings',
				'items' => array(
					'settings' => array( 'label' => esc_html__( 'General', 'za-creative-login-shield' ), 'icon' => 'dashicons-admin-generic' ),
				),
			),
		);

		if ( ! $onboarding_completed ) {
			$sections['tools']['items'] = array_merge(
				array( 'wizard' => array( 'label' => esc_html__( 'Setup Wizard', 'za-creative-login-shield' ), 'icon' => 'dashicons-yes-alt' ) ),
				$sections['tools']['items']
			);
		}

		return $sections;
	}

	public function render_admin_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'za-creative-login-shield' ) );
		}

		$onboarding_completed = 'yes' === get_option( 'zacls_onboarding_completed', 'no' );
		$is_onboarding = isset( $_GET['onboarding'] ) && ! $onboarding_completed;

		$sections = $this->get_sections();
		$all_tabs = array();
		foreach ( $sections as $section ) {
			foreach ( $section['items'] as $tab => $item ) {
				$all_tabs[ $tab ] = $item;
			}
		}

		$current_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'dashboard';
		if ( $is_onboarding ) {
			$current_tab = 'wizard';
		}
		if ( ! isset( $all_tabs[ $current_tab ] ) ) {
			$current_tab = 'dashboard';
		}

		$health = ZACLS_Health::calculate_score();
		$notif_count = ZACLS_Notifications::count_unread();
		$health_class = $health['score'] >= 80 ? 'success' : ( $health['score'] >= 50 ? 'warning' : 'danger' );
		?>
		<div class="zacls-wrap">
			<aside class="zacls-sidebar">
				<div class="zacls-brand">
					<div class="zacls-brand-icon">
						<span class="dashicons dashicons-shield-alt"></span>
					</div>
					<div class="zacls-brand-text">
						<span class="zacls-brand-name"><?php esc_html_e( 'Login Shield', 'za-creative-login-shield' ); ?></span>
						<span class="zacls-brand-version">v<?php echo esc_html( ZACLS_VERSION ); ?></span>
					</div>
				</div>

				<div class="zacls-sidebar-mini-score">
					<div class="zacls-mini-score-ring" data-score="<?php echo esc_attr( $health['score'] ); ?>">
						<svg width="48" height="48" viewBox="0 0 48 48">
							<circle cx="24" cy="24" r="20" fill="none" stroke="var(--zacls-border-light)" stroke-width="3"/>
							<circle cx="24" cy="24" r="20" fill="none" stroke="var(--zacls-<?php echo esc_attr( $health_class ); ?>)" stroke-width="3"
								stroke-dasharray="125.6" stroke-dashoffset="<?php echo esc_attr( 125.6 - ( $health['score'] / 100 ) * 125.6 ); ?>"
								stroke-linecap="round" transform="rotate(-90 24 24)"/>
						</svg>
						<span class="zacls-mini-score-value"><?php echo esc_html( $health['score'] ); ?>%</span>
					</div>
					<div class="zacls-mini-score-label"><?php esc_html_e( 'Security Score', 'za-creative-login-shield' ); ?></div>
				</div>

				<nav class="zacls-nav">
					<?php foreach ( $sections as $section_key => $section ) : ?>
						<div class="zacls-nav-section">
							<div class="zacls-nav-section-title">
								<span class="dashicons dashicons-<?php echo esc_attr( $section['icon'] ); ?>"></span>
								<?php echo esc_html( $section['label'] ); ?>
							</div>
							<ul class="zacls-nav-items">
								<?php foreach ( $section['items'] as $tab => $item ) : ?>
									<?php
									$is_active = $current_tab === $tab;
									$url = admin_url( 'admin.php?page=zacls' . ( $tab !== 'dashboard' ? '&tab=' . $tab : '' ) );
									?>
									<li class="zacls-nav-item <?php echo $is_active ? 'active' : ''; ?>">
										<a href="<?php echo esc_url( $url ); ?>">
											<span class="dashicons dashicons-<?php echo esc_attr( $item['icon'] ); ?>"></span>
											<span class="zacls-nav-label"><?php echo esc_html( $item['label'] ); ?></span>
											<?php if ( 'notifications' === $tab && $notif_count > 0 ) : ?>
												<span class="zacls-nav-badge"><?php echo esc_html( $notif_count ); ?></span>
											<?php endif; ?>
										</a>
									</li>
								<?php endforeach; ?>
							</ul>
						</div>
					<?php endforeach; ?>
				</nav>

				<div class="zacls-sidebar-footer">
					<a href="https://opencode.ai" target="_blank" rel="noopener noreferrer">
						<span class="dashicons dashicons-external"></span>
						<?php esc_html_e( 'Support', 'za-creative-login-shield' ); ?>
					</a>
				</div>
			</aside>

			<div class="zacls-main">
				<?php if ( $is_onboarding ) : ?>
					<?php $this->render_onboarding_flow(); ?>
				<?php else : ?>
					<div class="zacls-page-body">
					<?php
					switch ( $current_tab ) {
						case 'health': include ZACLS_PLUGIN_DIR . 'admin/views/health.php'; break;
						case 'analytics': include ZACLS_PLUGIN_DIR . 'admin/views/analytics.php'; break;
						case 'wizard': include ZACLS_PLUGIN_DIR . 'admin/views/wizard.php'; break;
						case 'settings': include ZACLS_PLUGIN_DIR . 'admin/views/settings.php'; break;
						case 'logs': include ZACLS_PLUGIN_DIR . 'admin/views/login-logs.php'; break;
						case 'blocked-ips': include ZACLS_PLUGIN_DIR . 'admin/views/blocked-ips.php'; break;
						case '2fa-status': include ZACLS_PLUGIN_DIR . 'admin/views/2fa-status.php'; break;
						case 'webauthn': include ZACLS_PLUGIN_DIR . 'admin/views/webauthn.php'; break;
						case 'sessions': include ZACLS_PLUGIN_DIR . 'admin/views/sessions.php'; break;
						case 'risk-scoring': include ZACLS_PLUGIN_DIR . 'admin/views/risk-scoring.php'; break;
						case 'file-monitor': include ZACLS_PLUGIN_DIR . 'admin/views/file-monitor.php'; break;
						case 'vulnerability': include ZACLS_PLUGIN_DIR . 'admin/views/vulnerability.php'; break;
						case 'lockdown': include ZACLS_PLUGIN_DIR . 'admin/views/lockdown.php'; break;
						case 'branding': include ZACLS_PLUGIN_DIR . 'admin/views/branding.php'; break;
						case 'whitelist': include ZACLS_PLUGIN_DIR . 'admin/views/whitelist.php'; break;
						case 'audit-trail': include ZACLS_PLUGIN_DIR . 'admin/views/audit-trail.php'; break;
						case 'notifications': include ZACLS_PLUGIN_DIR . 'admin/views/notifications.php'; break;
						case 'ai-assistant': include ZACLS_PLUGIN_DIR . 'admin/views/ai-assistant.php'; break;
						case 'performance': include ZACLS_PLUGIN_DIR . 'admin/views/performance.php'; break;
						default: include ZACLS_PLUGIN_DIR . 'admin/views/dashboard.php'; break;
					}
					?>
					</div>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	private function render_onboarding_flow() {
		$steps = array(
			array( 'key' => 'welcome', 'title' => esc_html__( 'Welcome', 'za-creative-login-shield' ), 'icon' => 'dashicons-shield-alt' ),
			array( 'key' => '2fa', 'title' => esc_html__( '2FA', 'za-creative-login-shield' ), 'icon' => 'dashicons-lock' ),
			array( 'key' => 'limits', 'title' => esc_html__( 'Rate Limits', 'za-creative-login-shield' ), 'icon' => 'dashicons-chart-area' ),
			array( 'key' => 'password', 'title' => esc_html__( 'Password Policy', 'za-creative-login-shield' ), 'icon' => 'dashicons-admin-network' ),
			array( 'key' => 'done', 'title' => esc_html__( 'Done', 'za-creative-login-shield' ), 'icon' => 'dashicons-yes-alt' ),
		);
		?>
		<div class="zacls-onboarding-overlay">
			<div class="zacls-onboarding-modal">
				<div class="zacls-onboarding-progress">
					<?php foreach ( $steps as $i => $step ) : ?>
						<div class="zacls-onboarding-step-indicator" data-step="<?php echo esc_attr( $i ); ?>">
							<div class="zacls-onboarding-step-circle">
								<span class="dashicons dashicons-<?php echo esc_attr( $step['icon'] ); ?>"></span>
							</div>
							<span class="zacls-onboarding-step-title"><?php echo esc_html( $step['title'] ); ?></span>
						</div>
					<?php endforeach; ?>
				</div>
				<div class="zacls-onboarding-content">
					<div class="zacls-onboarding-panel active" data-panel="0">
						<h2><?php esc_html_e( 'Welcome to Login Shield', 'za-creative-login-shield' ); ?></h2>
						<p class="zacls-onboarding-desc"><?php esc_html_e( 'Set up your security in under 2 minutes. We recommend enabling all protections.', 'za-creative-login-shield' ); ?></p>
						<button type="button" class="zacls-btn zacls-btn-primary zacls-onboarding-next">
							<?php esc_html_e( 'Get Started', 'za-creative-login-shield' ); ?>
							<span class="dashicons dashicons-arrow-right-alt2"></span>
						</button>
					</div>
					<div class="zacls-onboarding-panel" data-panel="1">
						<h2><?php esc_html_e( 'Two-Factor Authentication', 'za-creative-login-shield' ); ?></h2>
						<p class="zacls-onboarding-desc"><?php esc_html_e( 'Add an extra layer of security to user accounts.', 'za-creative-login-shield' ); ?></p>
						<label class="zacls-toggle-label">
							<input type="checkbox" class="zacls-toggle-input" id="ob-2fa" checked>
							<span class="zacls-toggle-track"></span>
							<span><?php esc_html_e( 'Enable 2FA for all administrators', 'za-creative-login-shield' ); ?></span>
						</label>
						<div class="zacls-onboarding-actions">
							<button type="button" class="zacls-btn zacls-btn-secondary zacls-onboarding-prev"><?php esc_html_e( 'Back', 'za-creative-login-shield' ); ?></button>
							<button type="button" class="zacls-btn zacls-btn-primary zacls-onboarding-next"><?php esc_html_e( 'Next', 'za-creative-login-shield' ); ?></button>
						</div>
					</div>
					<div class="zacls-onboarding-panel" data-panel="2">
						<h2><?php esc_html_e( 'Rate Limiting', 'za-creative-login-shield' ); ?></h2>
						<p class="zacls-onboarding-desc"><?php esc_html_e( 'Block brute-force attacks by limiting login attempts.', 'za-creative-login-shield' ); ?></p>
						<label class="zacls-toggle-label">
							<input type="checkbox" class="zacls-toggle-input" id="ob-limits" checked>
							<span class="zacls-toggle-track"></span>
							<span><?php esc_html_e( 'Enable login rate limiting (5 attempts per 15 min)', 'za-creative-login-shield' ); ?></span>
						</label>
						<div class="zacls-onboarding-actions">
							<button type="button" class="zacls-btn zacls-btn-secondary zacls-onboarding-prev"><?php esc_html_e( 'Back', 'za-creative-login-shield' ); ?></button>
							<button type="button" class="zacls-btn zacls-btn-primary zacls-onboarding-next"><?php esc_html_e( 'Next', 'za-creative-login-shield' ); ?></button>
						</div>
					</div>
					<div class="zacls-onboarding-panel" data-panel="3">
						<h2><?php esc_html_e( 'Password Policy', 'za-creative-login-shield' ); ?></h2>
						<p class="zacls-onboarding-desc"><?php esc_html_e( 'Enforce strong passwords across your site.', 'za-creative-login-shield' ); ?></p>
						<label class="zacls-toggle-label">
							<input type="checkbox" class="zacls-toggle-input" id="ob-password" checked>
							<span class="zacls-toggle-track"></span>
							<span><?php esc_html_e( 'Enforce strong password policy (12+ chars, symbols)', 'za-creative-login-shield' ); ?></span>
						</label>
						<div class="zacls-onboarding-actions">
							<button type="button" class="zacls-btn zacls-btn-secondary zacls-onboarding-prev"><?php esc_html_e( 'Back', 'za-creative-login-shield' ); ?></button>
							<button type="button" class="zacls-btn zacls-btn-primary zacls-onboarding-next"><?php esc_html_e( 'Next', 'za-creative-login-shield' ); ?></button>
						</div>
					</div>
					<div class="zacls-onboarding-panel" data-panel="4">
						<h2><?php esc_html_e( 'You\'re All Set!', 'za-creative-login-shield' ); ?></h2>
						<p class="zacls-onboarding-desc"><?php esc_html_e( 'Your recommended security settings have been applied. You can change any setting later.', 'za-creative-login-shield' ); ?></p>
						<button type="button" class="zacls-btn zacls-btn-primary zacls-onboarding-finish">
							<span class="dashicons dashicons-yes-alt"></span>
							<?php esc_html_e( 'Go to Dashboard', 'za-creative-login-shield' ); ?>
						</button>
						<p class="zacls-onboarding-skip">
							<button type="button" class="zacls-btn zacls-btn-link zacls-onboarding-dismiss"><?php esc_html_e( 'Skip setup, I\'ll do this later', 'za-creative-login-shield' ); ?></button>
						</p>
					</div>
				</div>
			</div>
		</div>
		<script>
		jQuery(function($) {
			var currentPanel = 0;
			var totalPanels = 5;

			function showPanel(index) {
				$('.zacls-onboarding-panel').removeClass('active');
				$('.zacls-onboarding-panel[data-panel="' + index + '"]').addClass('active');
				$('.zacls-onboarding-step-indicator').removeClass('active completed');
				$('.zacls-onboarding-step-indicator').each(function(i) {
					if (i < index) $(this).addClass('completed');
					else if (i === index) $(this).addClass('active');
				});
				currentPanel = index;
			}

			function applySettings(callback) {
				var settings = {
					zacls_2fa_enabled: $('#ob-2fa').is(':checked') ? 'yes' : 'no',
					zacls_2fa_forced_roles: $('#ob-2fa').is(':checked') ? ['administrator'] : [],
					zacls_login_limits: $('#ob-limits').is(':checked') ? { max_attempts: 5, time_window: 15, lockout_time: 15 } : { max_attempts: 0, time_window: 15, lockout_time: 15 },
					zacls_password_policy: $('#ob-password').is(':checked') ? { min_length: 12, require_upper: 'yes', require_lower: 'yes', require_number: 'yes', require_special: 'yes', history_count: 5, block_common: 'yes' } : { min_length: 0, require_upper: 'no', require_lower: 'no', require_number: 'no', require_special: 'no' },
					zacls_onboarding_completed: 'yes',
					zacls_geoip_enabled: 'yes',
					zacls_device_tracking: 'yes',
					zacls_report_frequency: 'weekly',
				};
				$.post(zaclsData.ajaxUrl, { action: 'zacls_save_settings', nonce: zaclsData.nonce, settings: settings }, function(r) {
					if (callback) callback(r.success);
				}, 'json');
			}

			$('.zacls-onboarding-next').on('click', function() {
				if (currentPanel < totalPanels - 1) showPanel(currentPanel + 1);
			});

			$('.zacls-onboarding-prev').on('click', function() {
				if (currentPanel > 0) showPanel(currentPanel - 1);
			});

			$('.zacls-onboarding-finish').on('click', function() {
				applySettings(function() {
					window.location.href = 'admin.php?page=zacls';
				});
			});

			$('.zacls-onboarding-dismiss').on('click', function() {
				$.post(zaclsData.ajaxUrl, { action: 'zacls_dismiss_onboarding', nonce: zaclsData.nonce }, function() {
					window.location.href = 'admin.php?page=zacls';
				});
			});

			showPanel(0);
		});
		</script>
		<?php
	}

	public function enqueue_assets( $hook ) {
		if ( false === strpos( $hook, 'zacls' ) && false === strpos( $hook, 'toplevel_page_zacls' ) ) {
			return;
		}

		wp_enqueue_style( 'zacls-admin', ZACLS_PLUGIN_URL . 'assets/css/admin.css', array(), ZACLS_VERSION );
		wp_enqueue_script( 'zacls-admin', ZACLS_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery' ), ZACLS_VERSION, true );

		wp_localize_script( 'zacls-admin', 'zaclsData', array(
			'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
			'nonce'       => wp_create_nonce( 'zacls_admin_nonce' ),
			'redirectUrl' => admin_url( 'admin.php?page=zacls' ),
			'i18n'        => array(
				'confirmUnblock'  => esc_html__( 'Are you sure you want to unblock this IP?', 'za-creative-login-shield' ),
				'confirmBlock'    => esc_html__( 'Are you sure you want to block this IP?', 'za-creative-login-shield' ),
				'confirmClear'    => esc_html__( 'Are you sure you want to clear all login logs?', 'za-creative-login-shield' ),
				'confirmLockdown' => esc_html__( 'Are you sure you want to activate emergency lockdown? This will block ALL login attempts except whitelisted IPs.', 'za-creative-login-shield' ),
				'saved'           => esc_html__( 'Settings saved successfully!', 'za-creative-login-shield' ),
				'error'           => esc_html__( 'An error occurred. Please try again.', 'za-creative-login-shield' ),
				'confirmTerminate'=> esc_html__( 'Terminate this session? The user will be logged out.', 'za-creative-login-shield' ),
			),
		) );
	}

	public function handle_settings_post() {
		if ( ! isset( $_POST['zacls_save_settings'] ) ) return;
		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'zacls_admin_nonce' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'za-creative-login-shield' ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'za-creative-login-shield' ) );
		}

		$settings_raw = isset( $_POST['settings'] ) ? wp_unslash( $_POST['settings'] ) : array();
		$settings     = is_string( $settings_raw ) ? json_decode( $settings_raw, true ) : (array) $settings_raw;

		$this->apply_settings( $settings );
		wp_safe_redirect( add_query_arg( 'settings-updated', '1', wp_get_referer() ) );
		exit;
	}

	public function handle_lockdown_action() {
		$action = isset( $_GET['zacls_action'] ) ? sanitize_text_field( wp_unslash( $_GET['zacls_action'] ) ) : '';
		if ( 'deactivate_lockdown' !== $action ) return;
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'zacls_lockdown_action' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'za-creative-login-shield' ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'za-creative-login-shield' ) );
		}

		ZACLS_Emergency::deactivate();
		wp_safe_redirect( remove_query_arg( array( 'zacls_action', '_wpnonce' ) ) );
		exit;
	}

	public function handle_export_action() {
		if ( ! isset( $_GET['zacls_export'] ) || ! isset( $_GET['_wpnonce'] ) ) return;
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'zacls_export_nonce' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'za-creative-login-shield' ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'za-creative-login-shield' ) );
		}

		$export_type = sanitize_text_field( wp_unslash( $_GET['zacls_export'] ) );
		$format      = isset( $_GET['format'] ) ? sanitize_text_field( wp_unslash( $_GET['format'] ) ) : 'csv';

		if ( 'login_attempts' === $export_type ) {
			ZACLS_Export::export_login_attempts( array(
				'days'   => isset( $_GET['days'] ) ? absint( $_GET['days'] ) : 30,
				'format' => $format,
			) );
		} elseif ( 'blocked_ips' === $export_type ) {
			ZACLS_Export::export_blocked_ips( $format );
		} elseif ( 'report' === $export_type ) {
			$days = isset( $_GET['days'] ) ? absint( $_GET['days'] ) : 30;
			ZACLS_Export::export_report( $days, $format );
		}
	}

	public function handle_branding_save() {
		if ( ! isset( $_POST['zacls_save_branding'] ) ) return;
		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'zacls_admin_nonce' ) ) return;
		if ( ! current_user_can( 'manage_options' ) ) return;

		$fields = array( 'zacls_login_logo_image', 'zacls_login_logo_url', 'zacls_login_logo_title', 'zacls_login_bg_color', 'zacls_login_form_bg', 'zacls_login_text_color', 'zacls_login_primary_color', 'zacls_login_header_html', 'zacls_login_footer_html', 'zacls_login_custom_css' );

		foreach ( $fields as $field ) {
			if ( isset( $_POST[ $field ] ) ) {
				$value = wp_unslash( $_POST[ $field ] );
				if ( in_array( $field, array( 'zacls_login_header_html', 'zacls_login_footer_html' ), true ) ) {
					update_option( $field, wp_kses_post( $value ) );
				} elseif ( 'zacls_login_custom_css' === $field ) {
					update_option( $field, ZACLS_Branding::sanitize_css( $value ) );
				} elseif ( strpos( $field, 'color' ) !== false ) {
					update_option( $field, sanitize_hex_color( $value ) );
				} elseif ( strpos( $field, 'url' ) !== false ) {
					update_option( $field, esc_url_raw( $value ) );
				} else {
					update_option( $field, sanitize_text_field( $value ) );
				}
			}
		}

		ZACLS_Audit_Trail::log( 'branding_saved', esc_html__( 'Login branding settings updated', 'za-creative-login-shield' ) );
		wp_safe_redirect( add_query_arg( 'settings-updated', '1', wp_get_referer() ) );
		exit;
	}

	private function apply_settings( $settings ) {
		if ( ! is_array( $settings ) ) return;

		$map = array(
			'zacls_2fa_enabled'           => 'sanitize_text_field',
			'zacls_2fa_forced_roles'      => 'array_map_sanitize',
			'zacls_webauthn_enabled'      => 'sanitize_text_field',
			'zacls_webauthn_bypasses_2fa' => 'sanitize_text_field',
			'zacls_custom_login_slug'     => 'sanitize_title',
			'zacls_block_wp_login'        => 'sanitize_text_field',
			'zacls_redirect_unauthorized' => 'sanitize_text_field',
			'zacls_admin_email'           => 'sanitize_email',
			'zacls_onboarding_completed'  => 'sanitize_text_field',
			'zacls_session_timeout'       => 'absint',
			'zacls_session_inactive_limit'=> 'absint',
			'zacls_device_tracking'       => 'sanitize_text_field',
			'zacls_cloudflare_enabled'    => 'sanitize_text_field',
			'zacls_geoip_enabled'         => 'sanitize_text_field',
			'zacls_tor_detection'         => 'sanitize_text_field',
			'zacls_report_frequency'      => 'sanitize_text_field',
			'zacls_auto_block_threshold'  => 'absint',
			'zacls_auto_block_duration'   => 'absint',
			'zacls_delete_data_on_uninstall'=> 'sanitize_text_field',
			'zacls_cleanup_frequency'     => 'sanitize_text_field',
			'zacls_cleanup_retention_days'=> 'absint',
		);

		foreach ( $map as $key => $sanitizer ) {
			if ( ! isset( $settings[ $key ] ) ) {
				continue;
			}

			$value = ZACLS_Settings::sanitize( $key, $settings[ $key ] );

			if ( 'array_map_sanitize' === $sanitizer ) {
				update_option( $key, array_map( 'sanitize_text_field', (array) $value ) );
			} else {
				update_option( $key, $value );
			}
		}

		if ( isset( $settings['zacls_trusted_proxy_ips'] ) ) {
			update_option( 'zacls_trusted_proxy_ips', ZACLS_Settings::sanitize_trusted_proxies( $settings['zacls_trusted_proxy_ips'] ) );
		}

		if ( isset( $settings['zacls_login_limits'] ) ) {
			update_option( 'zacls_login_limits', ZACLS_Settings::sanitize_login_limits( $settings['zacls_login_limits'] ) );
		}

		if ( isset( $settings['zacls_password_policy'] ) ) {
			update_option( 'zacls_password_policy', ZACLS_Settings::sanitize_password_policy( $settings['zacls_password_policy'] ) );
		}

		if ( isset( $settings['zacls_email_notifications'] ) ) {
			update_option( 'zacls_email_notifications', ZACLS_Settings::sanitize_email_notifications( $settings['zacls_email_notifications'] ) );
		}

		if ( isset( $settings['zacls_custom_login_slug'] ) ) {
			update_option( 'zacls_flush_rewrite', 'yes' );
		}

		if ( isset( $settings['zacls_report_frequency'] ) ) {
			self::schedule_report_cron( ZACLS_Settings::sanitize( 'zacls_report_frequency', $settings['zacls_report_frequency'] ) );
		}
	}

	private static function schedule_report_cron( $frequency ) {
		$hooks = array( 'zacls_daily_report', 'zacls_weekly_report', 'zacls_monthly_report' );
		foreach ( $hooks as $hook ) {
			$timestamp = wp_next_scheduled( $hook );
			if ( $timestamp ) wp_unschedule_event( $timestamp, $hook );
		}

		if ( 'none' === $frequency ) return;

		$map = array(
			'daily'   => array( 'hook' => 'zacls_daily_report', 'schedule' => 'daily' ),
			'weekly'  => array( 'hook' => 'zacls_weekly_report', 'schedule' => 'weekly' ),
			'monthly' => array( 'hook' => 'zacls_monthly_report', 'schedule' => 'monthly' ),
		);

		if ( isset( $map[ $frequency ] ) ) {
			$hook = $map[ $frequency ]['hook'];
			if ( ! wp_next_scheduled( $hook ) ) {
				wp_schedule_event( time(), $map[ $frequency ]['schedule'], $hook );
			}
		}
	}

	public function ajax_save_settings() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );
		}

		$settings_raw = isset( $_POST['settings'] ) ? wp_unslash( $_POST['settings'] ) : array();
		$settings     = is_string( $settings_raw ) ? json_decode( $settings_raw, true ) : (array) $settings_raw;

		$this->apply_settings( $settings );
		ZACLS_Audit_Trail::log( 'settings_saved', esc_html__( 'Security settings updated', 'za-creative-login-shield' ) );
		wp_send_json_success( array( 'message' => esc_html__( 'Settings saved successfully!', 'za-creative-login-shield' ) ) );
	}

	public function ajax_unblock_ip() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		$ip = isset( $_POST['ip'] ) ? sanitize_text_field( wp_unslash( $_POST['ip'] ) ) : '';
		if ( empty( $ip ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) wp_send_json_error( array( 'message' => esc_html__( 'Invalid IP address.', 'za-creative-login-shield' ) ) );

		ZACLS_IP_Blocker::unblock_ip( $ip );
		wp_send_json_success( array( 'message' => esc_html__( 'IP unblocked successfully.', 'za-creative-login-shield' ) ) );
	}

	public function ajax_block_ip() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		$ip     = isset( $_POST['ip'] ) ? sanitize_text_field( wp_unslash( $_POST['ip'] ) ) : '';
		$reason = isset( $_POST['reason'] ) ? sanitize_text_field( wp_unslash( $_POST['reason'] ) ) : '';
		if ( empty( $ip ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) wp_send_json_error( array( 'message' => esc_html__( 'Invalid IP address.', 'za-creative-login-shield' ) ) );

		ZACLS_IP_Blocker::manual_block_ip( $ip, $reason );
		wp_send_json_success( array( 'message' => esc_html__( 'IP blocked successfully.', 'za-creative-login-shield' ) ) );
	}

	public function ajax_whitelist_ip() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		$ip     = isset( $_POST['ip'] ) ? sanitize_text_field( wp_unslash( $_POST['ip'] ) ) : '';
		$reason = isset( $_POST['reason'] ) ? sanitize_text_field( wp_unslash( $_POST['reason'] ) ) : '';
		if ( empty( $ip ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) wp_send_json_error( array( 'message' => esc_html__( 'Invalid IP address.', 'za-creative-login-shield' ) ) );

		ZACLS_IP_Blocker::whitelist_ip( $ip, $reason );
		wp_send_json_success( array( 'message' => esc_html__( 'IP whitelisted successfully.', 'za-creative-login-shield' ) ) );
	}

	public function ajax_clear_logs() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		ZACLS_Login_Limiter::clear_logs();
		ZACLS_Audit_Trail::log( 'logs_cleared', esc_html__( 'All login attempt logs cleared', 'za-creative-login-shield' ) );
		wp_send_json_success( array( 'message' => esc_html__( 'Logs cleared successfully.', 'za-creative-login-shield' ) ) );
	}

	public function ajax_dismiss_onboarding() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
		update_option( 'zacls_onboarding_completed', 'yes' );
		wp_send_json_success();
	}

	public function ajax_activate_lockdown() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		$reason        = isset( $_POST['reason'] ) ? sanitize_text_field( wp_unslash( $_POST['reason'] ) ) : '';
		$whitelist_ips = isset( $_POST['whitelist_ips'] ) ? array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['whitelist_ips'] ) ) : array();

		ZACLS_Emergency::activate( get_current_user_id(), $reason, $whitelist_ips );
		ZACLS_Audit_Trail::log( 'lockdown_activated', $reason ? $reason : esc_html__( 'Emergency lockdown activated', 'za-creative-login-shield' ) );
		wp_send_json_success( array( 'message' => esc_html__( 'Emergency lockdown activated.', 'za-creative-login-shield' ) ) );
	}

	public function ajax_deactivate_lockdown() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		ZACLS_Emergency::deactivate();
		ZACLS_Audit_Trail::log( 'lockdown_deactivated', esc_html__( 'Emergency lockdown deactivated', 'za-creative-login-shield' ) );
		wp_send_json_success( array( 'message' => esc_html__( 'Emergency lockdown deactivated.', 'za-creative-login-shield' ) ) );
	}

	public function ajax_fetch_cloudflare_ips() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		$response = wp_remote_get( 'https://api.cloudflare.com/client/v4/ips', array( 'timeout' => 15, 'user-agent' => 'ZA Creative Login Shield/' . ZACLS_VERSION ) );
		if ( is_wp_error( $response ) ) wp_send_json_error( array( 'message' => esc_html__( 'Failed to fetch Cloudflare IP ranges.', 'za-creative-login-shield' ) ) );

		$code = wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) wp_send_json_error( array( 'message' => sprintf( esc_html__( 'Cloudflare API returned HTTP %d.', 'za-creative-login-shield' ), $code ) ) );

		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );
		if ( ! is_array( $data ) || empty( $data['success'] ) ) wp_send_json_error( array( 'message' => esc_html__( 'Invalid response from Cloudflare API.', 'za-creative-login-shield' ) ) );

		$merged = array_merge( $data['result']['ipv4_cidrs'], isset( $data['result']['ipv6_cidrs'] ) ? $data['result']['ipv6_cidrs'] : array() );
		update_option( 'zacls_trusted_proxy_ips', $merged );
		wp_send_json_success( array( 'message' => sprintf( esc_html__( 'Fetched %d Cloudflare IP ranges.', 'za-creative-login-shield' ), count( $merged ) ) ) );
	}

	public function ajax_clear_audit_logs() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		ZACLS_Audit_Trail::clear_logs();
		wp_send_json_success( array( 'message' => esc_html__( 'Audit logs cleared.', 'za-creative-login-shield' ) ) );
	}

	public function ajax_save_wizard_step() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		$step    = isset( $_POST['step'] ) ? sanitize_key( $_POST['step'] ) : '';
		$enabled = isset( $_POST['enabled'] ) && 'true' === sanitize_text_field( wp_unslash( $_POST['enabled'] ) );

		if ( 'custom_login' === $step ) {
			update_option( 'zacls_custom_login_slug', ZACLS_Settings::sanitize( 'zacls_custom_login_slug', $enabled ? 'be-login' : '' ) );
			if ( $enabled ) {
				update_option( 'zacls_flush_rewrite', 'yes' );
			}
		} elseif ( 'login_limits' === $step ) {
			update_option( 'zacls_login_limits', ZACLS_Settings::sanitize_login_limits( array( 'max_attempts' => $enabled ? 5 : 0, 'time_window' => 15, 'lockout_time' => 15 ) ) );
		} elseif ( 'password_policy' === $step ) {
			update_option( 'zacls_password_policy', ZACLS_Settings::sanitize_password_policy( array( 'min_length' => $enabled ? 8 : 0, 'require_upper' => $enabled ? 'yes' : 'no', 'require_lower' => $enabled ? 'yes' : 'no', 'require_number' => $enabled ? 'yes' : 'no', 'require_special' => $enabled ? 'yes' : 'no' ) ) );
		} elseif ( 'email_notifications' === $step ) {
			update_option( 'zacls_email_notifications', ZACLS_Settings::sanitize_email_notifications( array( 'failed_login' => $enabled ? 'yes' : 'no', 'new_ip_login' => $enabled ? 'yes' : 'no', 'ip_blocked' => $enabled ? 'yes' : 'no' ) ) );
		} elseif ( '2fa' === $step ) {
			update_option( 'zacls_2fa_enabled', ZACLS_Settings::sanitize( 'zacls_2fa_enabled', $enabled ? 'yes' : 'no' ) );
		}

		ZACLS_Audit_Trail::log( 'wizard_step_saved', sprintf( esc_html__( 'Wizard step "%1$s" set to %2$s', 'za-creative-login-shield' ), $step, $enabled ? 'enabled' : 'disabled' ) );
		wp_send_json_success();
	}

	public function ajax_terminate_session() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		$session_id = isset( $_POST['session_id'] ) ? sanitize_text_field( wp_unslash( $_POST['session_id'] ) ) : '';
		if ( empty( $session_id ) ) wp_send_json_error( array( 'message' => esc_html__( 'Invalid session.', 'za-creative-login-shield' ) ) );

		ZACLS_Session::terminate_session( $session_id );
		ZACLS_Audit_Trail::log( 'session_terminated', sprintf( esc_html__( 'Session %s terminated', 'za-creative-login-shield' ), substr( $session_id, 0, 12 ) ) );
		wp_send_json_success( array( 'message' => esc_html__( 'Session terminated.', 'za-creative-login-shield' ) ) );
	}

	public function ajax_apply_recommended() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		ZACLS_Health::apply_recommended_settings();
		wp_send_json_success( array( 'message' => esc_html__( 'Recommended settings applied successfully!', 'za-creative-login-shield' ) ) );
	}

	public function ajax_get_analytics() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		wp_send_json_success( array(
			'stats'     => ZACLS_Analytics::get_summary_stats( 1 ),
			'activity'  => ZACLS_Analytics::get_login_activity( 14 ),
			'attackers' => ZACLS_Analytics::get_top_attackers(),
			'countries' => ZACLS_Analytics::get_country_stats(),
		) );
	}

	public function ajax_run_file_scan() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		ZACLS_Background::add_to_queue( 'file_scan' );
		$result = ZACLS_File_Monitor::run_full_scan();
		ZACLS_Audit_Trail::log( 'file_scan', esc_html__( 'File integrity scan completed', 'za-creative-login-shield' ) );
		wp_send_json_success( array( 'message' => esc_html__( 'File scan completed successfully.', 'za-creative-login-shield' ), 'result' => $result ) );
	}

	public function ajax_run_vuln_scan() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'za-creative-login-shield' ) ) );

		$result = ZACLS_Vulnerability_Scanner::scan_plugins();
		wp_send_json_success( array( 'message' => sprintf( esc_html__( 'Scanned %d plugins. %d vulnerabilities found.', 'za-creative-login-shield' ), $result['checked'], $result['vuln_count'] ), 'result' => $result ) );
	}
}
