<?php
/**
 * Adaptive protection page handler for BotFend Anti-Bot Firewall
 *
 * @package BotFend\Admin\Pages
 */

namespace BotFend\Admin\Pages;

use BotFend\Core\Config;
use BotFend\Core\Core;

defined('ABSPATH') || exit;

class Adaptive {

    private $core;
    private $config;

    public function __construct(?Core $core = null) {
        $this->core = $core;
        $this->config = Config::get_instance();
        
        // Enqueue assets using WordPress standard hooks - same pattern as Dashboard, Logs, etc.
        add_action('admin_enqueue_scripts', [$this, 'enqueue_adaptive_assets']);
    }

    /**
     * Enqueue Adaptive page CSS and JavaScript
     *
     * @param string $hook Current admin page
     * @return void
     */
    public function enqueue_adaptive_assets(string $hook): void {
        // Only load on the Threat Dashboard page
        if (strpos($hook, 'botfend-adaptive') === false) {
            return;
        }

        // Enqueue CSS
        wp_enqueue_style(
            'botfend-adaptive-css',
            BOTFEND_ASSETS_URL . 'css/botfend-adaptive.css',
            [],
            BOTFEND_VERSION
        );
        
        // Enqueue JavaScript
        wp_enqueue_script(
            'botfend-adaptive-js',
            BOTFEND_ASSETS_URL . 'js/adaptive.js',
            ['jquery'],
            BOTFEND_VERSION,
            true
        );
        
        // Localize script if needed (for future AJAX functionality)
        wp_localize_script('botfend-adaptive-js', 'botfendAdaptive', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('botfend_adaptive_nonce'),
            'refreshText' => esc_html__('Refresh Data', 'botfend-anti-bot-firewall'),
            'refreshingText' => esc_html__('Refreshing...', 'botfend-anti-bot-firewall'),
        ]);
    }

    private function get_adaptive_data(): array {
        $data = [
            'mode' => 'balanced',
            'description' => $this->get_mode_description('balanced'),
            'block_score' => 8,
            'challenge_score' => 6,
            'rate_limit' => 100,
            'sampling_rate' => 30,
            'attack_level' => 0,
            'predictive_risk' => 0
        ];

        if ($this->core) {
            $components = $this->core->get_components();
            $adaptive = $components['adaptive'] ?? null;
            
            if ($adaptive && method_exists($adaptive, 'get_current_settings_enhanced')) {
                $engine_data = $adaptive->get_current_settings_enhanced();
                
                $data['mode'] = $engine_data['mode'];
                $data['description'] = $this->get_mode_description($engine_data['mode']);
                $data['block_score'] = $engine_data['block_score'] ?? 8;
                $data['challenge_score'] = $engine_data['challenge_score'] ?? 6;
                $data['rate_limit'] = $engine_data['rate_limit'] ?? 100;
                $data['sampling_rate'] = isset($engine_data['sampling_rate']) ? ($engine_data['sampling_rate'] * 100) : 30;
                $data['attack_level'] = $engine_data['attack_level'] ?? 0;
                $data['predictive_risk'] = $engine_data['predictive_risk'] ?? 0;
            }
        }

        return $data;
    }

    private function get_mode_description(string $mode): string {
        $descriptions = [
            'learning' => esc_html__('Learning mode - minimal protection while learning traffic patterns.', 'botfend-anti-bot-firewall'),
            'balanced' => esc_html__('Balanced mode - optimal protection for most websites.', 'botfend-anti-bot-firewall'),
            'aggressive' => esc_html__('Aggressive mode - higher protection, may increase false positives.', 'botfend-anti-bot-firewall'),
            'emergency' => esc_html__('Emergency mode - maximum protection during active attacks.', 'botfend-anti-bot-firewall')
        ];
        
        return $descriptions[$mode] ?? $descriptions['balanced'];
    }

    private function display_admin_notices(): void {
        if (isset($_GET['settings-updated']) && $_GET['settings-updated'] === 'true') {
            settings_errors('botfend_messages');
        }
    }

    public function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'botfend-anti-bot-firewall'));
        }
        
        $adaptive_data = $this->get_adaptive_data();
        $attack_level = $adaptive_data['attack_level'];
        $predictive_risk = $adaptive_data['predictive_risk'];
        
        $this->display_admin_notices();
        ?>
        <div class="wrap botfend-adaptive-wrap">
            <div class="botfend-adaptive-header">
                <div class="botfend-header-title-wrap">
                    <h1 class="botfend-page-title">
                        <?php echo esc_html__('Threat Dashboard', 'botfend-anti-bot-firewall'); ?>
                    </h1>
                    <span class="botfend-version-badge">v<?php echo esc_attr(BOTFEND_VERSION); ?></span>
                </div>
                <p class="botfend-header-description">
                    <?php echo esc_html__('Monitor your real-time threat intelligence.', 'botfend-anti-bot-firewall'); ?>
                </p>
            </div>

            <div class="botfend-adaptive-grid">
                <div class="botfend-adaptive-primary">
                    <div class="botfend-card">
                        <div class="botfend-card-header">
                            <span class="dashicons dashicons-shield-alt"></span>
                            <h2><?php echo esc_html__('Current Protection Status', 'botfend-anti-bot-firewall'); ?></h2>
                        </div>
                        
                        <div class="botfend-status-grid">
                            <div class="botfend-status-card">
                                <div class="botfend-status-icon mode-<?php echo esc_attr($adaptive_data['mode']); ?>">
                                    <span class="dashicons dashicons-shield"></span>
                                </div>
                                <div class="botfend-status-info">
                                    <span class="botfend-status-label"><?php echo esc_html__('Active Mode', 'botfend-anti-bot-firewall'); ?></span>
                                    <span class="botfend-status-value mode-<?php echo esc_attr($adaptive_data['mode']); ?>">
                                        <?php echo esc_html(ucfirst($adaptive_data['mode'])); ?>
                                    </span>
                                    <span class="botfend-status-desc"><?php echo esc_html($adaptive_data['description']); ?></span>
                                </div>
                            </div>

                            <div class="botfend-status-card">
                                <div class="botfend-status-icon">
                                    <span class="dashicons dashicons-warning"></span>
                                </div>
                                <div class="botfend-status-info" style="width: 100%;">
                                    <span class="botfend-status-label"><?php echo esc_html__('Current Attack Level', 'botfend-anti-bot-firewall'); ?></span>
                                    <div class="botfend-progress-wrapper">
                                        <div class="botfend-progress-bar" style="width: <?php echo esc_attr(min(100, max(0, $attack_level))); ?>%;
                                            background: <?php echo $attack_level >= 80 ? 'linear-gradient(90deg, #dc3232, #f0ad4e)' : ($attack_level >= 60 ? 'linear-gradient(90deg, #f0ad4e, #ffb900)' : 'linear-gradient(90deg, #46b450, #7cbd6e)'); ?>;">
                                        </div>
                                    </div>
                                    <div class="botfend-progress-meta" style="margin-bottom: 12px;">
                                        <span class="botfend-progress-value"><?php echo esc_html($attack_level); ?>%</span>
                                        <?php if ($attack_level >= 80): ?>
                                            <span class="botfend-badge danger"><?php esc_html_e('High Threat', 'botfend-anti-bot-firewall'); ?></span>
                                        <?php elseif ($attack_level >= 60): ?>
                                            <span class="botfend-badge warning"><?php esc_html_e('Medium Threat', 'botfend-anti-bot-firewall'); ?></span>
                                        <?php else: ?>
                                            <span class="botfend-badge success"><?php esc_html_e('Low Threat', 'botfend-anti-bot-firewall'); ?></span>
                                        <?php endif; ?>
                                    </div>

                                    <span class="botfend-status-label" style="margin-top: 10px; border-top: 1px solid #e2e4e7; padding-top: 10px;"><?php echo esc_html__('AI Predictive Risk (Trend)', 'botfend-anti-bot-firewall'); ?></span>
                                    <div class="botfend-progress-wrapper" style="height: 6px;">
                                        <div class="botfend-progress-bar" style="width: <?php echo esc_attr(min(100, max(0, $predictive_risk))); ?>%;
                                            background: <?php echo $predictive_risk >= 70 ? '#dc3232' : ($predictive_risk >= 40 ? '#ffb900' : '#46b450'); ?>;">
                                        </div>
                                    </div>
                                    <div class="botfend-progress-meta">
                                        <span class="botfend-progress-value" style="font-size: 12px;"><?php echo esc_html($predictive_risk); ?>%</span>
                                        <span style="font-size: 11px; color: #6c757d;"><?php esc_html_e('Based on 90-day history', 'botfend-anti-bot-firewall'); ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="botfend-settings-footer">
                            <div class="botfend-badge-item">
                                <span class="badge-label"><?php esc_html_e('Block Score', 'botfend-anti-bot-firewall'); ?></span>
                                <span class="badge-value"><?php echo esc_html($adaptive_data['block_score']); ?>/10</span>
                            </div>
                            <div class="botfend-badge-item">
                                <span class="badge-label"><?php esc_html_e('Challenge Score', 'botfend-anti-bot-firewall'); ?></span>
                                <span class="badge-value"><?php echo esc_html($adaptive_data['challenge_score']); ?>/10</span>
                            </div>
                            <div class="botfend-badge-item">
                                <span class="badge-label"><?php esc_html_e('Rate Limit', 'botfend-anti-bot-firewall'); ?></span>
                                <span class="badge-value"><?php echo esc_html($adaptive_data['rate_limit']); ?>/min</span>
                            </div>
                            <div class="botfend-badge-item">
                                <span class="badge-label"><?php esc_html_e('Sampling', 'botfend-anti-bot-firewall'); ?></span>
                                <span class="badge-value"><?php echo esc_html($adaptive_data['sampling_rate']); ?>%</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="botfend-adaptive-secondary">
                    <div class="botfend-card">
                        <div class="botfend-card-header botfend-collapsible-header">
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <span class="dashicons dashicons-controls-play"></span>
                                <h3><?php echo esc_html__('Quick Actions', 'botfend-anti-bot-firewall'); ?></h3>
                            </div>
                            <span class="dashicons dashicons-arrow-up botfend-toggle-icon"></span>
                        </div>
                        <div class="botfend-collapsible-content">
                            <div class="botfend-quick-actions">
                                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-settings')); ?>" class="botfend-action-btn">
                                    <span class="dashicons dashicons-admin-settings"></span>
                                    <?php echo esc_html__('Settings', 'botfend-anti-bot-firewall'); ?>
                                </a>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-dashboard')); ?>" class="botfend-action-btn">
                                    <span class="dashicons dashicons-dashboard"></span>
                                    <?php echo esc_html__('Main Dashboard', 'botfend-anti-bot-firewall'); ?>
                                </a>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-logs')); ?>" class="botfend-action-btn">
                                    <span class="dashicons dashicons-archive"></span>
                                    <?php echo esc_html__('View Threat Logs', 'botfend-anti-bot-firewall'); ?>
                                </a>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-blocklist')); ?>" class="botfend-action-btn">
                                    <span class="dashicons dashicons-list-view"></span>
                                    <?php echo esc_html__('Manage Blocklist', 'botfend-anti-bot-firewall'); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
}