<?php
if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

/**
 * FormShield Email Notifications Class
 * 
 * Handles all email notification functionality including:
 * - Saving email settings
 * - Sending notifications for attacks
 * - Sending notifications for new forms
 * - Frequency-based digest emails
 * 
 * @since 1.0.3-beta
 */
class FormShieldEmailNotifications {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('wp_ajax_formshield_save_email_settings', array($this, 'save_email_settings'));
        add_action('wp_ajax_formsh_test_email', array($this, 'test_email'));
        add_action('formshield_attack_detected', array($this, 'notify_attack'), 10, 2);
        add_action('formshield_new_form_detected', array($this, 'notify_new_form'), 10, 1);
        
        // Schedule periodic reports
        add_action('wp', array($this, 'schedule_periodic_reports'));
        add_action('formshield_send_periodic_report', array($this, 'send_periodic_report'));
    }
    
    /**
     * Save email settings via AJAX
     */
    public function save_email_settings() {
        // Check nonce
        if (!check_ajax_referer('formshield_email_settings', 'nonce', false)) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Get and validate data
        $admin_email = isset($_POST['admin_email']) ? sanitize_email(wp_unslash($_POST['admin_email'])) : '';
        $notification_frequency = isset($_POST['notification_frequency']) ? sanitize_text_field(wp_unslash($_POST['notification_frequency'])) : '';
        $email_attacks = isset($_POST['email_attacks']) ? (bool) $_POST['email_attacks'] : false;
        $email_forms = isset($_POST['email_forms']) ? (bool) $_POST['email_forms'] : false;
        $periodic_reports = isset($_POST['periodic_reports']) ? (bool) $_POST['periodic_reports'] : false;
        $report_frequency = isset($_POST['report_frequency']) ? sanitize_text_field(wp_unslash($_POST['report_frequency'])) : '';
        
        // Validate email
        if (!is_email($admin_email)) {
            wp_send_json_error('Invalid email address');
            return;
        }
        
        // Validate frequency
        $valid_frequencies = array('immediate', 'hourly', 'daily', 'weekly');
        if (!in_array($notification_frequency, $valid_frequencies)) {
            wp_send_json_error('Invalid notification frequency');
            return;
        }
        
        // Validate report frequency
        $valid_report_frequencies = array('15_days', '30_days');
        if (!in_array($report_frequency, $valid_report_frequencies)) {
            wp_send_json_error('Invalid report frequency');
            return;
        }
        
        // Save settings
        $options = form_shield()->get_options();
        $options['settings']['admin_email'] = $admin_email;
        $options['settings']['notification_frequency'] = $notification_frequency;
        $options['settings']['email_attacks'] = $email_attacks;
        $options['settings']['email_forms'] = $email_forms;
        $options['settings']['periodic_reports'] = $periodic_reports;
        $options['settings']['report_frequency'] = $report_frequency;
        
        form_shield()->update_options($options);
        
        wp_send_json_success(array(
            'message' => 'Email settings saved successfully',
            'settings' => $options['settings']
        ));
    }
    
    /**
     * Send test email
     */
    public function test_email() {
        // Check nonce
        if (!check_ajax_referer('formshield_email_settings', 'nonce', false)) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        $admin_email = formshield_get_post_email('admin_email');
        
        if (!is_email($admin_email)) {
            wp_send_json_error('Invalid email address');
            return;
        }
        
        $subject = 'FormShield Test Email';
        $message = $this->get_test_email_content();
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        $sent = wp_mail($admin_email, $subject, $message, $headers);
        
        if ($sent) {
            wp_send_json_success('Test email sent successfully');
        } else {
            wp_send_json_error('Failed to send test email');
        }
    }
    
    /**
     * Notify about detected attack
     */
    public function notify_attack($form_id, $attack_data) {
        $options = form_shield()->get_options();
        
        // Check if attack notifications are enabled
        if (empty($options['settings']['email_attacks'])) {
            return;
        }
        
        $admin_email = $options['settings']['admin_email'] ?? get_option('admin_email');
        $frequency = $options['settings']['notification_frequency'] ?? 'immediate';
        
        if ($frequency === 'immediate') {
            $this->send_attack_notification($admin_email, $form_id, $attack_data);
        } else {
            $this->queue_notification('attack', $admin_email, $form_id, $attack_data);
        }
    }
    
    /**
     * Notify about new form detection
     */
    public function notify_new_form($form_data) {
        $options = form_shield()->get_options();
        
        // Check if form notifications are enabled
        if (empty($options['settings']['email_forms'])) {
            return;
        }
        
        $admin_email = $options['settings']['admin_email'] ?? get_option('admin_email');
        $frequency = $options['settings']['notification_frequency'] ?? 'immediate';
        
        if ($frequency === 'immediate') {
            $this->send_new_form_notification($admin_email, $form_data);
        } else {
            $this->queue_notification('new_form', $admin_email, $form_data);
        }
    }
    
    /**
     * Send immediate attack notification
     */
    private function send_attack_notification($admin_email, $form_id, $attack_data) {
        $subject = sprintf('[FormShield] Attack Detected on Form: %s', $form_id);
        $message = $this->get_attack_email_content($form_id, $attack_data);
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        wp_mail($admin_email, $subject, $message, $headers);
    }
    
    /**
     * Send immediate new form notification
     */
    private function send_new_form_notification($admin_email, $form_data) {
        $subject = '[FormShield] New Form Detected';
        $message = $this->get_new_form_email_content($form_data);
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        wp_mail($admin_email, $subject, $message, $headers);
    }
    
    /**
     * Queue notification for later (digest)
     */
    private function queue_notification($type, $admin_email, $data1, $data2 = null) {
        $queue = get_option('formshield_email_queue', array());
        
        $queue[] = array(
            'type' => $type,
            'admin_email' => $admin_email,
            'data1' => $data1,
            'data2' => $data2,
            'timestamp' => current_time('mysql')
        );
        
        update_option('formshield_email_queue', $queue);
    }
    
    /**
     * Get test email content
     */
    private function get_test_email_content() {
        $site_name = get_bloginfo('name');
        $site_url = get_site_url();
        
        return "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
            <h2 style='color: #2271b1;'>FormShield Test Email</h2>
            <p>This is a test email from <strong>{$site_name}</strong> to verify that email notifications are working correctly.</p>
            <p><strong>Site URL:</strong> <a href='{$site_url}'>{$site_url}</a></p>
            <p><strong>Test Time:</strong> " . current_time('mysql') . "</p>
            <hr style='border: 1px solid #eee; margin: 20px 0;'>
            <p style='color: #666; font-size: 12px;'>If you received this email, your FormShield email notifications are configured correctly.</p>
        </div>
        ";
    }
    
    /**
     * Get attack notification email content
     */
    private function get_attack_email_content($form_id, $attack_data) {
        $site_name = get_bloginfo('name');
        $site_url = get_site_url();
        $ip_address = formshield_get_validated_ip('Unknown');
        
        return "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
            <h2 style='color: #e74c3c;'>🚨 Attack Detected!</h2>
            <p>A potential attack has been detected on your website <strong>{$site_name}</strong>.</p>
            
            <h3 style='color: #333;'>Attack Details:</h3>
            <ul>
                <li><strong>Form ID:</strong> {$form_id}</li>
                <li><strong>IP Address:</strong> {$ip_address}</li>
                <li><strong>Time:</strong> " . current_time('mysql') . "</li>
                <li><strong>Attack Type:</strong> " . esc_html($attack_data['type'] ?? 'Unknown') . "</li>
            </ul>
            
            <p><strong>Site URL:</strong> <a href='{$site_url}'>{$site_url}</a></p>
            
            <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0;'>
                <p style='margin: 0; color: #666;'><strong>Note:</strong> FormShield has automatically blocked this attack attempt.</p>
            </div>
        </div>
        ";
    }
    
    /**
     * Get new form notification email content
     */
    private function get_new_form_email_content($form_data) {
        $site_name = get_bloginfo('name');
        $site_url = get_site_url();
        
        return "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
            <h2 style='color: #27ae60;'>🆕 New Form Detected!</h2>
            <p>A new form has been detected on your website <strong>{$site_name}</strong>.</p>
            
            <h3 style='color: #333;'>Form Details:</h3>
            <ul>
                <li><strong>Form ID:</strong> " . esc_html($form_data['id'] ?? 'Unknown') . "</li>
                <li><strong>Form Type:</strong> " . esc_html($form_data['type'] ?? 'Unknown') . "</li>
                <li><strong>Location:</strong> " . esc_html($form_data['location'] ?? 'Unknown') . "</li>
                <li><strong>Detection Time:</strong> " . current_time('mysql') . "</li>
            </ul>
            
            <p><strong>Site URL:</strong> <a href='{$site_url}'>{$site_url}</a></p>
            
            <div style='background: #e8f5e8; padding: 15px; border-radius: 5px; margin: 20px 0;'>
                <p style='margin: 0; color: #27ae60;'><strong>Status:</strong> This form is now protected by FormShield!</p>
            </div>
        </div>
        ";
    }
    
    /**
     * Schedule periodic reports
     */
    public function schedule_periodic_reports() {
        $options = form_shield()->get_options();
        
        // Check if periodic reports are enabled
        if (empty($options['settings']['periodic_reports'])) {
            // Clear any existing scheduled events
            wp_clear_scheduled_hook('formshield_send_periodic_report');
            return;
        }
        
        $report_frequency = $options['settings']['report_frequency'] ?? '30_days';
        
        // Convert frequency to days
        switch ($report_frequency) {
            case '15_days':
                $days = 15;
                break;
            case '30_days':
            default:
                $days = 30;
                break;
        }
        
        // Schedule the event if not already scheduled
        if (!wp_next_scheduled('formshield_send_periodic_report')) {
            wp_schedule_event(time(), 'daily', 'formshield_send_periodic_report');
        }
    }
    
    /**
     * Send periodic report
     */
    public function send_periodic_report() {
        $options = form_shield()->get_options();
        
        // Check if periodic reports are enabled
        if (empty($options['settings']['periodic_reports'])) {
            return;
        }
        
        $admin_email = $options['settings']['admin_email'] ?? get_option('admin_email');
        $report_frequency = $options['settings']['report_frequency'] ?? '30_days';
        
        // Convert frequency to days
        switch ($report_frequency) {
            case '15_days':
                $days = 15;
                break;
            case '30_days':
            default:
                $days = 30;
                break;
        }
        
        // Check if it's time to send the report
        $last_report = get_option('formshield_last_periodic_report', 0);
        $time_since_last = time() - $last_report;
        $report_interval = $days * 24 * 60 * 60; // Convert days to seconds
        
        if ($time_since_last < $report_interval) {
            return; // Not time yet
        }
        
        // Generate and send the report
        $subject = sprintf('[FormShield] %d-Day Security Report', $days);
        $message = $this->get_periodic_report_content($days);
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        $sent = wp_mail($admin_email, $subject, $message, $headers);
        
        if ($sent) {
            // Update last report time
            update_option('formshield_last_periodic_report', time());
        }
    }
    
    /**
     * Get periodic report content
     */
    private function get_periodic_report_content($days) {
        $site_name = get_bloginfo('name');
        $site_url = get_site_url();
        $report_date = current_time('mysql');
        
        // Get statistics for the period
        $stats = $this->get_period_stats($days);
        
        return "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
            <h2 style='color: #2563EB;'>📊 FormShield Security Report</h2>
            <p>Here's your <strong>{$days}-day security report</strong> for <strong>{$site_name}</strong>.</p>
            
            <div style='background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;'>
                <h3 style='color: #333; margin-top: 0;'>📈 Activity Summary</h3>
                <div style='display: grid; grid-template-columns: 1fr 1fr; gap: 15px;'>
                    <div style='text-align: center; padding: 15px; background: white; border-radius: 5px;'>
                        <div style='font-size: 24px; font-weight: bold; color: #e74c3c;'>{$stats['total_attacks']}</div>
                        <div style='color: #666;'>Blocked Attacks</div>
                    </div>
                    <div style='text-align: center; padding: 15px; background: white; border-radius: 5px;'>
                        <div style='font-size: 24px; font-weight: bold; color: #27ae60;'>{$stats['total_forms']}</div>
                        <div style='color: #666;'>Protected Forms</div>
                    </div>
                    <div style='text-align: center; padding: 15px; background: white; border-radius: 5px;'>
                        <div style='font-size: 24px; font-weight: bold; color: #f39c12;'>{$stats['new_forms']}</div>
                        <div style='color: #666;'>New Forms</div>
                    </div>
                    <div style='text-align: center; padding: 15px; background: white; border-radius: 5px;'>
                        <div style='font-size: 24px; font-weight: bold; color: #9b59b6;'>{$stats['legitimate_submissions']}</div>
                        <div style='color: #666;'>Legitimate Submissions</div>
                    </div>
                </div>
            </div>
            
            <div style='background: #e8f5e8; padding: 15px; border-radius: 5px; margin: 20px 0;'>
                <h3 style='color: #27ae60; margin-top: 0;'>🛡️ Protection Status</h3>
                <p style='margin: 0;'>All forms are actively protected by FormShield. Your website is secure!</p>
            </div>
            
            <div style='background: #fff3cd; padding: 15px; border-radius: 5px; margin: 20px 0;'>
                <h3 style='color: #856404; margin-top: 0;'>⚠️ Top Attack Sources</h3>
                <ul style='margin: 0;'>
                    " . $this->get_top_attack_sources($days) . "
                </ul>
            </div>
            
            <p><strong>Site URL:</strong> <a href='{$site_url}'>{$site_url}</a></p>
            <p><strong>Report Generated:</strong> {$report_date}</p>
            
            <hr style='border: 1px solid #eee; margin: 20px 0;'>
            <p style='color: #666; font-size: 12px;'>This report covers the last {$days} days of activity. FormShield continues to protect your forms 24/7.</p>
        </div>
        ";
    }
    
    /**
     * Get period statistics
     */
    private function get_period_stats($days) {
        global $wpdb;
        
        $start_date = gmdate('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        // Get total attacks with caching
        $cache_key = 'formshield_total_attacks_' . md5($start_date);
        $total_attacks = wp_cache_get($cache_key, 'formshield');
        if (false === $total_attacks) {
            // Use WordPress Core API instead of direct database query
            $table_name = $wpdb->prefix . 'formshield_logs';
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- read-only query on internal plugin table
            $total_attacks = (int) $wpdb->get_var(
                $wpdb->prepare(
                    /* phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- safe internal table name */
                    "SELECT COUNT(*) FROM {$table_name} WHERE log_type = %s AND created_at >= %s",
                    'attack',
                    $start_date
                )
            );
            wp_cache_set($cache_key, $total_attacks, 'formshield', 300); // Cache for 5 minutes
        }
        
        // Get total forms
        $options = form_shield()->get_options();
        $total_forms = count($options['formshield_forms'] ?? []);
        
        // Get new forms (this is harder to track, so we'll estimate)
        $new_forms = 0; // Could be enhanced with better tracking
        
        // Get legitimate submissions with caching
        $cache_key_submissions = 'formshield_legitimate_submissions_' . md5($start_date);
        $legitimate_submissions = wp_cache_get($cache_key_submissions, 'formshield');
        if (false === $legitimate_submissions) {
            // Use WordPress Core API instead of direct database query
            $table_name = $wpdb->prefix . 'formshield_logs';
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- read-only query on internal plugin table
            $legitimate_submissions = (int) $wpdb->get_var(
                $wpdb->prepare(
                    /* phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- safe internal table name */
                    "SELECT COUNT(*) FROM {$table_name} WHERE log_type = %s AND created_at >= %s",
                    'submission',
                    $start_date
                )
            );
            wp_cache_set($cache_key_submissions, $legitimate_submissions, 'formshield', 300); // Cache for 5 minutes
        }
        
        return array(
            'total_attacks' => $total_attacks ?: 0,
            'total_forms' => $total_forms,
            'new_forms' => $new_forms,
            'legitimate_submissions' => $legitimate_submissions ?: 0
        );
    }
    
    /**
     * Get top attack sources
     */
    private function get_top_attack_sources($days) {
        global $wpdb;
        
        $start_date = gmdate('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        // Get top attack sources with caching
        $cache_key_sources = 'formshield_top_attack_sources_' . md5($start_date);
        $sources = wp_cache_get($cache_key_sources, 'formshield');
        if (false === $sources) {
            // Use WordPress Core API instead of direct database query
            $table_name = $wpdb->prefix . 'formshield_logs';
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- read-only query on internal plugin table
            $sources = $wpdb->get_results(
                $wpdb->prepare(
                    /* phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- safe internal table name */
                    "SELECT ip_address, COUNT(*) AS attack_count FROM {$table_name} WHERE log_type = %s AND created_at >= %s GROUP BY ip_address ORDER BY attack_count DESC LIMIT 5",
                    'attack',
                    $start_date
                )
            );
            wp_cache_set($cache_key_sources, $sources, 'formshield', 300); // Cache for 5 minutes
        }
        
        if (empty($sources)) {
            return '<li>No attacks detected in this period</li>';
        }
        
        $html = '';
        foreach ($sources as $source) {
            $html .= '<li>' . esc_html($source->ip_address) . ' - ' . $source->attack_count . ' attacks</li>';
        }
        
        return $html;
    }
}

// Initialize the class
FormShieldEmailNotifications::get_instance();
