<?php

namespace WPUltimateSecurity\UltimateSecurity\Modules\Authentication\LoginNotifications;

use WPUltimateSecurity\UltimateSecurity\Contracts\NotificationInterface;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\DateHelper;
use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\LoginNotifications;

/**
 * Email Notifier for Login Notifications
 *
 * Handles composing and sending all email notifications related to login security events.
 * Implements NotificationInterface for consistent notification API.
 *
 * @implements NotificationInterface
 */
class EmailNotifier implements NotificationInterface
{
    // =========================================================================
    // NotificationInterface Implementation
    // =========================================================================

    /**
     * {@inheritdoc}
     */
    public function send(int $userId, string $subject, string $message, array $data = []): bool
    {
        $user = get_user_by('ID', $userId);
        if (!$user) {
            // If no user, try sending to admin email
            $to = self::get_email();
        } else {
            // Send to user's email by default, or admin if specified in data
            $to = $data['send_to_admin'] ?? false ? self::get_email() : $user->user_email;
        }

        // Wrap message in template if not already HTML
        if (!empty($data['use_template']) || strpos($message, '<!DOCTYPE') === false) {
            $message = self::get_email_template($message, $subject);
        }

        return wp_mail($to, $subject, $message, self::get_headers());
    }

    /**
     * {@inheritdoc}
     */
    public function getType(): string
    {
        return 'email';
    }

    // =========================================================================
    // Static Methods (Existing Functionality)
    // =========================================================================

    /**
     * Get the notification email address
     */
    protected static function get_email(): string
    {
        $options = Utils::ultimate_security_get_option();
        $email = $options['security']['login_notifications']['notification_email'] ?? '';

        if (empty($email)) {
            $email = get_option('admin_email');
        }

        return $email;
    }

    /**
     * Get site name for emails
     */
    protected static function get_site_name(): string
    {
        return get_bloginfo('name') ?: parse_url(home_url(), PHP_URL_HOST);
    }

    /**
     * Get email headers
     */
    protected static function get_headers(): array
    {
        return [
            'Content-Type: text/html; charset=UTF-8',
            'From: Ultimate Security <noreply@' . parse_url(home_url(), PHP_URL_HOST) . '>',
        ];
    }

    /**
     * Get the email template wrapper
     */
    protected static function get_email_template(string $content, string $title = ''): string
    {
        $site_name = self::get_site_name();
        $site_url = home_url();
        $logo_url = ULTIMATE_SECURITY_URL . 'assets/images/logo.png';

        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title><?php echo esc_html($title ?: $site_name); ?></title>
            <style>
                body {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif;
                    background-color: #f5f5f5;
                    margin: 0;
                    padding: 0;
                }
                .container {
                    max-width: 600px;
                    margin: 20px auto;
                    background: #ffffff;
                    border-radius: 8px;
                    overflow: hidden;
                    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                }
                .header {
                    background: #7C3AED;
                    padding: 30px;
                    text-align: center;
                }
                .header h1 {
                    color: #ffffff;
                    margin: 0;
                    font-size: 24px;
                    font-weight: 600;
                }
                .header .site-name {
                    color: rgba(255,255,255,0.8);
                    font-size: 14px;
                    margin-top: 5px;
                }
                .content {
                    padding: 30px;
                }
                .alert-box {
                    background: #fff3cd;
                    border: 1px solid #ffc107;
                    border-radius: 6px;
                    padding: 15px;
                    margin-bottom: 20px;
                }
                .alert-box.danger {
                    background: #f8d7da;
                    border-color: #dc3545;
                }
                .alert-box.success {
                    background: #d4edda;
                    border-color: #28a745;
                }
                .alert-box.info {
                    background: #d1ecf1;
                    border-color: #17a2b8;
                }
                .info-table {
                    width: 100%;
                    border-collapse: collapse;
                    margin: 20px 0;
                }
                .info-table td {
                    padding: 12px;
                    border-bottom: 1px solid #eee;
                }
                .info-table td:first-child {
                    font-weight: 600;
                    color: #555;
                    width: 140px;
                }
                .btn {
                    display: inline-block;
                    padding: 12px 24px;
                    background: #dc3545;
                    color: #ffffff !important;
                    text-decoration: none;
                    border-radius: 6px;
                    font-weight: 600;
                    margin: 10px 5px 10px 0;
                }
                .btn-primary {
                    background: #7C3AED;
                }
                .btn-secondary {
                    background: #6c757d;
                }
                .footer {
                    background: #f8f9fa;
                    padding: 20px 30px;
                    text-align: center;
                    font-size: 12px;
                    color: #6c757d;
                }
                .footer a {
                    color: #7C3AED;
                    text-decoration: none;
                }
                .stats-grid {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 15px;
                    margin: 20px 0;
                }
                .stat-box {
                    flex: 1;
                    min-width: 120px;
                    background: #f8f9fa;
                    border-radius: 6px;
                    padding: 15px;
                    text-align: center;
                }
                .stat-box .number {
                    font-size: 28px;
                    font-weight: 700;
                    color: #333;
                }
                .stat-box .label {
                    font-size: 12px;
                    color: #6c757d;
                    text-transform: uppercase;
                }
                .ip-list {
                    list-style: none;
                    padding: 0;
                    margin: 0;
                }
                .ip-list li {
                    padding: 10px 15px;
                    background: #f8f9fa;
                    margin-bottom: 5px;
                    border-radius: 4px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                }
                .badge {
                    display: inline-block;
                    padding: 3px 8px;
                    border-radius: 12px;
                    font-size: 11px;
                    font-weight: 600;
                }
                .badge-danger {
                    background: #f8d7da;
                    color: #721c24;
                }
                .badge-warning {
                    background: #fff3cd;
                    color: #856404;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1><?php echo esc_html($title ?: __('Security Alert', 'ultimate-security')); ?></h1>
                    <div class="site-name"><?php echo esc_html($site_name); ?></div>
                </div>
                <div class="content">
                    <?php echo wp_kses_post($content); ?>
                </div>
                <div class="footer">
                    <p><?php esc_html_e('This email was sent by Ultimate Security plugin.', 'ultimate-security'); ?></p>
                    <p>
                        <a href="<?php echo esc_url($site_url); ?>"><?php echo esc_html($site_name); ?></a> |
                        <a href="<?php echo esc_url(admin_url('admin.php?page=ultimate-security#/settings/threat/brute-force/login-notifications')); ?>"><?php esc_html_e('Notification Settings', 'ultimate-security'); ?></a>
                    </p>
                </div>
            </div>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Format timestamp for display using DateHelper
     */
    protected static function format_time(int $timestamp): string
    {
        return DateHelper::format($timestamp);
    }

    /**
     * Format geolocation for display
     */
    protected static function format_geolocation(?array $geo): string
    {
        if (empty($geo)) {
            return __('Unknown', 'ultimate-security');
        }

        $parts = array_filter([
            $geo['city'] ?? '',
            $geo['region'] ?? '',
            $geo['country'] ?? '',
        ]);

        return implode(', ', $parts) ?: __('Unknown', 'ultimate-security');
    }

    /**
     * Get one-click block URL
     */
    protected static function get_block_url(string $ip): string
    {
        $nonce = wp_create_nonce('ultimate_security_block_ip');
        return add_query_arg([
            'action' => 'ultimate_security_quick_block',
            'ip' => $ip,
            'nonce' => $nonce,
        ], admin_url('admin.php'));
    }

    /**
     * Send failed login attempts notification
     */
    public static function send_failed_attempts_notification(array $data): bool
    {
        $email = self::get_email();
        $site_name = self::get_site_name();

        $subject = sprintf(
            /* translators: 1: Number of attempts, 2: Site name */
            __('[%2$s] Security Alert: %1$d Failed Login Attempts', 'ultimate-security'),
            $data['attempts'],
            $site_name
        );

        $options = Utils::ultimate_security_get_option();
        $show_block_button = $options['security']['login_notifications']['one_click_block'] === '1';

        ob_start();
        ?>
        <div class="alert-box danger">
            <strong><?php esc_html_e('Multiple Failed Login Attempts Detected', 'ultimate-security'); ?></strong>
        </div>

        <p><?php esc_html_e('Someone has made multiple failed login attempts to your WordPress site.', 'ultimate-security'); ?></p>

        <table class="info-table">
            <tr>
                <td><?php esc_html_e('IP Address', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($data['ip']); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Username Tried', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($data['username']); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Attempts', 'ultimate-security'); ?></td>
                <td><strong><?php echo esc_html($data['attempts']); ?></strong></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Location', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_geolocation($data['geolocation'])); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Time', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_time($data['timestamp'])); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Browser', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($data['user_agent']); ?></td>
            </tr>
        </table>

        <?php if ($show_block_button): ?>
            <p>
                <a href="<?php echo esc_url(self::get_block_url($data['ip'])); ?>" class="btn"><?php esc_html_e('Block This IP', 'ultimate-security'); ?></a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=ultimate-security#/settings/threat/brute-force/login-limit')); ?>" class="btn btn-secondary"><?php esc_html_e('View Settings', 'ultimate-security'); ?></a>
            </p>
        <?php endif; ?>

        <p style="color: #6c757d; font-size: 13px;">
            <?php esc_html_e('If this is you, no action is needed. If you do not recognize this activity, consider blocking this IP address.', 'ultimate-security'); ?>
        </p>
        <?php
        $content = ob_get_clean();

        return wp_mail(
            $email,
            $subject,
            self::get_email_template($content, __('Failed Login Alert', 'ultimate-security')),
            self::get_headers()
        );
    }

    /**
     * Send lockout notification
     */
    public static function send_lockout_notification(\WP_User $user, string $ip, string $user_agent, array $data = []): bool
    {
        $email = self::get_email();
        $site_name = self::get_site_name();

        $subject = sprintf(
            /* translators: 1: Username, 2: Site name */
            __('[%2$s] Account Locked: %1$s', 'ultimate-security'),
            $user->user_login,
            $site_name
        );

        $options = Utils::ultimate_security_get_option();
        $show_block_button = $options['security']['login_notifications']['one_click_block'] === '1';
        $geolocation = LoginNotifications::get_geolocation($ip);

        ob_start();
        ?>
        <div class="alert-box danger">
            <strong><?php esc_html_e('Account Lockout Triggered', 'ultimate-security'); ?></strong>
        </div>

        <p><?php
            printf(
                /* translators: %s: Username */
                esc_html__('The account "%s" has been locked due to too many failed login attempts.', 'ultimate-security'),
                esc_html($user->user_login)
            );
        ?></p>

        <table class="info-table">
            <tr>
                <td><?php esc_html_e('Username', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($user->user_login); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('User Email', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($user->user_email); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('IP Address', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($ip); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Location', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_geolocation($geolocation)); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Lockout Duration', 'ultimate-security'); ?></td>
                <td><?php
                    $duration = isset($data['duration_m'])?esc_html($data['duration_m']) : 0;
                    if ($duration >= 60) {
                        printf(
                            /* translators: %d: Number of hours */
                            esc_html(_n('%d hour', '%d hours', floor($duration / 60), 'ultimate-security')),
                            floor($duration / 60)
                        );
                    } else {
                        printf(
                            /* translators: %d: Number of minutes */
                            esc_html(_n('%d minute', '%d minutes', $duration, 'ultimate-security')),
                            esc_html($duration)
                        );
                    }
                ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Lockout Phase', 'ultimate-security'); ?></td>
                <td>
                    <span class="badge <?php echo ($data['phase'] ?? 1) >= 2 ? 'badge-danger' : 'badge-warning'; ?>">
                        <?php
                            $phase = $data['phase'] ?? 1;
                            if ($phase >= 2) {
                                esc_html_e('Phase 2 (Extended)', 'ultimate-security');
                            } else {
                                esc_html_e('Phase 1 (Standard)', 'ultimate-security');
                            }
                        ?>
                    </span>
                </td>
            </tr>
            <tr>
                <td><?php esc_html_e('Time', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_time(time())); ?></td>
            </tr>
        </table>

        <?php if ($show_block_button): ?>
            <p>
                <a href="<?php echo esc_url(self::get_block_url($ip)); ?>" class="btn"><?php esc_html_e('Block This IP', 'ultimate-security'); ?></a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=ultimate-security#/settings/threat/brute-force/locked-users')); ?>" class="btn btn-secondary"><?php esc_html_e('View Locked Users', 'ultimate-security'); ?></a>
            </p>
        <?php endif; ?>
        <?php
        $content = ob_get_clean();

        return wp_mail(
            $email,
            $subject,
            self::get_email_template($content, __('Account Locked', 'ultimate-security')),
            self::get_headers()
        );
    }

    /**
     * Send new IP notification
     */
    public static function send_new_ip_notification(\WP_User $user, string $ip, string $user_agent, ?array $geolocation): bool
    {
        $email = self::get_email();
        $site_name = self::get_site_name();

        $subject = sprintf(
            /* translators: 1: Username, 2: Site name */
            __('[%2$s] New Login Location: %1$s', 'ultimate-security'),
            $user->user_login,
            $site_name
        );

        $parsed_ua = Utils::parse_user_agent($user_agent);

        ob_start();
        ?>
        <div class="alert-box info">
            <strong><?php esc_html_e('Login From New Location', 'ultimate-security'); ?></strong>
        </div>

        <p><?php
            printf(
                /* translators: %s: Username */
                esc_html__('A successful login was detected for "%s" from a new IP address.', 'ultimate-security'),
                esc_html($user->user_login)
            );
        ?></p>

        <table class="info-table">
            <tr>
                <td><?php esc_html_e('Username', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($user->user_login); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('IP Address', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($ip); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Location', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_geolocation($geolocation)); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Device', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($parsed_ua['device'] . ' - ' . $parsed_ua['browser']); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Platform', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($parsed_ua['platform']); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Time', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_time(time())); ?></td>
            </tr>
        </table>

        <p style="color: #6c757d; font-size: 13px;">
            <?php esc_html_e('If this was you, no action is needed. If you do not recognize this login, please change your password immediately and review your account security.', 'ultimate-security'); ?>
        </p>

        <p>
            <a href="<?php echo esc_url(admin_url('profile.php')); ?>" class="btn btn-primary"><?php esc_html_e('Review Account', 'ultimate-security'); ?></a>
        </p>
        <?php
        $content = ob_get_clean();

        return wp_mail(
            $email,
            $subject,
            self::get_email_template($content, __('New Login Location', 'ultimate-security')),
            self::get_headers()
        );
    }

    /**
     * Send new device notification
     */
    public static function send_new_device_notification(\WP_User $user, string $ip, string $user_agent, array $parsed_ua, ?array $geolocation): bool
    {
        $email = self::get_email();
        $site_name = self::get_site_name();

        $subject = sprintf(
            /* translators: 1: Username, 2: Site name */
            __('[%2$s] New Device Login: %1$s', 'ultimate-security'),
            $user->user_login,
            $site_name
        );

        ob_start();
        ?>
        <div class="alert-box info">
            <strong><?php esc_html_e('Login From New Device', 'ultimate-security'); ?></strong>
        </div>

        <p><?php
            printf(
                /* translators: %s: Username */
                esc_html__('A successful login was detected for "%s" from a new device.', 'ultimate-security'),
                esc_html($user->user_login)
            );
        ?></p>

        <table class="info-table">
            <tr>
                <td><?php esc_html_e('Username', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($user->user_login); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Device Type', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($parsed_ua['device']); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Browser', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($parsed_ua['browser'] . ' ' . $parsed_ua['version']); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Platform', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($parsed_ua['platform']); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('IP Address', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($ip); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Location', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_geolocation($geolocation)); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Time', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_time(time())); ?></td>
            </tr>
        </table>

        <p style="color: #6c757d; font-size: 13px;">
            <?php esc_html_e('If this was you, no action is needed. If you do not recognize this device, please change your password immediately.', 'ultimate-security'); ?>
        </p>

        <p>
            <a href="<?php echo esc_url(admin_url('profile.php')); ?>" class="btn btn-primary"><?php esc_html_e('Review Account', 'ultimate-security'); ?></a>
        </p>
        <?php
        $content = ob_get_clean();

        return wp_mail(
            $email,
            $subject,
            self::get_email_template($content, __('New Device Login', 'ultimate-security')),
            self::get_headers()
        );
    }

    /**
     * Send success after failed attempts notification
     */
    public static function send_success_after_fail_notification(\WP_User $user, string $ip, string $user_agent, int $failed_attempts, ?array $geolocation): bool
    {
        $email = self::get_email();
        $site_name = self::get_site_name();

        $subject = sprintf(
            /* translators: 1: Username, 2: Site name */
            __('[%2$s] Successful Login After Failed Attempts: %1$s', 'ultimate-security'),
            $user->user_login,
            $site_name
        );

        $parsed_ua = Utils::parse_user_agent($user_agent);

        ob_start();
        ?>
        <div class="alert-box success">
            <strong><?php esc_html_e('Successful Login After Failed Attempts', 'ultimate-security'); ?></strong>
        </div>

        <p><?php
            printf(
                /* translators: 1: Username, 2: Number of failed attempts */
                esc_html__('The account "%1$s" successfully logged in after %2$d failed attempt(s).', 'ultimate-security'),
                esc_html($user->user_login),
                esc_html($failed_attempts)
            );
        ?></p>

        <table class="info-table">
            <tr>
                <td><?php esc_html_e('Username', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($user->user_login); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Failed Attempts', 'ultimate-security'); ?></td>
                <td><strong><?php echo esc_html($failed_attempts); ?></strong></td>
            </tr>
            <tr>
                <td><?php esc_html_e('IP Address', 'ultimate-security'); ?></td>
                <td><code><?php echo esc_html($ip); ?></code></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Location', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_geolocation($geolocation)); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Device', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($parsed_ua['device'] . ' - ' . $parsed_ua['browser']); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Time', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_time(time())); ?></td>
            </tr>
        </table>

        <p style="color: #6c757d; font-size: 13px;">
            <?php esc_html_e('This notification is sent because someone successfully logged in after multiple failed attempts. This could indicate someone guessed the correct password.', 'ultimate-security'); ?>
        </p>
        <?php
        $content = ob_get_clean();

        return wp_mail(
            $email,
            $subject,
            self::get_email_template($content, __('Login Success Alert', 'ultimate-security')),
            self::get_headers()
        );
    }

    /**
     * Send daily digest email
     */
    public static function send_daily_digest(array $stats): bool
    {
        $email = self::get_email();
        $site_name = self::get_site_name();

        $subject = sprintf(
            /* translators: 1: Site name, 2: Date */
            __('[%1$s] Daily Security Digest - %2$s', 'ultimate-security'),
            $site_name,
            DateHelper::formatDate(time())
        );

        ob_start();
        ?>
        <p><?php esc_html_e('Here is your daily login security summary for the past 24 hours.', 'ultimate-security'); ?></p>

        <div class="stats-grid">
            <div class="stat-box">
                <div class="number"><?php echo esc_html($stats['total_attempts']); ?></div>
                <div class="label"><?php esc_html_e('Total Attempts', 'ultimate-security'); ?></div>
            </div>
            <div class="stat-box">
                <div class="number" style="color: #28a745;"><?php echo esc_html($stats['successful_logins']); ?></div>
                <div class="label"><?php esc_html_e('Successful', 'ultimate-security'); ?></div>
            </div>
            <div class="stat-box">
                <div class="number" style="color: #dc3545;"><?php echo esc_html($stats['failed_attempts']); ?></div>
                <div class="label"><?php esc_html_e('Failed', 'ultimate-security'); ?></div>
            </div>
            <div class="stat-box">
                <div class="number" style="color: #ffc107;"><?php echo esc_html($stats['lockouts']); ?></div>
                <div class="label"><?php esc_html_e('Lockouts', 'ultimate-security'); ?></div>
            </div>
        </div>

        <?php if (!empty($stats['top_attacking_ips'])): ?>
            <h3><?php esc_html_e('Top Attacking IPs', 'ultimate-security'); ?></h3>
            <ul class="ip-list">
                <?php foreach ($stats['top_attacking_ips'] as $ip_data): ?>
                    <li>
                        <span><code><?php echo esc_html($ip_data['ip']); ?></code></span>
                        <span class="badge badge-danger"><?php echo esc_html($ip_data['count']); ?> <?php esc_html_e('attempts', 'ultimate-security'); ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <?php if (!empty($stats['targeted_usernames'])): ?>
            <h3><?php esc_html_e('Targeted Usernames', 'ultimate-security'); ?></h3>
            <ul class="ip-list">
                <?php foreach ($stats['targeted_usernames'] as $username_data): ?>
                    <li>
                        <span><code><?php echo esc_html($username_data['username']); ?></code></span>
                        <span class="badge badge-warning"><?php echo esc_html($username_data['count']); ?> <?php esc_html_e('attempts', 'ultimate-security'); ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <?php if (!empty($stats['locked_accounts'])): ?>
            <h3><?php esc_html_e('Locked Accounts', 'ultimate-security'); ?></h3>
            <p><?php
                printf(
                    /* translators: %d: Number of accounts */
                    esc_html(_n('%d account was locked today.', '%d accounts were locked today.', count($stats['locked_accounts']), 'ultimate-security')),
                    count($stats['locked_accounts'])
                );
            ?></p>
        <?php endif; ?>

        <p style="margin-top: 30px;">
            <a href="<?php echo esc_url(admin_url('admin.php?page=ultimate-security#/activity-logs')); ?>" class="btn btn-primary"><?php esc_html_e('View Activity Logs', 'ultimate-security'); ?></a>
        </p>
        <?php
        $content = ob_get_clean();

        return wp_mail(
            $email,
            $subject,
            self::get_email_template($content, __('Daily Security Digest', 'ultimate-security')),
            self::get_headers()
        );
    }

    /**
     * Send weekly summary email
     */
    public static function send_weekly_summary(array $stats): bool
    {
        $email = self::get_email();
        $site_name = self::get_site_name();

        $subject = sprintf(
            /* translators: 1: Site name */
            __('[%1$s] Weekly Security Report', 'ultimate-security'),
            $site_name
        );

        ob_start();
        ?>
        <p><?php esc_html_e('Here is your weekly security summary for the past 7 days.', 'ultimate-security'); ?></p>

        <div class="stats-grid">
            <div class="stat-box">
                <div class="number"><?php echo esc_html($stats['total_attempts']); ?></div>
                <div class="label"><?php esc_html_e('Total Login Attempts', 'ultimate-security'); ?></div>
            </div>
            <div class="stat-box">
                <div class="number" style="color: #28a745;"><?php echo esc_html($stats['successful_logins']); ?></div>
                <div class="label"><?php esc_html_e('Successful Logins', 'ultimate-security'); ?></div>
            </div>
            <div class="stat-box">
                <div class="number" style="color: #dc3545;"><?php echo esc_html($stats['failed_attempts']); ?></div>
                <div class="label"><?php esc_html_e('Failed Attempts', 'ultimate-security'); ?></div>
            </div>
            <div class="stat-box">
                <div class="number" style="color: #ffc107;"><?php echo esc_html($stats['lockouts']); ?></div>
                <div class="label"><?php esc_html_e('Account Lockouts', 'ultimate-security'); ?></div>
            </div>
        </div>

        <h3><?php esc_html_e('Weekly Trends', 'ultimate-security'); ?></h3>
        <table class="info-table">
            <tr>
                <td><?php esc_html_e('Unique IPs', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($stats['unique_ips']); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Unique Users', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($stats['unique_users']); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('New IP Logins', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($stats['new_ip_logins'] ?? 0); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('IPs Blocked', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($stats['ips_blocked'] ?? 0); ?></td>
            </tr>
        </table>

        <?php if (!empty($stats['top_attacking_ips'])): ?>
            <h3><?php esc_html_e('Top 10 Attacking IPs This Week', 'ultimate-security'); ?></h3>
            <ul class="ip-list">
                <?php foreach (array_slice($stats['top_attacking_ips'], 0, 10) as $ip_data): ?>
                    <li>
                        <span>
                            <code><?php echo esc_html($ip_data['ip']); ?></code>
                            <?php if (!empty($ip_data['location'])): ?>
                                <small style="color: #6c757d;">(<?php echo esc_html($ip_data['location']); ?>)</small>
                            <?php endif; ?>
                        </span>
                        <span class="badge badge-danger"><?php echo esc_html($ip_data['count']); ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <?php if (!empty($stats['daily_breakdown'])): ?>
            <h3><?php esc_html_e('Daily Breakdown', 'ultimate-security'); ?></h3>
            <table class="info-table">
                <tr style="background: #f8f9fa;">
                    <td><strong><?php esc_html_e('Day', 'ultimate-security'); ?></strong></td>
                    <td><strong><?php esc_html_e('Success', 'ultimate-security'); ?></strong></td>
                    <td><strong><?php esc_html_e('Failed', 'ultimate-security'); ?></strong></td>
                </tr>
                <?php foreach ($stats['daily_breakdown'] as $day => $day_stats): ?>
                    <tr>
                        <td><?php echo esc_html($day); ?></td>
                        <td style="color: #28a745;"><?php echo esc_html($day_stats['success']); ?></td>
                        <td style="color: #dc3545;"><?php echo esc_html($day_stats['failed']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>

        <p style="margin-top: 30px;">
            <a href="<?php echo esc_url(admin_url('admin.php?page=ultimate-security#/dashboard/general')); ?>" class="btn btn-primary"><?php esc_html_e('View Dashboard', 'ultimate-security'); ?></a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=ultimate-security#/activity-logs')); ?>" class="btn btn-secondary"><?php esc_html_e('Activity Logs', 'ultimate-security'); ?></a>
        </p>
        <?php
        $content = ob_get_clean();

        return wp_mail(
            $email,
            $subject,
            self::get_email_template($content, __('Weekly Security Report', 'ultimate-security')),
            self::get_headers()
        );
    }

    /**
     * Send test notification
     */
    public static function send_test_notification(string $email): bool
    {
        $site_name = self::get_site_name();

        $subject = sprintf(
            /* translators: %s: Site name */
            __('[%s] Test Notification - Login Notifications', 'ultimate-security'),
            $site_name
        );

        ob_start();
        ?>
        <div class="alert-box success">
            <strong><?php esc_html_e('Test Notification Successful!', 'ultimate-security'); ?></strong>
        </div>

        <p><?php esc_html_e('This is a test notification from Ultimate Security. If you received this email, your login notifications are configured correctly.', 'ultimate-security'); ?></p>

        <table class="info-table">
            <tr>
                <td><?php esc_html_e('Site', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($site_name); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Email', 'ultimate-security'); ?></td>
                <td><?php echo esc_html($email); ?></td>
            </tr>
            <tr>
                <td><?php esc_html_e('Time', 'ultimate-security'); ?></td>
                <td><?php echo esc_html(self::format_time(time())); ?></td>
            </tr>
        </table>

        <h3><?php esc_html_e('Active Notifications', 'ultimate-security'); ?></h3>
        <p><?php esc_html_e('Based on your current settings, you will receive notifications for:', 'ultimate-security'); ?></p>

        <?php
        $options = Utils::ultimate_security_get_option();
        $notification_options = $options['security']['login_notifications'] ?? [];
        ?>

        <ul style="padding-left: 20px;">
            <?php if (($notification_options['notify_on_failed'] ?? '1') === '1'): ?>
                <li><?php esc_html_e('Failed login attempts (threshold-based)', 'ultimate-security'); ?></li>
            <?php endif; ?>
            <?php if (($notification_options['notify_on_lockout'] ?? '1') === '1'): ?>
                <li><?php esc_html_e('Account lockouts', 'ultimate-security'); ?></li>
            <?php endif; ?>
            <?php if (($notification_options['notify_on_new_ip'] ?? '0') === '1'): ?>
                <li><?php esc_html_e('Login from new IP address', 'ultimate-security'); ?></li>
            <?php endif; ?>
            <?php if (($notification_options['notify_on_new_device'] ?? '0') === '1'): ?>
                <li><?php esc_html_e('Login from new device', 'ultimate-security'); ?></li>
            <?php endif; ?>
            <?php if (($notification_options['notify_on_success_after_fail'] ?? '1') === '1'): ?>
                <li><?php esc_html_e('Successful login after failed attempts', 'ultimate-security'); ?></li>
            <?php endif; ?>
            <?php if (($notification_options['daily_digest'] ?? '1') === '1'): ?>
                <li><?php esc_html_e('Daily security digest', 'ultimate-security'); ?></li>
            <?php endif; ?>
            <?php if (($notification_options['weekly_summary'] ?? '1') === '1'): ?>
                <li><?php esc_html_e('Weekly security summary', 'ultimate-security'); ?></li>
            <?php endif; ?>
        </ul>

        <p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=ultimate-security#/settings/threat/brute-force/login-notifications')); ?>" class="btn btn-primary"><?php esc_html_e('Manage Settings', 'ultimate-security'); ?></a>
        </p>
        <?php
        $content = ob_get_clean();

        return wp_mail(
            $email,
            $subject,
            self::get_email_template($content, __('Test Notification', 'ultimate-security')),
            self::get_headers()
        );
    }
}
