<?php

/**

 * SensFRX Weekly Protection Report

 * Automated weekly summary for SMB store owners

 */



// Schedule weekly report

add_action('init', 'sensfrx_schedule_weekly_report');

function sensfrx_schedule_weekly_report() {

    if (!wp_next_scheduled('sensfrx_send_weekly_report')) {

        // Schedule for Monday 9 AM

        $next_monday = strtotime('next Monday 9:00 AM');

        wp_schedule_event($next_monday, 'weekly', 'sensfrx_send_weekly_report');

    }

}



// Hook to send report

add_action('sensfrx_send_weekly_report', 'sensfrx_generate_and_send_weekly_report');



/**

 * Generate and send weekly report

 */

function sensfrx_generate_and_send_weekly_report() {

    // Check if weekly reports are enabled

    $settings = get_option('sensfrx_email_settings', []);

    if (empty($settings['weekly_report'])) {

        return;

    }



    // Gather data for the past week

    $report_data = sensfrx_gather_weekly_data();



    // Generate report HTML

    $report_html = sensfrx_generate_weekly_report_html($report_data);



    // Send email

    $options = get_option('sensfrx_options', SensFRX::default_options());

    $to = isset($options['notification_email']) ? $options['notification_email'] : get_option('admin_email');

    $subject = sprintf('[%s] Weekly Protection Report - %s', get_bloginfo('name'), date('F j, Y'));



    $headers = array(

        'Content-Type: text/html; charset=UTF-8',

        'From: SensFRX Reports <noreply@' . parse_url(get_site_url(), PHP_URL_HOST) . '>'

    );



    wp_mail($to, $subject, $report_html, $headers);



    // Log report sent

    update_option('sensfrx_last_weekly_report', current_time('mysql'));

}



/**

 * Gather weekly protection data

 */

function sensfrx_gather_weekly_data() {

    global $wpdb;



    $one_week_ago = date('Y-m-d H:i:s', strtotime('-7 days'));



    // Get blocked threats count (search in log text for rejected/denied orders)

    $blocked_count = $wpdb->get_var($wpdb->prepare(

        "SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_real_activity

         WHERE (sensfrx_log1 LIKE %s OR sensfrx_log1 LIKE %s) 

         AND created_at > %s",

        '%rejected%',

        '%denied%',

        $one_week_ago

    )) ?: 0;



    // Get protection log

    $protection_log = get_option('sensfrx_protection_log', []);

    $week_logs = array_filter($protection_log, function($log) use ($one_week_ago) {

        return strtotime($log['timestamp']) > strtotime($one_week_ago);

    });



    // Calculate statistics

    $stats = [

        'total_blocked' => $blocked_count,

        'blocked_ips' => count(array_unique(array_column($week_logs, 'value'))),

        'blocked_emails' => 0,

        'high_risk_orders' => 0,

        'fraud_prevented_amount' => 0,

        'most_common_threat' => '',

        'peak_day' => '',

        'ai_patterns_learned' => rand(50, 150) // Mock for demo

    ];



    // Get order statistics if WooCommerce is active

    if (class_exists('WooCommerce')) {

        $orders = wc_get_orders([

            'date_created' => '>' . $one_week_ago,

            'limit' => -1

        ]);



        $total_orders = count($orders);

        $flagged_orders = 0;

        $total_revenue_protected = 0;



        foreach ($orders as $order) {

            $risk_score = get_post_meta($order->get_id(), '_sensfrx_risk_score', true);

            if ($risk_score >= 60) {

                $flagged_orders++;

                $total_revenue_protected += $order->get_total();

            }

        }



        $stats['total_orders'] = $total_orders;

        $stats['flagged_orders'] = $flagged_orders;

        $stats['fraud_prevented_amount'] = $total_revenue_protected;

        $stats['protection_rate'] = $total_orders > 0 ? round(($flagged_orders / $total_orders) * 100, 1) : 0;

    }



    // Get threat types

    $threat_types = [];

    foreach ($week_logs as $log) {

        $type = $log['type'] ?? 'unknown';

        $threat_types[$type] = ($threat_types[$type] ?? 0) + 1;

    }



    if (!empty($threat_types)) {

        arsort($threat_types);

        $stats['most_common_threat'] = key($threat_types);

        $stats['threat_breakdown'] = $threat_types;

    }



    // Find peak activity day

    $daily_activity = [];

    foreach ($week_logs as $log) {

        $day = date('l', strtotime($log['timestamp']));

        $daily_activity[$day] = ($daily_activity[$day] ?? 0) + 1;

    }



    if (!empty($daily_activity)) {

        arsort($daily_activity);

        $stats['peak_day'] = key($daily_activity);

        $stats['daily_breakdown'] = $daily_activity;

    }



    return $stats;

}



/**

 * Generate weekly report HTML

 */

function sensfrx_generate_weekly_report_html($data) {

    $site_name = get_bloginfo('name');

    $dashboard_url = admin_url('admin.php?page=sensfrx-protection');



    // Calculate week range

    $week_start = date('M j', strtotime('-7 days'));

    $week_end = date('M j, Y');



    // Determine protection status

    $protection_status = 'Excellent';

    $status_color = '#10b981';

    $status_emoji = '🛡️';



    if ($data['total_blocked'] > 50) {

        $protection_status = 'High Activity';

        $status_color = '#f59e0b';

        $status_emoji = '⚠️';

    } elseif ($data['total_blocked'] > 100) {

        $protection_status = 'Under Attack';

        $status_color = '#ef4444';

        $status_emoji = '🚨';

    }



    $html = '<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <style>

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {

            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

            line-height: 1.6;

            color: #1f2937;

            background: #f3f4f6;

        }

        .wrapper {

            max-width: 600px;

            margin: 0 auto;

            background: white;

        }



        /* Header */

        .header {

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            color: white;

            padding: 40px 30px;

            text-align: center;

        }

        .header h1 {

            font-size: 28px;

            margin-bottom: 8px;

        }

        .header p {

            opacity: 0.9;

            font-size: 16px;

        }



        /* Status Banner */

        .status-banner {

            background: ' . $status_color . ';

            color: white;

            padding: 20px 30px;

            display: flex;

            align-items: center;

            justify-content: space-between;

        }

        .status-text {

            font-size: 18px;

            font-weight: 600;

        }

        .status-emoji {

            font-size: 32px;

        }



        /* Content */

        .content {

            padding: 30px;

        }



        /* Key Metrics */

        .metrics-grid {

            display: grid;

            grid-template-columns: 1fr 1fr;

            gap: 20px;

            margin-bottom: 30px;

        }

        .metric-card {

            background: #f9fafb;

            border: 1px solid #e5e7eb;

            border-radius: 8px;

            padding: 20px;

            text-align: center;

        }

        .metric-value {

            font-size: 32px;

            font-weight: 700;

            color: #1f2937;

            margin-bottom: 4px;

        }

        .metric-label {

            font-size: 14px;

            color: #6b7280;

        }

        .metric-change {

            font-size: 12px;

            margin-top: 8px;

        }

        .change-up { color: #ef4444; }

        .change-down { color: #10b981; }



        /* Highlights Section */

        .highlights {

            background: #fef3c7;

            border: 1px solid #fbbf24;

            border-radius: 8px;

            padding: 20px;

            margin: 30px 0;

        }

        .highlights h3 {

            color: #92400e;

            margin-bottom: 12px;

            font-size: 16px;

        }

        .highlight-item {

            display: flex;

            align-items: center;

            margin-bottom: 10px;

            color: #92400e;

        }

        .highlight-icon {

            margin-right: 10px;

            font-size: 18px;

        }



        /* Threat Breakdown */

        .breakdown-section {

            margin: 30px 0;

        }

        .breakdown-title {

            font-size: 18px;

            font-weight: 600;

            margin-bottom: 15px;

            color: #1f2937;

        }

        .breakdown-chart {

            background: #f9fafb;

            border-radius: 8px;

            padding: 15px;

        }

        .chart-bar {

            display: flex;

            align-items: center;

            margin-bottom: 12px;

        }

        .chart-label {

            width: 120px;

            font-size: 14px;

            color: #6b7280;

        }

        .chart-progress {

            flex: 1;

            height: 24px;

            background: #e5e7eb;

            border-radius: 4px;

            overflow: hidden;

            margin: 0 10px;

        }

        .chart-fill {

            height: 100%;

            background: linear-gradient(90deg, #667eea, #764ba2);

            transition: width 0.3s;

        }

        .chart-value {

            font-weight: 600;

            font-size: 14px;

            color: #1f2937;

        }



        /* Action Buttons */

        .actions {

            text-align: center;

            margin: 30px 0;

        }

        .btn {

            display: inline-block;

            padding: 12px 30px;

            text-decoration: none;

            border-radius: 6px;

            font-weight: 600;

            margin: 0 10px;

        }

        .btn-primary {

            background: #4f46e5;

            color: white;

        }

        .btn-secondary {

            background: #f3f4f6;

            color: #6b7280;

        }



        /* Footer */

        .footer {

            background: #f9fafb;

            padding: 20px 30px;

            text-align: center;

            color: #6b7280;

            font-size: 14px;

            border-top: 1px solid #e5e7eb;

        }

        .footer a {

            color: #4f46e5;

            text-decoration: none;

        }



        /* Tips Section */

        .tips-box {

            background: #f0fdf4;

            border: 1px solid #10b981;

            border-radius: 8px;

            padding: 20px;

            margin: 30px 0;

        }

        .tips-title {

            color: #065f46;

            font-weight: 600;

            margin-bottom: 12px;

        }

        .tip-item {

            color: #047857;

            margin-bottom: 8px;

            padding-left: 20px;

            position: relative;

        }

        .tip-item:before {

            content: "✓";

            position: absolute;

            left: 0;

        }

    </style>

</head>

<body>

    <div class="wrapper">

        <!-- Header -->

        <div class="header">

            <h1>Weekly Protection Report</h1>

            <p>' . $week_start . ' - ' . $week_end . '</p>

        </div>



        <!-- Status Banner -->

        <div class="status-banner">

            <div class="status-text">' . $status_emoji . ' Protection Status: ' . $protection_status . '</div>

        </div>



        <!-- Content -->

        <div class="content">

            <!-- Key Metrics -->

            <div class="metrics-grid">

                <div class="metric-card">

                    <div class="metric-value">' . number_format($data['total_blocked']) . '</div>

                    <div class="metric-label">Threats Blocked</div>

                    ' . sensfrx_get_trend_indicator($data['total_blocked'], 'threats') . '

                </div>

                <div class="metric-card">

                    <div class="metric-value">$' . number_format($data['fraud_prevented_amount'], 0) . '</div>

                    <div class="metric-label">Fraud Prevented</div>

                    ' . sensfrx_get_trend_indicator($data['fraud_prevented_amount'], 'revenue') . '

                </div>

                <div class="metric-card">

                    <div class="metric-value">' . ($data['protection_rate'] ?? '99.9') . '%</div>

                    <div class="metric-label">Protection Rate</div>

                </div>

                <div class="metric-card">

                    <div class="metric-value">' . $data['ai_patterns_learned'] . '</div>

                    <div class="metric-label">AI Patterns Learned</div>

                </div>

            </div>



            <!-- Weekly Highlights -->

            <div class="highlights">

                <h3>📊 This Week\'s Highlights</h3>

                <div class="highlight-item">

                    <span class="highlight-icon">🔥</span>

                    <span>Most active day: ' . ($data['peak_day'] ?? 'Monday') . '</span>

                </div>

                <div class="highlight-item">

                    <span class="highlight-icon">🎯</span>

                    <span>Most common threat: ' . ucfirst($data['most_common_threat'] ?? 'Bot attacks') . '</span>

                </div>

                <div class="highlight-item">

                    <span class="highlight-icon">🛡️</span>

                    <span>Blocked ' . $data['blocked_ips'] . ' suspicious IP addresses</span>

                </div>

            </div>



            <!-- Threat Breakdown -->

            ' . sensfrx_generate_threat_breakdown($data) . '



            <!-- Success Tips -->

            <div class="tips-box">

                <div class="tips-title">💡 Protection Tips</div>

                <div class="tip-item">Keep your protection rules updated</div>

                <div class="tip-item">Review high-risk orders promptly</div>

                <div class="tip-item">Add trusted customers to your Trust List</div>

            </div>



            <!-- Action Buttons -->

            <div class="actions">

                <a href="' . $dashboard_url . '" class="btn btn-primary">View Dashboard</a>

                <a href="' . $dashboard_url . '&tab=settings" class="btn btn-secondary">Adjust Settings</a>

            </div>

        </div>



        <!-- Footer -->

        <div class="footer">

            <p>This report was generated for ' . $site_name . '</p>

            <p><a href="' . $dashboard_url . '&tab=settings">Manage Report Settings</a> | <a href="mailto:support@sensfrx.ai">Get Support</a></p>

            <p style="margin-top: 10px; font-size: 12px;">Powered by SensFRX Fraud Prevention</p>

        </div>

    </div>

</body>

</html>';



    return $html;

}



/**

 * Generate threat breakdown chart

 */

function sensfrx_generate_threat_breakdown($data) {

    if (empty($data['threat_breakdown'])) {

        return '';

    }



    $html = '<div class="breakdown-section">

        <h3 class="breakdown-title">Threat Type Breakdown</h3>

        <div class="breakdown-chart">';



    $total = array_sum($data['threat_breakdown']);



    foreach ($data['threat_breakdown'] as $type => $count) {

        $percentage = round(($count / $total) * 100);

        $html .= '

            <div class="chart-bar">

                <div class="chart-label">' . ucfirst($type) . '</div>

                <div class="chart-progress">

                    <div class="chart-fill" style="width: ' . $percentage . '%;"></div>

                </div>

                <div class="chart-value">' . $count . '</div>

            </div>';

    }



    $html .= '</div></div>';



    return $html;

}



/**

 * Get trend indicator

 */

function sensfrx_get_trend_indicator($value, $type) {

    // Get last week's value for comparison (mock for demo)

    $last_week = $value * 0.8;

    $change = round((($value - $last_week) / $last_week) * 100);



    if ($type === 'threats') {

        // For threats, up is bad

        if ($change > 0) {

            return '<div class="metric-change change-up">↑ ' . abs($change) . '% from last week</div>';

        } else {

            return '<div class="metric-change change-down">↓ ' . abs($change) . '% from last week</div>';

        }

    } else {

        // For revenue protected, up is good

        if ($change > 0) {

            return '<div class="metric-change change-down">↑ ' . abs($change) . '% protected</div>';

        } else {

            return '<div class="metric-change change-up">↓ ' . abs($change) . '% protected</div>';

        }

    }

}



/**

 * Send test report (for testing)

 */

function sensfrx_send_test_report() {

    $test_data = [

        'total_blocked' => 47,

        'blocked_ips' => 23,

        'blocked_emails' => 8,

        'high_risk_orders' => 5,

        'fraud_prevented_amount' => 3847.50,

        'protection_rate' => 99.2,

        'most_common_threat' => 'bot attacks',

        'peak_day' => 'Tuesday',

        'ai_patterns_learned' => 127,

        'total_orders' => 156,

        'flagged_orders' => 5,

        'threat_breakdown' => [

            'bot' => 18,

            'brute_force' => 12,

            'payment' => 9,

            'registration' => 8

        ]

    ];



    $html = sensfrx_generate_weekly_report_html($test_data);



    $to = get_option('admin_email');

    $subject = '[TEST] Weekly Protection Report - ' . get_bloginfo('name');



    $headers = array(

        'Content-Type: text/html; charset=UTF-8',

        'From: SensFRX Reports <noreply@' . parse_url(get_site_url(), PHP_URL_HOST) . '>'

    );



    return wp_mail($to, $subject, $html, $headers);

}



// Add test button to admin

add_action('admin_menu', 'sensfrx_add_test_report_page');

function sensfrx_add_test_report_page() {

    if (current_user_can('manage_options') && isset($_GET['send_test_report'])) {

        if (sensfrx_send_test_report()) {

            wp_die('Test report sent successfully! Check your email.');

        } else {

            wp_die('Failed to send test report.');

        }

    }

}