<?php

/**
 * Guard Dog Dashboard Page
 *
 * Informational landing page with security score, quick stats,
 * feature status overview, and recent activity feed.
 *
 * @package GuardDog
 * @since 1.6.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class Guard_Dog_Dashboard_Page {

    /**
     * Feature instances.
     *
     * @var array
     */
    private array $features;

    /**
     * @param array $features Feature class instances.
     */
    public function __construct(array $features = []) {
        $this->features = $features;
    }

    /**
     * Render the dashboard page.
     */
    public function render(): void {
        $score_data = $this->calculate_security_score();
        ?>
        <div class="wrap guard-dog-dashboard">
            <h1 class="guard-dog-title">
                <span class="dashicons dashicons-pets"></span>
                <?php esc_html_e('Guard Dog Security', 'guard-dog'); ?>
            </h1>

            <p class="guard-dog-subtitle">
                <?php esc_html_e('Comprehensive WordPress security protection across all attack vectors', 'guard-dog'); ?>
            </p>

            <?php $this->render_security_score($score_data); ?>
            <?php $this->render_quick_stats(); ?>

            <div class="guard-dog-dashboard-grid">
                <div class="guard-dog-dashboard-main">
                    <?php $this->render_feature_cards(); ?>
                </div>
                <div class="guard-dog-dashboard-sidebar">
                    <?php $this->render_recent_activity(); ?>
                    <?php $this->render_quick_actions(); ?>
                </div>
            </div>
        </div>
        <?php
    }

    /* ------------------------------------------------------------------
     * Security Score
     * ----------------------------------------------------------------*/

    /**
     * Calculate a security score based on which features are enabled.
     *
     * @return array{score: int, level: string, checks: array}
     */
    private function calculate_security_score(): array {
        $checks = [];

        // Custom login URL (10 pts)
        $custom_url = get_option('guard_dog_login_slug', '');
        $checks[] = [
            'label'   => __('Custom Login URL', 'guard-dog'),
            'enabled' => !empty($custom_url),
            'points'  => 10,
        ];

        // Login attempt limiting (15 pts)
        $lla = get_option('guard_dog_lla_enabled', false);
        $checks[] = [
            'label'   => __('Login Attempt Limiting', 'guard-dog'),
            'enabled' => (bool) $lla,
            'points'  => 15,
        ];

        // Two-factor authentication (15 pts)
        $tfa_enabled = get_option('guard_dog_email_2fa_enabled', false);
        $checks[] = [
            'label'   => __('Two-Factor Authentication', 'guard-dog'),
            'enabled' => (bool) $tfa_enabled,
            'points'  => 15,
        ];

        // CAPTCHA (10 pts)
        $captcha = get_option('guard_dog_captcha_provider', 'none');
        $checks[] = [
            'label'   => __('CAPTCHA Protection', 'guard-dog'),
            'enabled' => $captcha !== 'none',
            'points'  => 10,
        ];

        // Access control rules (10 pts)
        $has_access_rules = !empty(get_option('guard_dog_ip_whitelist', ''))
            || !empty(get_option('guard_dog_ip_blacklist', ''));
        $checks[] = [
            'label'   => __('Access Control Rules', 'guard-dog'),
            'enabled' => $has_access_rules,
            'points'  => 10,
        ];

        // Password policy (10 pts)
        $password_policy = get_option('guard_dog_password_policy_enabled', false);
        $checks[] = [
            'label'   => __('Password Policy', 'guard-dog'),
            'enabled' => (bool) $password_policy,
            'points'  => 10,
        ];

        // Email verification (10 pts)
        $email_verify = get_option('guard_dog_email_verification_enabled', false);
        $checks[] = [
            'label'   => __('Email Verification', 'guard-dog'),
            'enabled' => (bool) $email_verify,
            'points'  => 10,
        ];

        // Session management (10 pts)
        $sessions = get_option('guard_dog_sessions_enabled', true);
        $checks[] = [
            'label'   => __('Session Management', 'guard-dog'),
            'enabled' => (bool) $sessions,
            'points'  => 10,
        ];

        // IP reputation (10 pts)
        $ip_rep = get_option('guard_dog_ip_reputation_login_enabled', true);
        $checks[] = [
            'label'   => __('IP Reputation Blocking', 'guard-dog'),
            'enabled' => (bool) $ip_rep,
            'points'  => 10,
        ];

        $total   = 0;
        $earned  = 0;
        foreach ($checks as $check) {
            $total += $check['points'];
            if ($check['enabled']) {
                $earned += $check['points'];
            }
        }

        $score = $total > 0 ? (int) round(($earned / $total) * 100) : 0;

        if ($score >= 80) {
            $level = 'secure';
        } elseif ($score >= 50) {
            $level = 'warning';
        } else {
            $level = 'danger';
        }

        return [
            'score'  => $score,
            'level'  => $level,
            'checks' => $checks,
        ];
    }

    /**
     * Render the security score banner.
     *
     * @param array $score_data From calculate_security_score().
     */
    private function render_security_score(array $score_data): void {
        $level_labels = [
            'secure'  => __('Strong', 'guard-dog'),
            'warning' => __('Moderate', 'guard-dog'),
            'danger'  => __('Weak', 'guard-dog'),
        ];
        $label = $level_labels[$score_data['level']] ?? '';
        ?>
        <div class="guard-dog-card">
            <div class="guard-dog-security-status">
                <h3><?php esc_html_e('Security Score', 'guard-dog'); ?></h3>
                <div class="guard-dog-status-indicator <?php echo esc_attr($score_data['level']); ?>">
                    <?php
                    printf(
                        /* translators: 1: numeric score 2: level label */
                        esc_html__('%1$d%% — %2$s', 'guard-dog'),
                        (int) $score_data['score'],
                        esc_html($label)
                    );
                    ?>
                </div>
                <div class="guard-dog-score-details" style="margin-top: 12px; display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 6px;">
                    <?php foreach ($score_data['checks'] as $check) : ?>
                        <div style="display: flex; align-items: center; gap: 6px; font-size: 13px;">
                            <span style="color: <?php echo $check['enabled'] ? '#28a745' : '#dc3545'; ?>;">
                                <?php echo $check['enabled'] ? '&#10003;' : '&#10007;'; ?>
                            </span>
                            <?php echo esc_html($check['label']); ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php
    }

    /* ------------------------------------------------------------------
     * Quick Stats
     * ----------------------------------------------------------------*/

    /**
     * Render the quick-stats row.
     */
    private function render_quick_stats(): void {
        global $wpdb;

        $logs_table     = esc_sql($wpdb->prefix . 'guard_dog_logs');
        $sessions_table = esc_sql($wpdb->prefix . 'guard_dog_sessions');
        $lockouts_table = esc_sql($wpdb->prefix . 'guard_dog_lla_lockouts');

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        // Table names are constructed from $wpdb->prefix (WordPress-controlled) and escaped with esc_sql().
        // Direct queries needed for custom tables; caching inappropriate for fresh dashboard stats.
        $total_events     = (int) $wpdb->get_var("SELECT COUNT(*) FROM $logs_table");
        $events_24h       = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $logs_table WHERE timestamp > %s",
            gmdate('Y-m-d H:i:s', time() - DAY_IN_SECONDS)
        ));
        $active_sessions  = (int) $wpdb->get_var("SELECT COUNT(*) FROM $sessions_table");
        $active_lockouts  = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $lockouts_table WHERE lockout_expiry > %s",
            current_time('mysql')
        ));
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        ?>
        <div class="guard-dog-stats-grid">
            <div class="guard-dog-stat-item">
                <div class="guard-dog-stat-number"><?php echo esc_html(number_format_i18n($events_24h)); ?></div>
                <div class="guard-dog-stat-label"><?php esc_html_e('Events (24 h)', 'guard-dog'); ?></div>
            </div>
            <div class="guard-dog-stat-item">
                <div class="guard-dog-stat-number"><?php echo esc_html(number_format_i18n($total_events)); ?></div>
                <div class="guard-dog-stat-label"><?php esc_html_e('Total Events', 'guard-dog'); ?></div>
            </div>
            <div class="guard-dog-stat-item">
                <div class="guard-dog-stat-number"><?php echo esc_html(number_format_i18n($active_sessions)); ?></div>
                <div class="guard-dog-stat-label"><?php esc_html_e('Active Sessions', 'guard-dog'); ?></div>
            </div>
            <div class="guard-dog-stat-item">
                <div class="guard-dog-stat-number"><?php echo esc_html(number_format_i18n($active_lockouts)); ?></div>
                <div class="guard-dog-stat-label"><?php esc_html_e('Active Lockouts', 'guard-dog'); ?></div>
            </div>
        </div>
        <?php
    }

    /* ------------------------------------------------------------------
     * Feature Cards — linking to new consolidated pages
     * ----------------------------------------------------------------*/

    /**
     * Render the feature-cards section.
     */
    private function render_feature_cards(): void {
        ?>
        <div class="guard-dog-card">
            <h2><?php esc_html_e('Security Features', 'guard-dog'); ?></h2>
            <div class="guard-dog-features-grid">
                <?php
                $this->render_feature_card(
                    'dashicons-lock',
                    __('Authentication', 'guard-dog'),
                    $this->get_authentication_status(),
                    __('Custom login URLs, brute-force limiting, CAPTCHA, 2FA, passkeys, and social login.', 'guard-dog'),
                    admin_url('admin.php?page=' . Guard_Dog_Admin::AUTHENTICATION_SLUG),
                    __('Configure', 'guard-dog')
                );
                $this->render_feature_card(
                    'dashicons-shield',
                    __('Access Control', 'guard-dog'),
                    $this->get_access_control_status(),
                    __('IP and user whitelisting/blacklisting, country blocking, and user enumeration protection.', 'guard-dog'),
                    admin_url('admin.php?page=' . Guard_Dog_Admin::ACCESS_CONTROL_SLUG),
                    __('Configure', 'guard-dog')
                );
                $this->render_feature_card(
                    'dashicons-groups',
                    __('Users & Sessions', 'guard-dog'),
                    $this->get_users_sessions_status(),
                    __('Email verification, password policies, temporary access, and session management.', 'guard-dog'),
                    admin_url('admin.php?page=' . Guard_Dog_Admin::USERS_SESSIONS_SLUG),
                    __('Configure', 'guard-dog')
                );
                $this->render_feature_card(
                    'dashicons-chart-bar',
                    __('Activity Log', 'guard-dog'),
                    ['status' => 'enabled', 'text' => __('Active', 'guard-dog')],
                    __('Comprehensive event logging and security activity monitoring.', 'guard-dog'),
                    admin_url('admin.php?page=' . Guard_Dog_Admin::ACTIVITY_LOG_SLUG),
                    __('View Logs', 'guard-dog')
                );
                ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render a single feature card.
     *
     * @param string $icon       Dashicon class (without prefix).
     * @param string $title      Card heading.
     * @param array  $status     {status: string, text: string}.
     * @param string $desc       Description text.
     * @param string $url        Link target.
     * @param string $link_label Link text.
     */
    private function render_feature_card(
        string $icon,
        string $title,
        array $status,
        string $desc,
        string $url,
        string $link_label
    ): void {
        ?>
        <div class="guard-dog-feature-card">
            <div class="guard-dog-feature-header">
                <div class="guard-dog-feature-icon">
                    <span class="dashicons <?php echo esc_attr($icon); ?>" style="font-size: 20px; color: #fff;"></span>
                </div>
                <div class="guard-dog-feature-title">
                    <h3><?php echo esc_html($title); ?></h3>
                    <span class="guard-dog-feature-status <?php echo esc_attr($status['status']); ?>">
                        <?php echo esc_html($status['text']); ?>
                    </span>
                </div>
            </div>
            <p class="guard-dog-feature-description"><?php echo esc_html($desc); ?></p>
            <a href="<?php echo esc_url($url); ?>" class="guard-dog-feature-action">
                <?php echo esc_html($link_label); ?>
            </a>
        </div>
        <?php
    }

    /* ------------------------------------------------------------------
     * Status helpers
     * ----------------------------------------------------------------*/

    /**
     * @return array{status: string, text: string}
     */
    private function get_authentication_status(): array {
        $count = 0;
        if (!empty(get_option('guard_dog_login_slug', ''))) {
            $count++;
        }
        if (get_option('guard_dog_lla_enabled', false)) {
            $count++;
        }
        if (get_option('guard_dog_email_2fa_enabled', false)) {
            $count++;
        }
        if (get_option('guard_dog_captcha_provider', 'none') !== 'none') {
            $count++;
        }

        if ($count >= 3) {
            return ['status' => 'enabled', 'text' => __('Active', 'guard-dog')];
        }
        if ($count > 0) {
            return ['status' => 'partial', 'text' => __('Partial', 'guard-dog')];
        }
        return ['status' => 'disabled', 'text' => __('Inactive', 'guard-dog')];
    }

    /**
     * @return array{status: string, text: string}
     */
    private function get_access_control_status(): array {
        $has_rules = !empty(get_option('guard_dog_ip_whitelist', ''))
            || !empty(get_option('guard_dog_ip_blacklist', ''));

        return $has_rules
            ? ['status' => 'enabled', 'text' => __('Active', 'guard-dog')]
            : ['status' => 'disabled', 'text' => __('Inactive', 'guard-dog')];
    }

    /**
     * @return array{status: string, text: string}
     */
    private function get_users_sessions_status(): array {
        $count = 0;
        if (get_option('guard_dog_email_verification_enabled', false)) {
            $count++;
        }
        if (get_option('guard_dog_password_policy_enabled', false)) {
            $count++;
        }
        if (get_option('guard_dog_sessions_enabled', true)) {
            $count++;
        }

        if ($count >= 2) {
            return ['status' => 'enabled', 'text' => __('Active', 'guard-dog')];
        }
        if ($count > 0) {
            return ['status' => 'partial', 'text' => __('Partial', 'guard-dog')];
        }
        return ['status' => 'disabled', 'text' => __('Inactive', 'guard-dog')];
    }

    /* ------------------------------------------------------------------
     * Recent Activity Feed
     * ----------------------------------------------------------------*/

    /**
     * Render the recent activity sidebar card.
     */
    private function render_recent_activity(): void {
        global $wpdb;

        $table_name = esc_sql($wpdb->prefix . 'guard_dog_logs');

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        // Table name uses $wpdb->prefix (WordPress-controlled) escaped with esc_sql().
        // Direct query for recent dashboard activity; caching would show stale data.
        $recent_logs = $wpdb->get_results(
            "SELECT event_type, details, timestamp FROM $table_name ORDER BY timestamp DESC LIMIT 10"
        );
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        ?>
        <div class="guard-dog-card">
            <h2><?php esc_html_e('Recent Activity', 'guard-dog'); ?></h2>
            <?php if (empty($recent_logs)) : ?>
                <p class="guard-dog-no-activity"><?php esc_html_e('No recent activity logged.', 'guard-dog'); ?></p>
            <?php else : ?>
                <div class="guard-dog-activity-list">
                    <?php foreach ($recent_logs as $log) :
                        $icon_data = $this->get_event_icon($log->event_type);
                        $time_ago  = human_time_diff(strtotime($log->timestamp), current_time('timestamp'));
                        ?>
                        <div class="guard-dog-activity-item">
                            <div class="guard-dog-activity-icon" style="background: <?php echo esc_attr($icon_data['bg']); ?>;">
                                <span class="dashicons <?php echo esc_attr($icon_data['icon']); ?>" style="font-size: 14px; color: <?php echo esc_attr($icon_data['color']); ?>;"></span>
                            </div>
                            <div class="guard-dog-activity-content">
                                <div class="guard-dog-activity-title">
                                    <?php echo esc_html($this->humanize_event_type($log->event_type)); ?>
                                </div>
                                <div class="guard-dog-activity-meta">
                                    <?php
                                    printf(
                                        /* translators: %s: human time diff */
                                        esc_html__('%s ago', 'guard-dog'),
                                        esc_html($time_ago)
                                    );
                                    ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="guard-dog-view-all">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=' . Guard_Dog_Admin::ACTIVITY_LOG_SLUG)); ?>">
                        <?php esc_html_e('View All Activity', 'guard-dog'); ?> &rarr;
                    </a>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Get icon data for an event type.
     *
     * @param string $event_type Event type key.
     * @return array{icon: string, bg: string, color: string}
     */
    private function get_event_icon(string $event_type): array {
        $map = [
            'login_success'          => ['dashicons-yes-alt', '#d4edda', '#155724'],
            'login_failed'           => ['dashicons-warning', '#f8d7da', '#721c24'],
            'login_lockout'          => ['dashicons-lock', '#f8d7da', '#721c24'],
            'user_registered'        => ['dashicons-admin-users', '#d1ecf1', '#0c5460'],
            'password_changed'       => ['dashicons-admin-network', '#fff3cd', '#856404'],
            'ip_blocked'             => ['dashicons-dismiss', '#f8d7da', '#721c24'],
            'ip_added_to_blacklist'  => ['dashicons-dismiss', '#f8d7da', '#721c24'],
            'session_terminated'     => ['dashicons-no', '#fff3cd', '#856404'],
            'two_factor_success'     => ['dashicons-yes-alt', '#d4edda', '#155724'],
            'two_factor_failed'      => ['dashicons-warning', '#f8d7da', '#721c24'],
        ];

        if (isset($map[$event_type])) {
            return [
                'icon'  => $map[$event_type][0],
                'bg'    => $map[$event_type][1],
                'color' => $map[$event_type][2],
            ];
        }

        return [
            'icon'  => 'dashicons-info-outline',
            'bg'    => '#f0f0f0',
            'color' => '#666',
        ];
    }

    /**
     * Convert event_type key to human-readable label.
     *
     * @param string $event_type The event type key.
     * @return string
     */
    private function humanize_event_type(string $event_type): string {
        $labels = [
            'login_success'            => __('Successful Login', 'guard-dog'),
            'login_failed'             => __('Failed Login Attempt', 'guard-dog'),
            'login_lockout'            => __('Account Locked Out', 'guard-dog'),
            'user_registered'          => __('New User Registered', 'guard-dog'),
            'password_changed'         => __('Password Changed', 'guard-dog'),
            'ip_blocked'               => __('IP Address Blocked', 'guard-dog'),
            'ip_added_to_blacklist'    => __('IP Added to Blacklist', 'guard-dog'),
            'ip_removed_from_blacklist' => __('IP Removed from Blacklist', 'guard-dog'),
            'session_terminated'       => __('Session Terminated', 'guard-dog'),
            'two_factor_success'       => __('2FA Verified', 'guard-dog'),
            'two_factor_failed'        => __('2FA Failed', 'guard-dog'),
            'email_verification_sent'  => __('Email Verification Sent', 'guard-dog'),
        ];

        return $labels[$event_type] ?? ucwords(str_replace('_', ' ', $event_type));
    }

    /* ------------------------------------------------------------------
     * Quick Actions
     * ----------------------------------------------------------------*/

    /**
     * Render the quick actions sidebar card.
     */
    private function render_quick_actions(): void {
        ?>
        <div class="guard-dog-card">
            <h2><?php esc_html_e('Quick Actions', 'guard-dog'); ?></h2>
            <div class="guard-dog-quick-actions" style="display: flex; flex-direction: column; gap: 8px;">
                <a href="<?php echo esc_url(admin_url('admin.php?page=' . Guard_Dog_Admin::AUTHENTICATION_SLUG)); ?>" class="guard-dog-quick-action">
                    <span class="dashicons dashicons-lock"></span>
                    <?php esc_html_e('Authentication Settings', 'guard-dog'); ?>
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=' . Guard_Dog_Admin::ACCESS_CONTROL_SLUG)); ?>" class="guard-dog-quick-action">
                    <span class="dashicons dashicons-shield"></span>
                    <?php esc_html_e('Access Control', 'guard-dog'); ?>
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=' . Guard_Dog_Admin::USERS_SESSIONS_SLUG)); ?>" class="guard-dog-quick-action">
                    <span class="dashicons dashicons-groups"></span>
                    <?php esc_html_e('Users & Sessions', 'guard-dog'); ?>
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=' . Guard_Dog_Admin::APPEARANCE_SLUG)); ?>" class="guard-dog-quick-action">
                    <span class="dashicons dashicons-admin-appearance"></span>
                    <?php esc_html_e('Appearance', 'guard-dog'); ?>
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=' . Guard_Dog_Admin::SETTINGS_SLUG)); ?>" class="guard-dog-quick-action">
                    <span class="dashicons dashicons-admin-generic"></span>
                    <?php esc_html_e('Settings', 'guard-dog'); ?>
                </a>
            </div>
        </div>
        <?php
    }
}
