<?php

/**

 * SensFRX Email Notifications for SMB

 * Sends alerts when fraud is blocked

 */



// Hook into fraud detection events

add_action('sensfrx_fraud_blocked', 'sensfrx_send_fraud_blocked_email', 10, 2);

add_action('sensfrx_high_risk_detected', 'sensfrx_send_high_risk_alert', 10, 2);

add_action('sensfrx_review_required', 'sensfrx_send_review_notification', 10, 2);



/**

 * Send email when fraud is blocked

 */

function sensfrx_send_fraud_blocked_email($fraud_data, $action_taken) {

    // Check if email notifications are enabled

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

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

        return;

    }



    // Get admin email

    $to = get_option('admin_email');

    $site_name = get_bloginfo('name');



    // Email subject

    $subject = sprintf('[%s] Fraud Blocked: %s', $site_name, $fraud_data['type']);



    // Build email content

    $message = sensfrx_get_blocked_email_template($fraud_data, $action_taken, $site_name);



    // Email headers

    $headers = array(

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

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

    );



    // Send email

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



    // Log email sent

    sensfrx_log_notification('fraud_blocked', $fraud_data);

}



/**

 * Send high risk alert

 */

function sensfrx_send_high_risk_alert($order_data, $risk_score) {

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

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

        return;

    }



    $to = get_option('admin_email');

    $site_name = get_bloginfo('name');



    $subject = sprintf('[%s] ⚠️ High Risk Order Detected - Score: %d', $site_name, $risk_score);



    $message = sensfrx_get_high_risk_email_template($order_data, $risk_score, $site_name);



    $headers = array(

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

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

        'X-Priority: 1'

    );



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

}



/**

 * Send review required notification

 */

function sensfrx_send_review_notification($order_id, $reason) {

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

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

        return;

    }



    $to = get_option('admin_email');

    $site_name = get_bloginfo('name');



    $subject = sprintf('[%s] Order #%s Requires Review', $site_name, $order_id);



    $message = sensfrx_get_review_email_template($order_id, $reason, $site_name);



    $headers = array(

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

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

    );



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

}



/**

 * Email template for blocked fraud

 */

function sensfrx_get_blocked_email_template($fraud_data, $action_taken, $site_name) {

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



    $html = '<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <style>

        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: #333; }

        .container { max-width: 600px; margin: 0 auto; padding: 20px; }

        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 8px 8px 0 0; text-align: center; }

        .content { background: white; padding: 30px; border: 1px solid #e5e7eb; border-radius: 0 0 8px 8px; }

        .alert-box { background: #fee2e2; border-left: 4px solid #ef4444; padding: 15px; margin: 20px 0; border-radius: 4px; }

        .details-table { width: 100%; border-collapse: collapse; margin: 20px 0; }

        .details-table td { padding: 10px; border-bottom: 1px solid #e5e7eb; }

        .details-table td:first-child { font-weight: 600; color: #6b7280; width: 40%; }

        .action-btn { display: inline-block; background: #4f46e5; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin-top: 20px; }

        .footer { text-align: center; margin-top: 30px; color: #6b7280; font-size: 14px; }

    </style>

</head>

<body>

    <div class="container">

        <div class="header">

            <h1 style="margin: 0; font-size: 24px;">🛡️ Fraud Blocked</h1>

            <p style="margin: 10px 0 0; opacity: 0.9;">SensFRX Protection prevented a fraudulent attempt</p>

        </div>



        <div class="content">

            <div class="alert-box">

                <strong>Action Taken:</strong> ' . esc_html($action_taken) . '

            </div>



            <h2 style="color: #1f2937; font-size: 18px;">Threat Details</h2>



            <table class="details-table">

                <tr>

                    <td>Type:</td>

                    <td>' . esc_html($fraud_data['type']) . '</td>

                </tr>

                <tr>

                    <td>IP Address:</td>

                    <td>' . esc_html($fraud_data['ip_address']) . '</td>

                </tr>

                <tr>

                    <td>Email:</td>

                    <td>' . esc_html($fraud_data['email'] ?? 'N/A') . '</td>

                </tr>

                <tr>

                    <td>Risk Score:</td>

                    <td><span style="color: #ef4444; font-weight: 600;">' . esc_html($fraud_data['risk_score']) . '/100</span></td>

                </tr>

                <tr>

                    <td>Time:</td>

                    <td>' . current_time('F j, Y g:i a') . '</td>

                </tr>

                <tr>

                    <td>Location:</td>

                    <td>' . esc_html($fraud_data['location'] ?? 'Unknown') . '</td>

                </tr>

            </table>



            <div style="background: #f9fafb; padding: 20px; border-radius: 6px; margin: 20px 0;">

                <h3 style="margin: 0 0 10px; color: #1f2937; font-size: 16px;">What happened?</h3>

                <p style="margin: 0; color: #6b7280;">

                    SensFRX detected and blocked a ' . esc_html(strtolower($fraud_data['type'])) . ' attempt

                    from IP address ' . esc_html($fraud_data['ip_address']) . '.

                    The attempt was automatically blocked based on your protection settings.

                </p>

            </div>



            <center>

                <a href="' . esc_url($admin_url) . '" class="action-btn">View Protection Dashboard</a>

            </center>



            <div class="footer">

                <p>This email was sent by SensFRX Fraud Prevention for ' . esc_html($site_name) . '</p>

                <p><a href="' . esc_url($admin_url . '&tab=settings') . '" style="color: #4f46e5;">Manage notification settings</a></p>

            </div>

        </div>

    </div>

</body>

</html>';



    return $html;

}



/**

 * Email template for high risk alerts

 */

function sensfrx_get_high_risk_email_template($order_data, $risk_score, $site_name) {

    $review_url = admin_url('admin.php?page=sensfrx-order-review&order_id=' . $order_data['order_id']);



    $risk_color = $risk_score >= 70 ? '#ef4444' : '#f59e0b';

    $risk_level = $risk_score >= 70 ? 'HIGH RISK' : 'MEDIUM RISK';



    $html = '<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <style>

        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: #333; }

        .container { max-width: 600px; margin: 0 auto; padding: 20px; }

        .header { background: ' . $risk_color . '; color: white; padding: 30px; border-radius: 8px 8px 0 0; text-align: center; }

        .content { background: white; padding: 30px; border: 1px solid #e5e7eb; border-radius: 0 0 8px 8px; }

        .risk-badge { display: inline-block; background: ' . $risk_color . '; color: white; padding: 6px 12px; border-radius: 20px; font-weight: 600; font-size: 14px; }

        .order-summary { background: #f9fafb; padding: 20px; border-radius: 6px; margin: 20px 0; }

        .details-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 20px 0; }

        .detail-item { padding: 10px; background: white; border: 1px solid #e5e7eb; border-radius: 4px; }

        .detail-label { font-size: 13px; color: #6b7280; margin-bottom: 4px; }

        .detail-value { font-weight: 600; color: #1f2937; }

        .action-buttons { text-align: center; margin-top: 30px; }

        .btn { display: inline-block; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 0 10px; font-weight: 500; }

        .btn-review { background: ' . $risk_color . '; color: white; }

        .btn-dashboard { background: #f3f4f6; color: #6b7280; }

    </style>

</head>

<body>

    <div class="container">

        <div class="header">

            <h1 style="margin: 0; font-size: 24px;">⚠️ High Risk Order Detected</h1>

            <p style="margin: 10px 0 0; opacity: 0.9;">Immediate review recommended</p>

        </div>



        <div class="content">

            <div style="text-align: center; margin: 20px 0;">

                <span class="risk-badge">' . $risk_level . ' - Score: ' . $risk_score . '/100</span>

            </div>



            <div class="order-summary">

                <h3 style="margin: 0 0 15px; color: #1f2937;">Order #' . esc_html($order_data['order_id']) . '</h3>

                <div class="details-grid">

                    <div class="detail-item">

                        <div class="detail-label">Customer</div>

                        <div class="detail-value">' . esc_html($order_data['customer_email']) . '</div>

                    </div>

                    <div class="detail-item">

                        <div class="detail-label">Amount</div>

                        <div class="detail-value">$' . number_format($order_data['amount'], 2) . '</div>

                    </div>

                    <div class="detail-item">

                        <div class="detail-label">IP Address</div>

                        <div class="detail-value">' . esc_html($order_data['ip_address']) . '</div>

                    </div>

                    <div class="detail-item">

                        <div class="detail-label">Location</div>

                        <div class="detail-value">' . esc_html($order_data['location'] ?? 'Unknown') . '</div>

                    </div>

                </div>

            </div>



            <h3 style="color: #1f2937; font-size: 16px;">Risk Factors Detected:</h3>

            <ul style="color: #6b7280;">

                ' . sensfrx_format_risk_factors($order_data['risk_factors'] ?? []) . '

            </ul>



            <div class="action-buttons">

                <a href="' . esc_url($review_url) . '" class="btn btn-review">Review Order</a>

                <a href="' . admin_url('admin.php?page=sensfrx-protection') . '" class="btn btn-dashboard">Dashboard</a>

            </div>

        </div>

    </div>

</body>

</html>';



    return $html;

}



/**

 * Format risk factors for email

 */

function sensfrx_format_risk_factors($factors) {

    if (empty($factors)) {

        return '<li>Multiple risk indicators detected</li>';

    }



    $html = '';

    foreach ($factors as $factor) {

        $html .= '<li>' . esc_html($factor) . '</li>';

    }

    return $html;

}



/**

 * Log notification sent

 */

function sensfrx_log_notification($type, $data) {

    $log = get_option('sensfrx_notification_log', []);

    $log[] = [

        'type' => $type,

        'data' => $data,

        'timestamp' => current_time('mysql'),

        'sent_to' => get_option('admin_email')

    ];



    // Keep only last 50 entries

    if (count($log) > 50) {

        $log = array_slice($log, -50);

    }



    update_option('sensfrx_notification_log', $log);

}



/**

 * Settings page for email notifications

 */

function sensfrx_email_settings_page() {

    if (isset($_POST['save_settings'])) {

        $settings = [

            'email_alerts' => !empty($_POST['email_alerts']),

            'high_risk_alerts' => !empty($_POST['high_risk_alerts']),

            'review_notifications' => !empty($_POST['review_notifications']),

            'daily_summary' => !empty($_POST['daily_summary']),

            'weekly_report' => !empty($_POST['weekly_report']),

            'notification_email' => sanitize_email($_POST['notification_email'] ?? get_option('admin_email'))

        ];



        update_option('sensfrx_email_settings', $settings);

        echo '<div class="notice notice-success"><p>Settings saved successfully!</p></div>';

    }



    $settings = get_option('sensfrx_email_settings', [

        'email_alerts' => true,

        'high_risk_alerts' => true,

        'review_notifications' => true,

        'daily_summary' => false,

        'weekly_report' => true,

        'notification_email' => get_option('admin_email')

    ]);

    ?>



    <div class="wrap">

        <h1>Email Notification Settings</h1>



        <form method="post">

            <table class="form-table">

                <tr>

                    <th scope="row">Notification Email</th>

                    <td>

                        <input type="email" name="notification_email" value="<?php echo esc_attr($settings['notification_email']); ?>" class="regular-text">

                        <p class="description">Where to send fraud alerts</p>

                    </td>

                </tr>



                <tr>

                    <th scope="row">Real-time Alerts</th>

                    <td>

                        <label>

                            <input type="checkbox" name="email_alerts" <?php checked($settings['email_alerts']); ?>>

                            Send email when fraud is blocked

                        </label><br>



                        <label>

                            <input type="checkbox" name="high_risk_alerts" <?php checked($settings['high_risk_alerts']); ?>>

                            Alert for high-risk orders (score 70+)

                        </label><br>



                        <label>

                            <input type="checkbox" name="review_notifications" <?php checked($settings['review_notifications']); ?>>

                            Notify when orders need review

                        </label>

                    </td>

                </tr>



                <tr>

                    <th scope="row">Summary Reports</th>

                    <td>

                        <label>

                            <input type="checkbox" name="daily_summary" <?php checked($settings['daily_summary']); ?>>

                            Daily summary (sent at 9 AM)

                        </label><br>



                        <label>

                            <input type="checkbox" name="weekly_report" <?php checked($settings['weekly_report']); ?>>

                            Weekly protection report (sent Monday mornings)

                        </label>

                    </td>

                </tr>

            </table>



            <?php submit_button('Save Settings'); ?>

        </form>



        <h2>Recent Notifications</h2>

        <?php

        $log = get_option('sensfrx_notification_log', []);

        if (empty($log)) {

            echo '<p>No notifications sent yet.</p>';

        } else {

            echo '<table class="wp-list-table widefat fixed striped">';

            echo '<thead><tr><th>Type</th><th>Details</th><th>Sent</th></tr></thead>';

            echo '<tbody>';

            foreach (array_reverse(array_slice($log, -10)) as $entry) {

                echo '<tr>';

                echo '<td>' . esc_html($entry['type']) . '</td>';

                echo '<td>' . esc_html(json_encode($entry['data'])) . '</td>';

                echo '<td>' . esc_html($entry['timestamp']) . '</td>';

                echo '</tr>';

            }

            echo '</tbody></table>';

        }

        ?>

    </div>

    <?php

}