<?php

/**

 * SensFRX SMB Integration

 * Connects new SMB features with existing email notification system

 */



// Hook into existing email system

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



/**

 * Send fraud blocked notification using existing email templates

 */

function sensfrx_smb_fraud_blocked_notification($fraud_data, $action_taken) {

    // Get existing email options

    $email_options = get_option('sensfrx_policy_options', []);

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



    // Check if notifications are enabled

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

        return;

    }



    // Determine risk level

    $risk_level = 'high'; // Default

    if ($fraud_data['risk_score'] < 40) {

        $risk_level = 'low';

    } elseif ($fraud_data['risk_score'] < 70) {

        $risk_level = 'medium';

    }



    // Get appropriate email template based on risk

    $email_content = '';

    switch ($risk_level) {

        case 'low':

            $email_content = $email_options['sensfrx_allow_payment_email'] ?? '';

            break;

        case 'medium':

            $email_content = $email_options['sensfrx_challenge_payment_email'] ?? '';

            break;

        case 'high':

            $email_content = $email_options['sensfrx_deny_payment_email'] ?? '';

            break;

    }



    // If no custom template, use SMB-friendly default

    if (empty($email_content)) {

        $email_content = sensfrx_get_smb_default_email($risk_level, $fraud_data);

    }



    // Send to admin

    $admin_email = get_option('admin_email');

    $site_name = get_bloginfo('name');



    // Email subject based on risk

    $subjects = [

        'low' => '✅ Safe Order Processed',

        'medium' => '⚠️ Order Needs Review',

        'high' => '🛡️ Fraud Blocked'

    ];



    $subject = sprintf('[%s] %s', $site_name, $subjects[$risk_level]);



    // Process email content

    $email_content = sensfrx_process_email_variables($email_content, $fraud_data);



    // Send email

    $headers = array(

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

        'From: ' . get_bloginfo('name') . ' <' . get_option('woocommerce_email_from_address', 'noreply@' . parse_url(get_site_url(), PHP_URL_HOST)) . '>'

    );



    wp_mail($admin_email, $subject, $email_content, $headers);

}



/**

 * Get SMB-friendly default email template

 */

function sensfrx_get_smb_default_email($risk_level, $fraud_data) {

    $templates = [

        'low' => '<h2>Order Approved</h2>

            <p>Good news! An order was automatically approved as it showed no signs of fraud.</p>

            <p><strong>Customer:</strong> {customer_email}<br>

            <strong>Amount:</strong> ${order_amount}<br>

            <strong>Risk Score:</strong> {risk_score}/100</p>

            <p>No action needed - the order is processing normally.</p>',



        'medium' => '<h2>Order Needs Your Review</h2>

            <p>An order has been flagged for review due to some warning signs.</p>

            <p><strong>Customer:</strong> {customer_email}<br>

            <strong>Amount:</strong> ${order_amount}<br>

            <strong>Risk Score:</strong> {risk_score}/100<br>

            <strong>Reason:</strong> {risk_reason}</p>

            <p><a href="{review_url}" style="background:#f59e0b;color:white;padding:10px 20px;text-decoration:none;border-radius:5px;">Review Order</a></p>',



        'high' => '<h2>Fraud Blocked Successfully</h2>

            <p>We blocked a fraudulent order attempt to protect your store.</p>

            <p><strong>Blocked:</strong> {customer_email}<br>

            <strong>IP Address:</strong> {ip_address}<br>

            <strong>Risk Score:</strong> {risk_score}/100<br>

            <strong>Threat Type:</strong> {threat_type}</p>

            <p>The customer has been notified. No action needed.</p>'

    ];



    return $templates[$risk_level] ?? $templates['high'];

}



/**

 * Process email variables

 */

function sensfrx_process_email_variables($content, $data) {

    $replacements = [

        '{customer_email}' => $data['email'] ?? 'Unknown',

        '{order_amount}' => $data['amount'] ?? '0',

        '{risk_score}' => $data['risk_score'] ?? '0',

        '{risk_reason}' => $data['reason'] ?? 'Multiple risk factors detected',

        '{ip_address}' => $data['ip_address'] ?? 'Unknown',

        '{threat_type}' => $data['type'] ?? 'Suspicious activity',

        '{review_url}' => admin_url('admin.php?page=sensfrx_fpwoo&tab=fraud'),

        '{site_name}' => get_bloginfo('name'),

        '{date}' => current_time('F j, Y'),

        '{time}' => current_time('g:i a')

    ];



    return str_replace(array_keys($replacements), array_values($replacements), $content);

}



/**

 * Add SMB settings to existing email notification page

 */

add_action('sensfrx_email_settings_after', 'sensfrx_add_smb_email_settings');

function sensfrx_add_smb_email_settings() {

    $smb_settings = get_option('sensfrx_email_settings', [

        'email_alerts' => true,

        'high_risk_alerts' => true,

        'weekly_report' => true

    ]);

    ?>



    <!-- SMB Quick Settings -->

    <div class="sensfrx-section" style="margin-top: 30px;">

        <h2 class="sensfrx-section-title">Small Business Settings</h2>

        <p class="sensfrx-section-subtitle">Simplified email preferences for store owners</p>



        <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 20px;">

            <div style="margin-bottom: 20px;">

                <label style="display: flex; align-items: center; gap: 10px;">

                    <input type="checkbox" name="sensfrx_smb[instant_alerts]" value="1"

                           <?php checked($smb_settings['email_alerts'] ?? true); ?>>

                    <span>

                        <strong>Instant Fraud Alerts</strong><br>

                        <span style="color: #6b7280; font-size: 14px;">Get notified immediately when fraud is blocked</span>

                    </span>

                </label>

            </div>



            <div style="margin-bottom: 20px;">

                <label style="display: flex; align-items: center; gap: 10px;">

                    <input type="checkbox" name="sensfrx_smb[high_risk_only]" value="1"

                           <?php checked($smb_settings['high_risk_alerts'] ?? false); ?>>

                    <span>

                        <strong>High Risk Only</strong><br>

                        <span style="color: #6b7280; font-size: 14px;">Only alert me for serious threats (score 70+)</span>

                    </span>

                </label>

            </div>



            <div style="margin-bottom: 20px;">

                <label style="display: flex; align-items: center; gap: 10px;">

                    <input type="checkbox" name="sensfrx_smb[weekly_summary]" value="1"

                           <?php checked($smb_settings['weekly_report'] ?? true); ?>>

                    <span>

                        <strong>Weekly Protection Report</strong><br>

                        <span style="color: #6b7280; font-size: 14px;">Get a summary every Monday morning</span>

                    </span>

                </label>

            </div>



            <div>

                <label>

                    <strong>Send Notifications To:</strong><br>

                    <input type="email" name="sensfrx_smb[notification_email]"

                           value="<?php echo esc_attr($smb_settings['notification_email'] ?? get_option('admin_email')); ?>"

                           style="width: 300px; padding: 8px; margin-top: 8px; border: 1px solid #d1d5db; border-radius: 4px;">

                </label>

            </div>

        </div>

    </div>



    <!-- Test Notification Button -->

    <div style="margin-top: 20px;">

        <button type="button" id="send-test-notification" class="button button-secondary">

            Send Test Notification

        </button>

        <span id="test-result" style="margin-left: 10px;"></span>

    </div>



    <script>

    jQuery('#send-test-notification').on('click', function() {

        var btn = jQuery(this);

        btn.prop('disabled', true).text('Sending...');



        jQuery.ajax({

            url: ajaxurl,

            type: 'POST',

            data: {

                action: 'sensfrx_send_test_email',

                nonce: '<?php echo esc_js( wp_create_nonce('sensfrx_test_email') ); ?>'

            },

            success: function(response) {

                if (response.success) {

                    jQuery('#test-result').html('<span style="color: #10b981;">✓ Test email sent!</span>');

                } else {

                    jQuery('#test-result').html('<span style="color: #ef4444;">✗ Failed to send</span>');

                }

            },

            complete: function() {

                btn.prop('disabled', false).text('Send Test Notification');

                setTimeout(function() {

                    jQuery('#test-result').empty();

                }, 5000);

            }

        });

    });

    </script>

    <?php

}



/**

 * Handle test email sending

 */

add_action('wp_ajax_sensfrx_send_test_email', 'sensfrx_handle_test_email');

function sensfrx_handle_test_email() {

    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sensfrx_test_email' ) ) {

        wp_die('Security check failed');

    }



    $test_data = [

        'email' => 'test@example.com',

        'risk_score' => 85,

        'ip_address' => '192.168.1.1',

        'type' => 'Test Fraud Attempt',

        'amount' => '125.00',

        'reason' => 'This is a test notification'

    ];



    // Trigger test notification

    do_action('sensfrx_fraud_blocked', $test_data, 'Test notification sent successfully');



    wp_send_json_success(['message' => 'Test email sent']);

}



/**

 * Save SMB email settings

 */

add_action('update_option_sensfrx_policy_options', 'sensfrx_save_smb_email_settings', 10, 2);

function sensfrx_save_smb_email_settings($old_value, $new_value) {

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

        $smb_settings = [

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

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

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

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

        ];



        update_option('sensfrx_email_settings', $smb_settings);

    }

}



/**

 * Add dashboard notification widget for SMB

 */

add_action('wp_dashboard_setup', 'sensfrx_add_smb_dashboard_widget');

function sensfrx_add_smb_dashboard_widget() {

    if (current_user_can('manage_options')) {

        wp_add_dashboard_widget(

            'sensfrx_smb_protection',

            '🛡️ SensFRX Fraud Protection',

            'sensfrx_smb_dashboard_widget'

        );

    }

}



/**

 * Dashboard widget content

 */

function sensfrx_smb_dashboard_widget() {

    // Get recent stats

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

    $today_count = 0;

    $week_count = 0;



    $today = date('Y-m-d');

    $week_ago = date('Y-m-d', strtotime('-7 days'));



    foreach ($protection_log as $log) {

        $log_date = date('Y-m-d', strtotime($log['timestamp']));

        if ($log_date === $today) {

            $today_count++;

        }

        if ($log_date >= $week_ago) {

            $week_count++;

        }

    }



    ?>

    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">

        <div style="text-align: center; padding: 15px; background: #f9fafb; border-radius: 6px;">

            <div style="font-size: 24px; font-weight: bold; color: #1f2937;"><?php echo esc_html( $today_count ); ?></div>

            <div style="font-size: 13px; color: #6b7280;">Blocked Today</div>

        </div>

        <div style="text-align: center; padding: 15px; background: #f9fafb; border-radius: 6px;">

            <div style="font-size: 24px; font-weight: bold; color: #1f2937;"><?php echo esc_html( $week_count ); ?></div>

            <div style="font-size: 13px; color: #6b7280;">This Week</div>

        </div>

    </div>



    <div style="border-top: 1px solid #e5e7eb; padding-top: 15px;">

        <a href="<?php echo esc_url( admin_url('admin.php?page=sensfrx-protection') ); ?>"

           class="button button-primary" style="width: 100%; text-align: center;">

            View Protection Dashboard

        </a>

    </div>

    <?php

}



/**

 * Add setup wizard trigger for new users

 */

add_action('admin_notices', 'sensfrx_show_setup_wizard_notice');

function sensfrx_show_setup_wizard_notice() {

    $wizard_completed = get_option('sensfrx_wizard_completed', false);

    $dismissed = get_user_meta(get_current_user_id(), 'sensfrx_wizard_dismissed', true);



    if (!$wizard_completed && !$dismissed && current_user_can('manage_options')) {

        ?>

        <div class="notice notice-info is-dismissible" id="sensfrx-setup-notice">

            <p>

                <strong>Welcome to SensFRX Fraud Protection!</strong>

                Set up fraud protection for your store in just 3 minutes.

            </p>

            <p>

                <a href="<?php echo esc_url( admin_url('admin.php?page=sensfrx-setup-wizard') ); ?>"

                   class="button button-primary">Start Setup Wizard</a>

                <a href="#" id="dismiss-wizard-notice" class="button button-secondary">I'll do it later</a>

            </p>

        </div>



        <script>

        jQuery('#dismiss-wizard-notice, #sensfrx-setup-notice .notice-dismiss').on('click', function(e) {

            e.preventDefault();

            jQuery.post(ajaxurl, {

                action: 'sensfrx_dismiss_wizard',

                nonce: '<?php echo esc_js( wp_create_nonce('sensfrx_dismiss') ); ?>'

            });

            jQuery('#sensfrx-setup-notice').fadeOut();

        });

        </script>

        <?php

    }

}



// Handle wizard dismissal

add_action('wp_ajax_sensfrx_dismiss_wizard', function() {

    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sensfrx_dismiss' ) ) {

        wp_die('Security check failed');

    }

    update_user_meta(get_current_user_id(), 'sensfrx_wizard_dismissed', true);

    wp_die();

});