<?php

/**

 * Fraud Protection Settings - Simple On/Off Controls

 *

 * @package    SensFRX

 * @subpackage SensFRX/admin/partials

 */



// If this file is called directly, abort.

if (!defined('WPINC')) {

    die;

}



// Get current settings

$options = get_option('sensfrx_policy_options', SensFRX::default_policy_options());



// Define user-friendly help text for each option

$help_texts = array(

    'master_fraud' => array(

        'title' => 'Protect My Store from Fraud',

        'short' => 'Turn on automatic protection for your online store',

        'long' => 'This is the main ON/OFF switch for fraud protection. When turned ON, your store will automatically check all orders, registrations, and logins for suspicious activity. We recommend keeping this ON at all times to protect your business.'

    ),

    'bot_fraud' => array(

        'title' => 'Block Fake Customers (Bots)',

        'short' => 'Stop automated programs from placing fake orders',

        'long' => 'Bots are computer programs that create fake accounts and orders. This protection identifies and blocks them automatically, saving you time from processing fake orders and protecting your inventory.'

    ),

    'new_account_fraud' => array(

        'title' => 'Check New Customer Sign-Ups',

        'short' => 'Review new accounts for suspicious behavior',

        'long' => 'When someone creates a new account, we check if they\'re a real customer or a fraudster. This helps prevent stolen credit card users from signing up and placing fraudulent orders in your store.'

    ),

    'login_fraud' => array(

        'title' => 'Protect Customer Logins',

        'short' => 'Stop hackers from guessing customer passwords',

        'long' => 'Detects when someone is trying to break into customer accounts by guessing passwords repeatedly. This protects your customers\' personal information and prevents unauthorized purchases.'

    ),

    'reset_password_fraud' => array(

        'title' => 'Secure Password Resets',

        'short' => 'Prevent fake password reset attempts',

        'long' => 'Stops fraudsters from trying to reset your customers\' passwords to take over their accounts. This keeps customer accounts safe and prevents unauthorized access to order history and saved payment methods.'

    ),

    'before_payment_fraud' => array(

        'title' => 'Check Orders Before Payment',

        'short' => 'Review orders for fraud before processing payment',

        'long' => 'Before processing any payment, we check if the order looks suspicious (stolen credit card, fake address, etc.). This prevents chargebacks and protects your store from losing money on fraudulent orders.'

    ),

    'after_payment_fraud' => array(

        'title' => 'Double-Check Completed Orders',

        'short' => 'Review completed transactions for fraud patterns',

        'long' => 'After a payment goes through, we do an extra check to catch any suspicious patterns we might have missed. This gives you an extra layer of protection and helps identify fraudsters for future orders.'

    ),

    'medium_email' => array(

        'title' => 'Medium Risk Alerts',

        'short' => 'Get emails about slightly suspicious activity',

        'long' => 'When something looks a bit suspicious but not definitely fraud, we\'ll send you an email so you can decide what to do. This helps you catch potential problems early.'

    ),

    'challenge_email' => array(

        'title' => 'Orders Needing Review',

        'short' => 'Email me when orders need manual checking',

        'long' => 'Sometimes an order is suspicious enough that we think you should review it personally before fulfilling it. We\'ll send you an email with all the details so you can make the final decision.'

    ),

    'deny_email' => array(

        'title' => 'Blocked Order Alerts',

        'short' => 'Notify me when we block suspicious orders',

        'long' => 'When we automatically block an order because it looks very fraudulent, we\'ll send you an email to keep you informed. You can review these to make sure we\'re not being too strict.'

    ),

    // Login-specific alert texts

    'medium_login_email' => array(

        'title' => 'Medium Risk Login Alerts',

        'short' => 'Get emails about slightly suspicious login attempts',

        'long' => 'When a login attempt shows some warning signs (like unusual location, new device, or multiple failed attempts) but isn\'t clearly malicious, we\'ll send you an email. This helps you monitor potential account security issues early.'

    ),

    'challenge_login_email' => array(

        'title' => 'High Risk Login Alerts',

        'short' => 'Email me when logins need manual review',

        'long' => 'When a login attempt is suspicious enough to be challenged (requiring additional verification from the user), we\'ll send you an email with all the details. This helps you track potential account takeover attempts and decide if further action is needed.'

    ),

    'deny_login_email' => array(

        'title' => 'Blocked Login Alerts',

        'short' => 'Notify me when we block suspicious login attempts',

        'long' => 'When we automatically block a login attempt because it appears to be malicious (credential stuffing, brute force attack, or compromised account access), we\'ll send you an email to keep you informed. You can review these to monitor security threats to your store.'

    ),

    'allow_payment_email' => array(

        'title' => 'Approved Payment Notifications',

        'short' => 'Email when payments pass our checks',

        'long' => 'Get notified when a payment is checked and approved as safe. This helps you keep track of legitimate orders coming through your store.'

    ),

    'challenge_payment_email' => array(

        'title' => 'Payment Review Needed',

        'short' => 'Alert me about payments that need review',

        'long' => 'When a payment looks questionable, we\'ll email you to review it before processing. This gives you control over borderline cases.'

    ),

    'deny_payment_email' => array(

        'title' => 'Declined Payment Alerts',

        'short' => 'Notify me when payments are blocked',

        'long' => 'Get an email whenever we block a payment for fraud protection. This keeps you informed about potential threats to your store.'

    ),

    'allow_register_email' => array(

        'title' => 'Approved Registration Notifications',

        'short' => 'Email when new customer accounts are approved',

        'long' => 'Get notified when someone creates a new account and it passes our safety checks. This helps you welcome new legitimate customers.'

    ),

    'challenge_register_email' => array(

        'title' => 'Registration Review Needed',

        'short' => 'Alert me about suspicious new accounts',

        'long' => 'When a new account signup looks suspicious, we\'ll email you to review it. You can decide whether to approve or block the account.'

    ),

    'deny_register_email' => array(

        'title' => 'Blocked Registration Alerts',

        'short' => 'Notify me when we block fake account attempts',

        'long' => 'Get an email when we automatically block a suspicious account registration. This keeps you informed about fraud attempts on your store.'

    ),

    'webhook_allow' => array(

        'title' => 'Real-Time Updates (Webhooks)',

        'short' => 'Enable instant notifications to external systems',

        'long' => 'Webhooks let SensFRX send instant updates to other software you use (like Slack, your custom dashboard, etc.). Only turn this ON if you\'ve set up webhook integrations.'

    ),

    'whitle_list_email' => array(

        'title' => 'Trusted Customers List',

        'short' => 'Let VIP customers skip fraud checks',

        'long' => 'If you have trusted regular customers, you can add them to a whitelist so they never get flagged for fraud. This gives your best customers a smooth shopping experience.'

    ),

    // Admin Notifications (CRITICAL SECURITY FEATURE)

    // Note: Master toggle 'admin_fraud_alerts' removed - admin alerts are cloud-managed, no master needed

    'admin_login_alerts' => array(

        'title' => 'Login Fraud Alerts',

        'short' => 'Alert me about blocked login attempts',

        'long' => 'Get notified when suspicious login attempts are detected or blocked. Helps you monitor account takeover attempts.'

    ),

    'admin_payment_alerts' => array(

        'title' => 'Payment Fraud Alerts',

        'short' => 'Alert me about suspicious orders',

        'long' => 'Receive alerts for high-risk or blocked transactions. Critical for preventing chargebacks and financial fraud.'

    ),

    'admin_registration_alerts' => array(

        'title' => 'Registration Fraud Alerts',

        'short' => 'Alert me about fake account attempts',

        'long' => 'Get notified when suspicious account registrations are blocked. Helps you track bot attacks and fake accounts.'

    ),

    // Combined toggles for Simple Mode

    'account_takeover' => array(

        'title' => 'Account Takeover Protection',

        'short' => 'Stop unauthorized access to customer accounts',

        'long' => 'Protects against account takeover attempts including brute force login attacks, credential stuffing, and fake password reset requests. This keeps your customers\' accounts safe from hackers.',

        'protects' => 'Login attempts, password resets'

    ),

    'transaction_fraud' => array(

        'title' => 'Transaction Fraud Protection',

        'short' => 'Detect fraudulent payments & orders',

        'long' => 'Comprehensive transaction fraud detection that checks orders both before and after payment processing. Prevents chargebacks, identifies stolen credit cards, and catches suspicious order patterns.',

        'protects' => 'Checkout, payment processing, completed orders'

    )

);



// Helper function to render a toggle with info icon

function render_fraud_toggle($option_key, $options, $help_text) {

    $is_checked = isset($options[$option_key]) ? $options[$option_key] : '1';

    $tooltip_id = 'tooltip-' . $option_key;

    ?>

    <div class="sensfrx-toggle-group">

        <div class="sensfrx-toggle-label-wrapper">

            <label class="sensfrx-toggle-label">

                <strong>

                    <?php echo esc_html($help_text['title']); ?>

                    <span class="sensfrx-info-icon" data-tooltip="<?php echo absint( $tooltip_id ); ?>">

                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                            <circle cx="8" cy="8" r="7" stroke="#6b7280" stroke-width="1.5"/>

                            <path d="M8 7v4M8 5h.01" stroke="#6b7280" stroke-width="1.5" stroke-linecap="round"/>

                        </svg>

                    </span>

                </strong>

                <p class="sensfrx-toggle-description"><?php echo esc_html($help_text['short']); ?></p>

            </label>

            <div class="sensfrx-tooltip" id="<?php echo absint( $tooltip_id ); ?>">

                <div class="sensfrx-tooltip-content">

                    <strong><?php echo esc_html($help_text['title']); ?></strong>

                    <p><?php echo esc_html($help_text['long']); ?></p>

                </div>

            </div>

        </div>

        <label class="sensfrx-toggle-switch">

            <input type="checkbox" name="sensfrx_policy_options[<?php echo esc_html( $option_key ); ?>]" value="1" <?php checked($is_checked, '1'); ?>>

            <span class="sensfrx-toggle-slider"></span>

        </label>

    </div>

    <?php

}



// Helper function to render a combined toggle (for Simple Mode)

function render_combined_toggle($option_key, $icon, $options, $help_text) {

    // For combined toggles, check if ALL sub-options are enabled

    $is_checked = '1'; // Default to enabled

    $actual_keys = array();

    

    if ($option_key === 'account_takeover') {

        $actual_keys = array('sensfrx_login_fraud', 'sensfrx_reset_password_fraud');

        $login = isset($options['sensfrx_login_fraud']) ? $options['sensfrx_login_fraud'] : '1';

        $reset = isset($options['sensfrx_reset_password_fraud']) ? $options['sensfrx_reset_password_fraud'] : '1';

        $is_checked = ($login === '1' && $reset === '1') ? '1' : '0';

    } elseif ($option_key === 'transaction_fraud') {

        $actual_keys = array('sensfrx_before_payment_fraud', 'sensfrx_after_payment_fraud');

        $before = isset($options['sensfrx_before_payment_fraud']) ? $options['sensfrx_before_payment_fraud'] : '1';

        $after = isset($options['sensfrx_after_payment_fraud']) ? $options['sensfrx_after_payment_fraud'] : '1';

        $is_checked = ($before === '1' && $after === '1') ? '1' : '0';

    } else {

        // Direct mapping for master, bot, new_account

        $actual_keys = array($option_key);

        $is_checked = isset($options[$option_key]) ? $options[$option_key] : '1';

    }

    

    $tooltip_id = 'tooltip-' . $option_key;

    $is_master = ($option_key === 'sensfrx_master_fraud');

    ?>

    <div class="sensfrx-protection-item" data-protection-type="<?php echo $is_master ? 'master' : 'child'; ?>">

        <div class="sensfrx-protection-icon"><?php echo esc_html( $icon ); ?></div>

        <div class="sensfrx-protection-content">

            <div class="sensfrx-protection-header">

                <strong><?php echo esc_html($help_text['title']); ?></strong>

                <span class="sensfrx-info-icon" data-tooltip="<?php echo absint( $tooltip_id ); ?>">

                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                        <circle cx="8" cy="8" r="7" stroke="#6b7280" stroke-width="1.5"/>

                        <path d="M8 7v4M8 5h.01" stroke="#6b7280" stroke-width="1.5" stroke-linecap="round"/>

                    </svg>

                </span>

            </div>

            <p class="sensfrx-protection-description"><?php echo esc_html($help_text['short']); ?></p>

            <?php if (isset($help_text['protects'])): ?>

                <p class="sensfrx-protection-scope"><strong>Protects:</strong> <?php echo esc_html($help_text['protects']); ?></p>

            <?php endif; ?>

            <div class="sensfrx-tooltip" id="<?php echo absint( $tooltip_id ); ?>">

                <div class="sensfrx-tooltip-content">

                    <strong><?php echo esc_html($help_text['title']); ?></strong>

                    <p><?php echo esc_html($help_text['long']); ?></p>

                    <?php if (isset($help_text['protects'])): ?>

                        <p style="margin-top: 10px;"><strong>Protects:</strong> <?php echo esc_html($help_text['protects']); ?></p>

                    <?php endif; ?>

                </div>

            </div>

        </div>

        <label class="sensfrx-toggle-switch">

            <input type="checkbox" class="sensfrx-combined-toggle" data-combined="<?php echo esc_html( $option_key ); ?>" <?php checked($is_checked, '1'); ?>>

            <span class="sensfrx-toggle-slider"></span>

        </label>

        

        <!-- Hidden form inputs for actual submission -->

        <?php foreach ($actual_keys as $key): 

            $key_value = isset($options[$key]) ? $options[$key] : '1';

        ?>

            <input type="hidden" name="sensfrx_policy_options[<?php echo esc_html( $key ); ?>]" value="<?php echo esc_html( $key_value ); ?>" class="sensfrx-hidden-checkbox" data-key="<?php echo esc_html( $key ); ?>">

        <?php endforeach; ?>

    </div>

    <?php

}



// ============================================================================

// SYNC SETTINGS FROM API (Bi-Directional Sync - Cloud TO WordPress)

// ============================================================================

// Fetch latest settings from SensFRX API before displaying the page

// This ensures the plugin always shows the most up-to-date settings from the cloud

try {

    // Check if the fetch method exists (safety check)

    if (method_exists('SensFRX_API_Callback_Handling', 'fetch_admin_alerts_from_api')) {

        $sync_result = SensFRX_API_Callback_Handling::fetch_admin_alerts_from_api();

        

        // If sync was successful, reload options to get the updated values

        if (isset($sync_result['success']) && $sync_result['success']) {

            $options = get_option('sensfrx_policy_options', SensFRX::default_policy_options());

        } else {

            // Sync failed but don't break the page - just log it

            error_log('SensFRX: Auto-sync on page load - FAILED: ' . (isset($sync_result['message']) ? $sync_result['message'] : 'Unknown error'));

        }

    }

} catch (Exception $e) {

    // If sync fails, don't crash the page - just log the error

    error_log('SensFRX: Auto-sync exception - ' . $e->getMessage());

}

?>



<div class="sensfrx-enterprise-wrapper">

    <!-- Navigation Tabs -->

    <?php include_once plugin_dir_path(__FILE__) . 'sensfrx-navigation.php'; ?>



    <!-- Main Content -->

    <div class="sensfrx-enterprise-dashboard">

        <!-- Page Header -->

        <div class="sensfrx-page-header">

            <div class="sensfrx-page-title-section">

                <h1 class="sensfrx-page-title">Fraud Protection Controls</h1>

                <p class="sensfrx-page-subtitle">Enable/disable protection for different types of fraud - simple and straightforward</p>

            </div>

            <div style="display: flex; align-items: center; gap: 16px;">

                <!-- Refresh Alert Settings Button -->

                <button id="sync-from-cloud-btn" onclick="syncFromCloud()" style="display: flex; align-items: center; gap: 8px; padding: 8px 16px; background: #fff; border: 1px solid #e5e7eb; border-radius: 6px; cursor: pointer; font-size: 14px; color: #047857; transition: all 0.2s;" title="Get the latest alert settings from your SensFRX dashboard">

                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" id="sync-icon" style="transition: transform 0.5s;">

                        <path d="M4 12a8 8 0 0 1 8-8V0l4 4-4 4V4a6 6 0 1 0 6 6h2a8 8 0 0 1-16 0z" fill="currentColor"/>

                    </svg>

                    <span>Refresh Alert Settings</span>

                </button>

                <span id="sync-status" style="font-size: 13px; color: #666;"></span>

                

                <!-- Auto-save Status -->

                <div class="sensfrx-autosave-status" id="sensfrx-save-status">

                    <svg class="sensfrx-save-icon" width="20" height="20" viewBox="0 0 20 20" fill="none">

                        <path d="M16 4l-8 8-4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                    <span id="sensfrx-save-text">All changes saved</span>

                </div>

            </div>

        </div>



        <?php /* ?>

        <!-- Premium Features Section - OFAC Compliance -->

        <div id="ofac-premium-section" style="margin-bottom: 30px;">

            <!-- Loading state -->

            <div id="ofac-premium-loading" style="text-align: center; padding: 20px; color: #6B7280;">

                Loading...

            </div>



            <!-- For FREE users - Show upgrade card with PRO badge -->

            <div id="ofac-free-card" style="display: none;">

                <div class="sensfrx-settings-card" style="background: linear-gradient(135deg, #EFF6FF 0%, #DBEAFE 100%); border: 2px solid #3B82F6;">

                    <div style="display: flex; align-items: center; gap: 20px; padding: 24px;">

                        <!-- Icon -->

                        <div style="flex-shrink: 0;">

                            <div style="width: 56px; height: 56px; background: #3B82F6; border-radius: 12px; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 6px rgba(59, 130, 246, 0.3);">

                                <svg width="28" height="28" viewBox="0 0 24 24" fill="none">

                                    <path d="M12 2L3 7v6c0 5.5 3.8 10.7 9 12 5.2-1.3 9-6.5 9-12V7l-9-5z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                    <circle cx="12" cy="12" r="3" fill="white"/>

                                </svg>

                            </div>

                        </div>

                        <!-- Content -->

                        <div style="flex: 1;">

                            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px;">

                                <h3 style="margin: 0; font-size: 20px; font-weight: 700; color: #1E40AF;">OFAC Compliance</h3>

                                <span style="background: #3B82F6; color: white; padding: 4px 12px; border-radius: 6px; font-size: 12px; font-weight: 700; letter-spacing: 0.5px;">PRO</span>

                            </div>

                            <p style="margin: 0 0 16px; font-size: 14px; color: #1E3A8A; line-height: 1.6;">

                                Automated sanctions screening against US Treasury lists. Ensure compliance with federal regulations and protect your business from legal risks.

                            </p>

                            <a href="<?php echo esc_url(admin_url('admin.php?page=sensfrx_fpwoo&tab=ofac-compliance')); ?>" style="display: inline-flex; align-items: center; gap: 8px; padding: 10px 20px; background: #3B82F6; color: white; text-decoration: none; border-radius: 6px; font-size: 14px; font-weight: 600; transition: all 0.2s; box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);">

                                <svg width="16" height="16" viewBox="0 0 20 20" fill="white">

                                    <path d="M10 2l2 6h6l-5 4 2 6-5-4-5 4 2-6-5-4h6z"/>

                                </svg>

                                View Details & Upgrade

                            </a>

                        </div>

                    </div>

                </div>

            </div>



            <!-- For PRO users - Show configuration card (Compact when Active) -->

            <div id="ofac-pro-card" style="display: none;">

                <div id="ofac-card-container" class="sensfrx-settings-card" style="background: white; border: 1px solid #E5E7EB; cursor: pointer; transition: all 0.3s;" onclick="toggleOfacCard()">

                    <div style="display: flex; align-items: center; gap: 16px; padding: 14px 18px;">

                        <!-- Smaller Icon -->

                        <div id="ofac-icon-container" style="flex-shrink: 0;">

                            <div style="width: 36px; height: 36px; background: #10B981; border-radius: 8px; display: flex; align-items: center; justify-content: center;">

                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none">

                                    <path d="M12 2L3 7v6c0 5.5 3.8 10.7 9 12 5.2-1.3 9-6.5 9-12V7l-9-5z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                    <path d="M9 12l2 2 4-4" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                </svg>

                            </div>

                        </div>

                        <!-- Content -->

                        <div style="flex: 1;">

                            <div style="display: flex; align-items: center; gap: 8px;">

                                <h3 style="margin: 0; font-size: 15px; font-weight: 600; color: #374151;">OFAC Compliance</h3>

                                <span id="ofac-status-badge" style="background: #E5E7EB; color: #6B7280; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600;">Checking...</span>

                            </div>

                            <p id="ofac-description" style="margin: 4px 0 0; font-size: 12px; color: #6B7280; line-height: 1.4;">

                                Automated sanctions screening is available. Configure your OFAC compliance settings.

                            </p>

                        </div>

                        <!-- Buttons -->

                        <div style="flex-shrink: 0; display: flex; gap: 8px; align-items: center;">

                            <a id="ofac-configure-btn" href="<?php echo esc_url(admin_url('admin.php?page=sensfrx_fpwoo&tab=ofac-compliance')); ?>" onclick="event.stopPropagation();" style="display: inline-flex; align-items: center; gap: 6px; padding: 8px 14px; background: #10B981; color: white; text-decoration: none; border-radius: 6px; font-size: 13px; font-weight: 600; transition: all 0.2s; white-space: nowrap;">

                                Configure Settings

                                <svg width="14" height="14" viewBox="0 0 20 20" fill="white">

                                    <path d="M7 10l5 5 5-5M7 5l5 5 5-5" stroke="white" stroke-width="2" fill="none"/>

                                </svg>

                            </a>

                            <button type="button" id="ofac-collapse-btn" onclick="event.stopPropagation(); toggleOfacCard();" style="display: none; padding: 6px; background: #F9FAFB; border: 1px solid #E5E7EB; color: #6B7280; border-radius: 6px; cursor: pointer; transition: all 0.2s;">

                                <svg id="ofac-collapse-icon" width="18" height="18" viewBox="0 0 20 20" fill="none" style="transition: transform 0.3s;">

                                    <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                </svg>

                            </button>

                        </div>

                    </div>

                </div>

            </div>

        </div>

        <?php */ ?>



        <form id="sensfrx-fraud-protection-form" method="post" action="options.php">

            <?php settings_fields('sensfrx_plugin_policy_options'); ?>



            <!-- Protection Settings with Two Column Layout -->

            <div class="sensfrx-settings-grid">

                <!-- Left Column - Core Protection Settings (STICKY) -->

                <div class="sensfrx-settings-column sensfrx-sticky-column">

                    <div class="sensfrx-protection-list">

                        <?php

                        // Master Protection

                        render_combined_toggle('sensfrx_master_fraud', '🔒', $options, $help_texts['master_fraud']);

                        

                        // Bot Protection

                        render_combined_toggle('sensfrx_bot_fraud', '🤖', $options, $help_texts['bot_fraud']);

                        

                        // New Account Fraud

                        render_combined_toggle('sensfrx_new_account_fraud', '👤', $options, $help_texts['new_account_fraud']);

                        

                        // Account Takeover (combines login + password reset)

                        render_combined_toggle('account_takeover', '🔐', $options, $help_texts['account_takeover']);

                        

                        // Transaction Fraud (combines before + after payment)

                        render_combined_toggle('transaction_fraud', '💳', $options, $help_texts['transaction_fraud']);

                        ?>

                    </div>

                </div>



                <!-- Right Column - Email Notifications & Advanced Features -->

                <div class="sensfrx-settings-column">



                    <!-- Admin Notifications (CRITICAL SECURITY FEATURE) -->

                    <div class="sensfrx-settings-card sensfrx-collapsible-card" data-card="admin-alerts" style="border: 2px solid #d32f2f; background: linear-gradient(135deg, #fff5f5 0%, #ffebee 100%);">

                        <div class="sensfrx-card-header sensfrx-card-header-clickable" onclick="toggleCard('admin-alerts')">

                            <div style="display: flex; align-items: flex-start; gap: 16px; flex: 1;">

                                <div class="sensfrx-card-icon" style="background: linear-gradient(135deg, #d32f2f 0%, #c62828 100%);">

                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                        <path d="M12 2L3 7v6c0 5.5 3.8 10.7 9 12 5.2-1.3 9-6.5 9-12V7l-9-5z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        <path d="M12 8v4M12 16h.01" stroke="white" stroke-width="2" stroke-linecap="round"/>

                                    </svg>

                                </div>

                                <div>

                                    <h3 class="sensfrx-card-title" style="color: #d32f2f;">🔴 Admin Fraud Alerts</h3>

                                    <p class="sensfrx-card-description" style="color: #c62828;"><strong>CRITICAL:</strong> Get notified about fraud attempts</p>

                                </div>

                            </div>

                            <button type="button" class="sensfrx-collapse-btn" onclick="event.stopPropagation(); toggleCard('admin-alerts')">

                                <svg class="sensfrx-collapse-icon" width="20" height="20" viewBox="0 0 20 20" fill="none">

                                    <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                </svg>

                            </button>

                        </div>

                        

                        <div class="sensfrx-card-body" data-card-body="admin-alerts">



                        <div style="background: #fff; padding: 12px; border-radius: 5px; margin-bottom: 15px; border-left: 4px solid #d32f2f;">

                            <p style="margin: 0; font-size: 13px; color: #666;">

                                <strong>⚡ Why this matters:</strong> Without admin alerts, you won't know when fraudsters attack your store. 

                                These alerts keep YOU (the store owner) informed about blocked logins, suspicious orders, and fake registrations.

                            </p>

                        </div>



                        <div style="padding: 12px; background: #f5f5f5; border-radius: 5px; margin-bottom: 20px;">

                            <label style="display: block; margin-bottom: 8px; font-weight: 600; font-size: 13px; color: #333;">

                                📧 Admin Email Address

                            </label>

                            <input type="email" 

                                   name="sensfrx_policy_options[sensfrx_admin_alert_email]" 

                                   value="<?php echo esc_attr(isset($options['sensfrx_admin_alert_email']) ? $options['sensfrx_admin_alert_email'] : get_option('admin_email')); ?>" 

                                   placeholder="<?php echo esc_attr(get_option('admin_email')); ?>"

                                   style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">

                            <p style="margin: 8px 0 0 0; font-size: 12px; color: #666;">All admin alerts will be sent to this email address</p>

                        </div>



                        <!-- Admin Login Alerts -->

                        <div class="sensfrx-admin-subsection sensfrx-subsection-collapsed" data-subsection="admin-login" style="margin-bottom: 20px; padding: 15px; background: #fff; border-radius: 8px; border: 1px solid #e5e7eb;">

                            <div class="sensfrx-subsection-header" onclick="toggleSubsection('admin-login')" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; cursor: pointer;">

                                <div style="display: flex; align-items: center; gap: 12px; flex: 1;">

                                    <h4 style="margin: 0; font-size: 15px; font-weight: 600; color: #374151; display: flex; align-items: center; gap: 8px;">

                                        <span style="font-size: 18px;">🔑</span> Login Fraud Alerts

                                    </h4>

                                </div>

                                <div style="display: flex; align-items: center; gap: 12px;">

                                    <button type="button" class="sensfrx-subsection-collapse-btn" onclick="event.stopPropagation(); toggleSubsection('admin-login')" style="background: #f3f4f6; border: none; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; color: #6b7280;">

                                        <svg class="sensfrx-subsection-collapse-icon" width="16" height="16" viewBox="0 0 20 20" fill="none" style="transition: transform 0.3s ease;">

                                            <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        </svg>

                                    </button>

                                </div>

                            </div>

                            <div class="sensfrx-subsection-body" data-subsection-body="admin-login" style="max-height: 0; overflow: hidden; transition: max-height 0.3s ease, opacity 0.3s ease; opacity: 0;">

                                <p style="margin: 0 0 12px 0; font-size: 13px; color: #6b7280;">Get notified when suspicious or blocked login attempts are detected</p>

                                <?php render_fraud_toggle('sensfrx_admin_challenge_login_email', $options, array(

                                    'title' => 'High Risk Login Alerts',

                                    'short' => 'Email admin when logins are challenged',

                                    'long' => 'Get notified when customer logins require additional verification due to high risk (score 60-89).'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_admin_deny_login_email', $options, array(

                                    'title' => 'Blocked Login Alerts',

                                    'short' => 'Email admin when logins are blocked',

                                    'long' => 'Get notified when customer logins are blocked due to critical security threats (score 90+).'

                                )); ?>

                            </div>

                        </div>



                        <!-- Admin Payment Alerts -->

                        <div class="sensfrx-admin-subsection sensfrx-subsection-collapsed" data-subsection="admin-payment" style="margin-bottom: 20px; padding: 15px; background: #fff; border-radius: 8px; border: 1px solid #e5e7eb;">

                            <div class="sensfrx-subsection-header" onclick="toggleSubsection('admin-payment')" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; cursor: pointer;">

                                <div style="display: flex; align-items: center; gap: 12px; flex: 1;">

                                    <h4 style="margin: 0; font-size: 15px; font-weight: 600; color: #374151; display: flex; align-items: center; gap: 8px;">

                                        <span style="font-size: 18px;">💳</span> Payment Fraud Alerts

                                    </h4>

                                </div>

                                <div style="display: flex; align-items: center; gap: 12px;">

                                    <button type="button" class="sensfrx-subsection-collapse-btn" onclick="event.stopPropagation(); toggleSubsection('admin-payment')" style="background: #f3f4f6; border: none; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; color: #6b7280;">

                                        <svg class="sensfrx-subsection-collapse-icon" width="16" height="16" viewBox="0 0 20 20" fill="none" style="transition: transform 0.3s ease;">

                                            <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        </svg>

                                    </button>

                                </div>

                            </div>

                            <div class="sensfrx-subsection-body" data-subsection-body="admin-payment" style="max-height: 0; overflow: hidden; transition: max-height 0.3s ease, opacity 0.3s ease; opacity: 0;">

                                <p style="margin: 0 0 12px 0; font-size: 13px; color: #6b7280;">Get notified about suspicious payment/order activity</p>

                                <?php render_fraud_toggle('sensfrx_admin_challenge_payment_email', $options, array(

                                    'title' => 'Payment Review Alerts',

                                    'short' => 'Email admin when payments need review',

                                    'long' => 'Get notified when customer payments are flagged for manual review due to high risk (score 60-89).'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_admin_deny_payment_email', $options, array(

                                    'title' => 'Declined Payment Alerts',

                                    'short' => 'Email admin when payments are declined',

                                    'long' => 'Get notified when customer payments are blocked due to critical fraud indicators (score 90+).'

                                )); ?>

                            </div>

                        </div>



                        <!-- Admin Registration Alerts -->

                        <div class="sensfrx-admin-subsection sensfrx-subsection-collapsed" data-subsection="admin-registration" style="margin-bottom: 0; padding: 15px; background: #fff; border-radius: 8px; border: 1px solid #e5e7eb;">

                            <div class="sensfrx-subsection-header" onclick="toggleSubsection('admin-registration')" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; cursor: pointer;">

                                <div style="display: flex; align-items: center; gap: 12px; flex: 1;">

                                    <h4 style="margin: 0; font-size: 15px; font-weight: 600; color: #374151; display: flex; align-items: center; gap: 8px;">

                                        <span style="font-size: 18px;">👤</span> Registration Fraud Alerts

                                    </h4>

                                </div>

                                <div style="display: flex; align-items: center; gap: 12px;">

                                    <button type="button" class="sensfrx-subsection-collapse-btn" onclick="event.stopPropagation(); toggleSubsection('admin-registration')" style="background: #f3f4f6; border: none; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; color: #6b7280;">

                                        <svg class="sensfrx-subsection-collapse-icon" width="16" height="16" viewBox="0 0 20 20" fill="none" style="transition: transform 0.3s ease;">

                                            <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        </svg>

                                    </button>

                                </div>

                            </div>

                            <div class="sensfrx-subsection-body" data-subsection-body="admin-registration" style="max-height: 0; overflow: hidden; transition: max-height 0.3s ease, opacity 0.3s ease; opacity: 0;">

                                <p style="margin: 0 0 12px 0; font-size: 13px; color: #6b7280;">Get notified about suspicious and blocked account registration attempts</p>

                                <?php render_fraud_toggle('sensfrx_admin_challenge_register_email', $options, array(

                                    'title' => 'Registration Review Alerts',

                                    'short' => 'Email admin when registrations need review',

                                    'long' => 'Get notified when customer registrations are flagged for manual review due to high risk (score 60-89).'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_admin_deny_register_email', $options, array(

                                    'title' => 'Blocked Registration Alerts',

                                    'short' => 'Email admin when registrations are blocked',

                                    'long' => 'Get notified when customer registrations are blocked due to critical fraud indicators (score 90+).'

                                )); ?>

                            </div>

                        </div>



                        </div>

                    </div>



                    <!-- Customer Fraud Alert Emails -->

                    <div class="sensfrx-settings-card sensfrx-collapsible-card" data-card="customer-alerts" style="border: 2px solid #3b82f6; background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);">

                        <div class="sensfrx-card-header sensfrx-card-header-clickable" onclick="toggleCard('customer-alerts')">

                            <div style="display: flex; align-items: flex-start; gap: 16px; flex: 1;">

                                <div class="sensfrx-card-icon" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);">

                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                        <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        <circle cx="9" cy="7" r="4" stroke="white" stroke-width="2"/>

                                        <path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                    </svg>

                                </div>

                                <div>

                                    <h3 class="sensfrx-card-title" style="color: #2563eb;">🔵 Customer Fraud Alert Emails</h3>

                                    <p class="sensfrx-card-description" style="color: #1e40af;">Send fraud alert emails to your CUSTOMERS when their actions are flagged</p>

                                </div>

                            </div>

                            <div style="display: flex; align-items: center; gap: 12px;">

                                <!-- Master Toggle for Customer Alerts -->

                                <div class="sensfrx-header-toggle" onclick="event.stopPropagation();" style="display: flex; align-items: center; gap: 8px;">

                                    <input type="hidden" 

                                           name="sensfrx_policy_options[sensfrx_customer_fraud_alerts]" 

                                           class="sensfrx-hidden-checkbox" 

                                           data-key="sensfrx_customer_fraud_alerts" 

                                           value="<?php echo esc_attr(isset($options['sensfrx_customer_fraud_alerts']) && $options['sensfrx_customer_fraud_alerts'] === '1' ? '1' : '0'); ?>">

                                    <label class="sensfrx-toggle-switch" style="position: relative; display: inline-block; width: 44px; height: 24px; margin: 0;">

                                        <input type="checkbox" 

                                               class="sensfrx-checkbox-toggle sensfrx-customer-master-toggle" 

                                               data-section="customer-alerts"

                                               <?php echo (isset($options['sensfrx_customer_fraud_alerts']) && $options['sensfrx_customer_fraud_alerts'] === '1') ? 'checked' : ''; ?>

                                               style="opacity: 0; width: 0; height: 0;">

                                        <span class="sensfrx-slider sensfrx-header-slider"></span>

                                    </label>

                                </div>

                                <button type="button" class="sensfrx-collapse-btn" onclick="event.stopPropagation(); toggleCard('customer-alerts')">

                                    <svg class="sensfrx-collapse-icon" width="20" height="20" viewBox="0 0 20 20" fill="none">

                                        <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                    </svg>

                                </button>

                            </div>

                        </div>

                        

                        <div class="sensfrx-card-body" data-card-body="customer-alerts">



                        <div style="background: #fff; padding: 12px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #3b82f6;">

                            <p style="margin: 0; font-size: 13px; color: #666;">

                                <strong>📨 About Customer Emails:</strong> These emails are sent TO YOUR CUSTOMERS (not admins) when their login, payment, or registration triggers fraud detection. 

                                This keeps customers informed about security events on their account and helps prevent account takeovers.

                            </p>

                        </div>



                        <!-- Customer Login Alert Emails -->

                        <div class="sensfrx-customer-subsection sensfrx-subsection-collapsed" data-subsection="customer-login" style="margin-bottom: 20px; padding: 15px; background: #fff; border-radius: 8px; border: 1px solid #e5e7eb;">

                            <div class="sensfrx-subsection-header" onclick="toggleSubsection('customer-login')" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; cursor: pointer;">

                                <div style="display: flex; align-items: center; gap: 12px; flex: 1;">

                                    <h4 style="margin: 0; font-size: 15px; font-weight: 600; color: #374151; display: flex; align-items: center; gap: 8px;">

                                        <span style="font-size: 18px;">🔑</span> Login Alert Emails to Customers

                                    </h4>

                                    <button type="button" class="sensfrx-subsection-collapse-btn" onclick="event.stopPropagation(); toggleSubsection('customer-login')" style="background: #f3f4f6; border: none; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; color: #6b7280;">

                                        <svg class="sensfrx-subsection-collapse-icon" width="16" height="16" viewBox="0 0 20 20" fill="none" style="transition: transform 0.3s ease;">

                                            <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        </svg>

                                    </button>

                                </div>

                            </div>

                            <div class="sensfrx-subsection-body" data-subsection-body="customer-login" style="max-height: 0; overflow: hidden; transition: max-height 0.3s ease, opacity 0.3s ease; opacity: 0;">

                                <p style="margin: 0 0 12px 0; font-size: 13px; color: #6b7280;">Send email alerts to customers when their login attempt is flagged</p>

                                <?php render_fraud_toggle('sensfrx_medium_email', $options, array(

                                    'title' => 'Medium Risk Login Email',

                                    'short' => 'Email customer about medium risk login',

                                    'long' => 'When a customer\'s login shows warning signs but is allowed, they receive an email to verify it was them.'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_challenge_email', $options, array(

                                    'title' => 'High Risk Login Email',

                                    'short' => 'Email customer when login is challenged',

                                    'long' => 'When a customer\'s login is challenged for additional verification, they receive an email with instructions.'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_deny_email', $options, array(

                                    'title' => 'Blocked Login Email',

                                    'short' => 'Email customer when login is blocked',

                                    'long' => 'When a customer\'s login is blocked for security, they receive an email explaining why and how to resolve it.'

                                )); ?>

                            </div>

                        </div>



                        <!-- Customer Payment Alert Emails -->

                        <div class="sensfrx-customer-subsection sensfrx-subsection-collapsed" data-subsection="customer-payment" style="margin-bottom: 20px; padding: 15px; background: #fff; border-radius: 8px; border: 1px solid #e5e7eb;">

                            <div class="sensfrx-subsection-header" onclick="toggleSubsection('customer-payment')" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; cursor: pointer;">

                                <div style="display: flex; align-items: center; gap: 12px; flex: 1;">

                                    <h4 style="margin: 0; font-size: 15px; font-weight: 600; color: #374151; display: flex; align-items: center; gap: 8px;">

                                        <span style="font-size: 18px;">💳</span> Payment Alert Emails to Customers

                                    </h4>

                                    <button type="button" class="sensfrx-subsection-collapse-btn" onclick="event.stopPropagation(); toggleSubsection('customer-payment')" style="background: #f3f4f6; border: none; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; color: #6b7280;">

                                        <svg class="sensfrx-subsection-collapse-icon" width="16" height="16" viewBox="0 0 20 20" fill="none" style="transition: transform 0.3s ease;">

                                            <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        </svg>

                                    </button>

                                </div>

                            </div>

                            <div class="sensfrx-subsection-body" data-subsection-body="customer-payment" style="max-height: 0; overflow: hidden; transition: max-height 0.3s ease, opacity 0.3s ease; opacity: 0;">

                                <p style="margin: 0 0 12px 0; font-size: 13px; color: #6b7280;">Send email alerts to customers when their payment/order is flagged</p>

                                <?php render_fraud_toggle('sensfrx_allow_payment_email', $options, array(

                                    'title' => 'Medium Risk Payment Email',

                                    'short' => 'Email customer about medium risk payment',

                                    'long' => 'When a customer\'s payment shows warning signs but is processed, they receive a security notification email.'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_challenge_payment_email', $options, array(

                                    'title' => 'Payment Review Email',

                                    'short' => 'Email customer when payment is under review',

                                    'long' => 'When a customer\'s payment is flagged for review, they receive an email that their order is being verified.'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_deny_payment_email', $options, array(

                                    'title' => 'Declined Payment Email',

                                    'short' => 'Email customer when payment is declined',

                                    'long' => 'When a customer\'s payment is declined for fraud protection, they receive an email explaining why and next steps.'

                                )); ?>

                            </div>

                        </div>



                        <!-- Customer Registration Alert Emails -->

                        <div class="sensfrx-customer-subsection sensfrx-subsection-collapsed" data-subsection="customer-registration" style="margin-bottom: 0; padding: 15px; background: #fff; border-radius: 8px; border: 1px solid #e5e7eb;">

                            <div class="sensfrx-subsection-header" onclick="toggleSubsection('customer-registration')" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; cursor: pointer;">

                                <div style="display: flex; align-items: center; gap: 12px; flex: 1;">

                                    <h4 style="margin: 0; font-size: 15px; font-weight: 600; color: #374151; display: flex; align-items: center; gap: 8px;">

                                        <span style="font-size: 18px;">👤</span> Registration Alert Emails to Customers

                                    </h4>

                                    <button type="button" class="sensfrx-subsection-collapse-btn" onclick="event.stopPropagation(); toggleSubsection('customer-registration')" style="background: #f3f4f6; border: none; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; color: #6b7280;">

                                        <svg class="sensfrx-subsection-collapse-icon" width="16" height="16" viewBox="0 0 20 20" fill="none" style="transition: transform 0.3s ease;">

                                            <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                        </svg>

                                    </button>

                                </div>

                            </div>

                            <div class="sensfrx-subsection-body" data-subsection-body="customer-registration" style="max-height: 0; overflow: hidden; transition: max-height 0.3s ease, opacity 0.3s ease; opacity: 0;">

                                <p style="margin: 0 0 12px 0; font-size: 13px; color: #6b7280;">Send email alerts to customers when their registration attempt is flagged</p>

                                <?php render_fraud_toggle('sensfrx_allow_register_email', $options, array(

                                    'title' => 'Medium Risk Registration Email',

                                    'short' => 'Email customer about medium risk registration',

                                    'long' => 'When a customer\'s registration shows warning signs but is approved, they receive a welcome email with security notice.'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_challenge_register_email', $options, array(

                                    'title' => 'Registration Review Email',

                                    'short' => 'Email customer when registration is under review',

                                    'long' => 'When a customer\'s registration is flagged for review, they receive an email that their account is being verified.'

                                )); ?>

                                <?php render_fraud_toggle('sensfrx_deny_register_email', $options, array(

                                    'title' => 'Blocked Registration Email',

                                    'short' => 'Email customer when registration is blocked',

                                    'long' => 'When a customer\'s registration is blocked for security, they receive an email explaining why with support contact info.'

                                )); ?>

                            </div>

                        </div>



                        </div>

                    </div>



                    <!-- Advanced Features -->

                    <div class="sensfrx-settings-card sensfrx-collapsible-card sensfrx-card-collapsed" data-card="advanced-features">

                        <div class="sensfrx-card-header sensfrx-card-header-clickable" onclick="toggleCard('advanced-features')">

                            <div style="display: flex; align-items: flex-start; gap: 16px; flex: 1;">

                                <div class="sensfrx-card-icon" style="background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);">

                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                                        <circle cx="12" cy="12" r="3" stroke="white" stroke-width="2"/>

                                        <path d="M12 1v3m0 14v3M4.2 4.2l2.1 2.1m11.4 11.4l2.1 2.1M1 12h3m14 0h3M4.2 19.8l2.1-2.1m11.4-11.4l2.1-2.1" stroke="white" stroke-width="2"/>

                                    </svg>

                                </div>

                                <div>

                                    <h3 class="sensfrx-card-title">Advanced Features</h3>

                                    <p class="sensfrx-card-description">Extra tools for power users</p>

                                </div>

                            </div>

                            <button type="button" class="sensfrx-collapse-btn" onclick="event.stopPropagation(); toggleCard('advanced-features')">

                                <svg class="sensfrx-collapse-icon" width="20" height="20" viewBox="0 0 20 20" fill="none">

                                    <path d="M5 7.5l5 5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                </svg>

                            </button>

                        </div>



                        <div class="sensfrx-card-body" data-card-body="advanced-features">

                        <?php render_fraud_toggle('sensfrx_webhook_allow', $options, $help_texts['webhook_allow']); ?>

                        <?php //render_fraud_toggle('sensfrx_whitle_list_email', $options, $help_texts['whitle_list_email']); ?>

                        </div>

                    </div>



                </div>

            </div>



            <!-- Save Button -->

            <!-- <div class="sensfrx-form-actions" style="margin-top: 30px;">

                <button type="submit" class="sensfrx-btn-primary">

                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">

                        <path d="M16 4l-8 8-4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                    Save All Settings

                </button>

            </div> -->

        </form>

    </div>

</div>



<style>

    /* Additional styles specific to fraud protection page */



    /* Protection List */

    .sensfrx-protection-list {

        display: flex;

        flex-direction: column;

        gap: 16px;

    }



    .sensfrx-protection-item {

        display: flex;

        align-items: flex-start;

        gap: 20px;

        padding: 24px;

        background: white;

        border: 1px solid #e5e7eb;

        border-radius: 12px;

        transition: all 0.2s ease;

    }



    .sensfrx-protection-item:hover {

        border-color: #3b82f6;

        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);

    }



    .sensfrx-protection-icon {

        flex-shrink: 0;

        font-size: 32px;

        line-height: 1;

    }



    /* Disabled toggle styles */

    .sensfrx-toggle-switch input[type="checkbox"]:disabled + .sensfrx-toggle-slider {

        cursor: not-allowed;

        opacity: 0.5;

    }



    .sensfrx-protection-item[data-protection-type="child"] {

        transition: opacity 0.3s ease;

    }



    .sensfrx-protection-content {

        flex: 1;

        position: relative;

    }



    .sensfrx-protection-header {

        display: flex;

        align-items: center;

        gap: 8px;

        margin-bottom: 6px;

    }



    .sensfrx-protection-header strong {

        font-size: 16px;

        font-weight: 600;

        color: #1f2937;

    }



    .sensfrx-protection-description {

        font-size: 14px;

        color: #6b7280;

        margin: 0 0 8px 0;

        line-height: 1.5;

    }



    .sensfrx-protection-scope {

        font-size: 13px;

        color: #3b82f6;

        margin: 0;

    }



    .sensfrx-protection-scope strong {

        font-weight: 600;

    }



    /* Advanced Mode - Grid Layout */

    .sensfrx-settings-grid {

        display: grid;

        grid-template-columns: 1fr 1fr;

        gap: 30px;

        margin-top: 30px;

    }



    .sensfrx-settings-column {

        display: flex;

        flex-direction: column;

        gap: 24px;

    }



    /* Sticky Left Column */

    .sensfrx-sticky-column {

        position: sticky;

        top: 32px; /* WordPress admin bar height */

        align-self: flex-start;

        max-height: calc(100vh - 64px);

        overflow-y: auto;

    }



    /* Scrollbar styling for sticky column */

    .sensfrx-sticky-column::-webkit-scrollbar {

        width: 6px;

    }



    .sensfrx-sticky-column::-webkit-scrollbar-track {

        background: #f3f4f6;

        border-radius: 3px;

    }



    .sensfrx-sticky-column::-webkit-scrollbar-thumb {

        background: #d1d5db;

        border-radius: 3px;

    }



    .sensfrx-sticky-column::-webkit-scrollbar-thumb:hover {

        background: #9ca3af;

    }



    /* Improved Toggle Switch Styling */

    .sensfrx-toggle-group {

        display: flex;

        justify-content: space-between;

        align-items: center;

        padding: 16px;

        background: #f9fafb;

        border-radius: 8px;

        margin-bottom: 12px;

        transition: background 0.2s ease;

    }



    .sensfrx-toggle-group:hover {

        background: #f3f4f6;

    }



    .sensfrx-toggle-label-wrapper {

        flex: 1;

        margin-right: 20px;

        position: relative;

    }



    .sensfrx-toggle-label {

        margin: 0;

        cursor: pointer;

    }



    .sensfrx-toggle-label strong {

        display: flex;

        align-items: center;

        font-size: 15px;

        font-weight: 600;

        color: #1f2937;

        margin-bottom: 4px;

    }



    .sensfrx-toggle-description {

        font-size: 13px;

        color: #6b7280;

        margin: 0;

        line-height: 1.5;

    }



    /* Info Icon */

    .sensfrx-info-icon {

        display: inline-flex;

        align-items: center;

        margin-left: 6px;

        cursor: help;

        position: relative;

    }



    .sensfrx-info-icon svg {

        transition: transform 0.2s ease;

    }



    .sensfrx-info-icon:hover svg {

        transform: scale(1.1);

    }



    .sensfrx-info-icon:hover svg circle,

    .sensfrx-info-icon:hover svg path {

        stroke: #3b82f6;

    }



    /* Tooltip */

    .sensfrx-tooltip {

        display: none;

        position: absolute;

        left: 0;

        top: 100%;

        margin-top: 8px;

        background: #1f2937;

        color: white;

        padding: 12px 16px;

        border-radius: 8px;

        max-width: 400px;

        z-index: 1000;

        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2);

        font-size: 13px;

        line-height: 1.5;

    }



    .sensfrx-tooltip.show {

        display: block;

    }



    .sensfrx-tooltip strong {

        display: block;

        margin-bottom: 6px;

        color: #60a5fa;

        font-size: 14px;

    }



    .sensfrx-tooltip p {

        margin: 0;

    }



    /* Modern Toggle Switch */

    .sensfrx-toggle-switch {

        position: relative;

        display: inline-block;

        width: 52px;

        height: 28px;

        flex-shrink: 0;

    }



    .sensfrx-toggle-switch input {

        opacity: 0;

        width: 0;

        height: 0;

    }



    .sensfrx-toggle-slider {

        position: absolute;

        cursor: pointer;

        top: 0;

        left: 0;

        right: 0;

        bottom: 0;

        background-color: #d1d5db;

        transition: .3s;

        border-radius: 28px;

    }



    .sensfrx-toggle-slider:before {

        position: absolute;

        content: "";

        height: 22px;

        width: 22px;

        left: 3px;

        bottom: 3px;

        background-color: white;

        transition: .3s;

        border-radius: 50%;

        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

    }



    .sensfrx-toggle-switch input:checked + .sensfrx-toggle-slider {

        background-color: #10b981;

    }



    .sensfrx-toggle-switch input:checked + .sensfrx-toggle-slider:before {

        transform: translateX(24px);

    }



    .sensfrx-toggle-switch input:focus + .sensfrx-toggle-slider {

        box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2);

    }



    /* Header Master Toggle (smaller version in subsection headers) */

    .sensfrx-header-slider {

        position: absolute;

        cursor: pointer;

        top: 0;

        left: 0;

        right: 0;

        bottom: 0;

        background-color: #cbd5e1;

        transition: .3s;

        border-radius: 24px;

    }



    .sensfrx-header-slider:before {

        position: absolute;

        content: "";

        height: 18px;

        width: 18px;

        left: 3px;

        bottom: 3px;

        background-color: white;

        transition: .3s;

        border-radius: 50%;

        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

    }



    /* Customer Master Toggle (for Customer Alerts card) */

    .sensfrx-customer-master-toggle:checked + .sensfrx-header-slider {

        background-color: #10b981 !important;

    }



    .sensfrx-customer-master-toggle:checked + .sensfrx-header-slider:before {

        transform: translateX(20px);

    }



    .sensfrx-customer-master-toggle:focus + .sensfrx-header-slider {

        box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2);

    }



    /* Refresh Alert Settings Button */

    #sync-from-cloud-btn:hover {

        background: #f9fafb !important;

        border-color: #047857 !important;

        transform: translateY(-1px);

        box-shadow: 0 2px 4px rgba(4, 120, 87, 0.1);

    }

    

    #sync-from-cloud-btn:active {

        transform: translateY(0);

    }

    

    #sync-from-cloud-btn:disabled {

        opacity: 0.6;

        cursor: not-allowed;

    }

    

    @keyframes spin {

        from { transform: rotate(0deg); }

        to { transform: rotate(360deg); }

    }



    /* Card Improvements */

    .sensfrx-settings-card {

        background: white;

        border: 1px solid #e5e7eb;

        border-radius: 12px;

        padding: 24px;

        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

        transition: all 0.3s ease;

    }



    /* Collapsible Card Styles */

    .sensfrx-collapsible-card .sensfrx-card-header {

        display: flex;

        align-items: flex-start;

        justify-content: space-between;

        gap: 16px;

        margin-bottom: 20px;

        padding-bottom: 20px;

        border-bottom: 2px solid #f3f4f6;

    }



    .sensfrx-card-header-clickable {

        cursor: pointer;

        transition: background-color 0.2s ease;

        border-radius: 8px;

    }



    .sensfrx-card-header-clickable:hover {

        background-color: rgba(59, 130, 246, 0.05);

    }



    .sensfrx-collapse-btn {

        background: #f3f4f6;

        border: none;

        border-radius: 8px;

        width: 36px;

        height: 36px;

        display: flex;

        align-items: center;

        justify-content: center;

        cursor: pointer;

        transition: all 0.2s ease;

        flex-shrink: 0;

        color: #6b7280;

    }



    .sensfrx-collapse-btn:hover {

        background: #e5e7eb;

        color: #374151;

    }



    .sensfrx-collapse-icon {

        transition: transform 0.3s ease;

    }



    .sensfrx-card-collapsed .sensfrx-collapse-icon {

        transform: rotate(-90deg);

    }



    .sensfrx-card-body {

        max-height: 1000px;

        overflow: hidden;

        transition: max-height 0.3s ease, opacity 0.3s ease;

        opacity: 1;

    }



    .sensfrx-card-collapsed .sensfrx-card-body {

        max-height: 0;

        opacity: 0;

    }



    .sensfrx-card-collapsed {

        padding-bottom: 0;

    }



    .sensfrx-card-collapsed .sensfrx-card-header {

        margin-bottom: 0;

        padding-bottom: 0;

        border-bottom: none;

    }



    /* Disabled Card Content */

    .sensfrx-card-disabled {

        position: relative;

    }



    .sensfrx-card-disabled .sensfrx-card-body {

        opacity: 0.4;

        pointer-events: none;

        user-select: none;

    }



    .sensfrx-card-disabled .sensfrx-card-body::after {

        content: '';

        position: absolute;

        top: 0;

        left: 0;

        right: 0;

        bottom: 0;

        background: rgba(255, 255, 255, 0.7);

        backdrop-filter: blur(1px);

        z-index: 1;

    }



    .sensfrx-card-disabled .sensfrx-card-icon {

        opacity: 0.5;

    }



    .sensfrx-card-disabled .sensfrx-card-title,

    .sensfrx-card-disabled .sensfrx-card-description {

        opacity: 0.6;

    }



    /* Admin & Customer Subsection Styles */

    .sensfrx-admin-subsection,

    .sensfrx-customer-subsection {

        transition: all 0.2s ease;

    }



    .sensfrx-subsection-header {

        transition: background-color 0.2s ease;

        padding: 4px;

        margin: -4px -4px 8px -4px;

        border-radius: 6px;

    }



    .sensfrx-subsection-header:hover {

        background-color: rgba(59, 130, 246, 0.05);

    }



    .sensfrx-subsection-collapse-btn:hover {

        background: #e5e7eb !important;

        color: #374151 !important;

    }



    .sensfrx-subsection-collapsed .sensfrx-subsection-header {

        margin-bottom: 0 !important;

    }



    /* Master Toggle in Header */

    .sensfrx-master-toggle {

        flex-shrink: 0;

    }



    .sensfrx-card-header {

        display: flex;

        align-items: flex-start;

        gap: 16px;

        margin-bottom: 20px;

        padding-bottom: 20px;

        border-bottom: 2px solid #f3f4f6;

    }



    .sensfrx-card-icon {

        width: 48px;

        height: 48px;

        border-radius: 10px;

        display: flex;

        align-items: center;

        justify-content: center;

        flex-shrink: 0;

    }



    .sensfrx-card-title {

        font-size: 18px;

        font-weight: 700;

        color: #111827;

        margin: 0 0 6px 0;

    }



    .sensfrx-card-description {

        font-size: 14px;

        color: #6b7280;

        margin: 0;

        line-height: 1.5;

    }



    /* Save Button Styling */

    .sensfrx-btn-primary {

        background: linear-gradient(135deg, #0254ff 0%, #0040cc 100%);

        color: white;

        border: none;

        padding: 14px 32px;

        border-radius: 8px;

        font-size: 15px;

        font-weight: 600;

        cursor: pointer;

        display: inline-flex;

        align-items: center;

        gap: 10px;

        transition: all 0.3s ease;

        box-shadow: 0 4px 6px rgba(2, 84, 255, 0.2);

    }



    .sensfrx-btn-primary:hover {

        transform: translateY(-2px);

        box-shadow: 0 6px 12px rgba(2, 84, 255, 0.3);

    }



    .sensfrx-btn-primary:active {

        transform: translateY(0);

    }



    /* Auto-save Status */

    .sensfrx-autosave-status {

        display: flex;

        align-items: center;

        gap: 8px;

        font-size: 14px;

        color: #10b981;

        font-weight: 500;

    }



    .sensfrx-save-icon {

        width: 18px;

        height: 18px;

    }



    /* Page Header Improvements */

    .sensfrx-page-header {

        display: flex;

        justify-content: space-between;

        align-items: flex-start;

        margin-bottom: 30px;

        padding-bottom: 20px;

        border-bottom: 1px solid #e5e7eb;

    }



    .sensfrx-page-title {

        font-size: 28px;

        font-weight: 800;

        color: #111827;

        margin: 0 0 8px 0;

    }



    .sensfrx-page-subtitle {

        font-size: 15px;

        color: #6b7280;

        margin: 0;

        line-height: 1.6;

        max-width: 700px;

    }



    @media (max-width: 1200px) {

        .sensfrx-settings-grid {

            grid-template-columns: 1fr;

        }



        .sensfrx-sticky-column {

            position: relative;

            top: 0;

            max-height: none;

        }

    }



    @media (max-width: 768px) {

        .sensfrx-page-header {

            flex-direction: column;

            gap: 16px;

        }



        .sensfrx-toggle-group {

            flex-direction: column;

            align-items: flex-start;

            gap: 12px;

        }



        .sensfrx-toggle-label-wrapper {

            margin-right: 0;

        }



        .sensfrx-tooltip {

            max-width: calc(100vw - 60px);

        }

        

        .sensfrx-protection-item {

            flex-direction: column;

            gap: 16px;

        }

        

        .sensfrx-protection-icon {

            font-size: 28px;

        }

    }



    /* FIX: Allow scrolling for long Admin & Customer alert cards */

    [data-card="admin-alerts"] .sensfrx-card-body,

    [data-card="customer-alerts"] .sensfrx-card-body {

        max-height: none;          /* remove height limit */

        overflow-y: auto;          /* enable scrollbar */

        padding-right: 6px;        /* prevent scrollbar overlap */

    }



    /* Keep collapse animation working */

    .sensfrx-card-collapsed[data-card="admin-alerts"] .sensfrx-card-body,

    .sensfrx-card-collapsed[data-card="customer-alerts"] .sensfrx-card-body {

        max-height: 0;

        overflow: hidden;

    }



</style>



<script>

    // console.log("FULL POLICY OPTIONS:", <?php 

    //     echo json_encode(

    //         get_option('sensfrx_policy_options', SensFRX::default_policy_options()),

    //         JSON_PRETTY_PRINT

    //     ); 

    // ?>);

jQuery(document).ready(function($) {

    // Check license and show appropriate OFAC card

    $.ajax({

        url: sensfrxData.restUrl + 'get_license_info',

        method: 'GET',

        beforeSend: function(xhr) {

            xhr.setRequestHeader('X-WP-Nonce', sensfrxData.nonce);

        },

        success: function(response) {

            $('#ofac-premium-loading').hide();



            if (response.status === 'success' && response.data) {

                const planName = response.data.planName || response.data.plan_name || response.data.plan || 'FREE';

                const userPlan = planName.toUpperCase();



                // Check if user has PRO access (PRO, GROWTH, BUSINESS, or ENTERPRISE)

                const hasProAccess = userPlan.includes('PRO') ||

                                    userPlan.includes('GROWTH') ||

                                    userPlan.includes('BUSINESS') ||

                                    userPlan.includes('ENTERPRISE');



                if (hasProAccess) {

                    // Show PRO card

                    $('#ofac-pro-card').show();



                    // Check OFAC enabled status and update badge

                    const ofacEnabled = response.data.ofac_enabled || false;

                    const statusBadge = $('#ofac-status-badge');

                    if (ofacEnabled) {

                        statusBadge.text('Active').css({

                            'background': '#10B981',

                            'color': 'white'

                        });

                        // Auto-minimize when active - make it very compact and passive

                        $('#ofac-collapse-btn').show();

                        $('#ofac-description').hide();

                        $('#ofac-configure-btn').hide();

                        $('#ofac-collapse-icon').css('transform', 'rotate(-90deg)');

                    } else {

                        statusBadge.text('Inactive').css({

                            'background': '#6B7280',

                            'color': 'white'

                        });

                        // Keep expanded when inactive

                        $('#ofac-collapse-btn').hide();

                        $('#ofac-configure-btn').show();

                    }

                } else {

                    // Show FREE upgrade card

                    $('#ofac-free-card').show();

                }

            } else {

                // Default to showing FREE card on error

                $('#ofac-free-card').show();

            }

        },

        error: function() {

            $('#ofac-premium-loading').hide();

            $('#ofac-free-card').show();

        }

    });



    // Tooltip functionality

    $('.sensfrx-info-icon').on('click', function(e) {

        e.preventDefault();

        e.stopPropagation();



        var tooltipId = $(this).data('tooltip');

        var tooltip = $('#' + tooltipId);



        // Close all other tooltips

        $('.sensfrx-tooltip').not(tooltip).removeClass('show');



        // Toggle this tooltip

        tooltip.toggleClass('show');

    });



    // Close tooltips when clicking outside

    $(document).on('click', function(e) {

        if (!$(e.target).closest('.sensfrx-info-icon').length) {

            $('.sensfrx-tooltip').removeClass('show');

        }

    });



    // Prevent tooltip from closing when clicking inside it

    $('.sensfrx-tooltip').on('click', function(e) {

        e.stopPropagation();

    });



    // fetching review count

    fetch(sensfrxData.restUrl + 'get_sensfrx_review_count', {

        method: 'GET',

        headers: {

            'Content-Type': 'application/json'

        }

    })

    .then(response => response.json())

    .then(data => {

        if (data.status === 'success') {

            const badge = document.querySelector('.sensfrx-nav-badge');

            if (badge) {

                badge.textContent = data.reviewCount || 0;

            }

        }

    })

    .catch(error => console.error('Error fetching review count:', error));



    // Combined toggle change handler (single source of truth)

    $('.sensfrx-combined-toggle').on('change', function() {

        const $toggle = $(this);

        const combinedType = $toggle.data('combined');

        const isChecked = $toggle.prop('checked');

        const $item = $toggle.closest('.sensfrx-protection-item');



        // If this is the MASTER toggle and user is turning it OFF, confirm and possibly revert.

        if (combinedType === 'sensfrx_master_fraud' && !isChecked) {

            const confirmed = confirm('Disabling Master Fraud Protection will turn off all fraud detection features. Are you sure?');

            if (!confirmed) {

                // Revert UI and stop further processing

                $toggle.prop('checked', true);

                // no need to update hidden inputs because state unchanged

                return;

            }

        }



        // Update hidden form inputs

        if (combinedType === 'account_takeover') {

            $item.find('input[data-key="sensfrx_login_fraud"]').val(isChecked ? '1' : '0');

            $item.find('input[data-key="sensfrx_reset_password_fraud"]').val(isChecked ? '1' : '0');

        } else if (combinedType === 'transaction_fraud') {

            $item.find('input[data-key="sensfrx_before_payment_fraud"]').val(isChecked ? '1' : '0');

            $item.find('input[data-key="sensfrx_after_payment_fraud"]').val(isChecked ? '1' : '0');

        } else {

            // Direct mapping for master, bot, new_account, etc.

            // combinedType equals the actual data-key used in the hidden input

            $item.find('input[data-key="' + combinedType + '"]').val(isChecked ? '1' : '0');

        }



        // If this is master toggle, enable/disable child controls immediately

        if (combinedType === 'sensfrx_master_fraud') {

            toggleProtectionControls(isChecked);

        }



        // Auto-save settings

        autoSaveSettings();

    });

    

    // Function to enable/disable all protection toggles except master

    function toggleProtectionControls(enabled) {

        $('.sensfrx-protection-item[data-protection-type="child"]').each(function() {

            const $item = $(this);

            const $toggle = $item.find('.sensfrx-combined-toggle');

            const $toggleSwitch = $item.find('.sensfrx-toggle-switch');

            

            if (enabled) {

                // Enable the toggle

                $toggle.prop('disabled', false);

                $toggleSwitch.css('opacity', '1');

                $item.css('opacity', '1');

            } else {

                // Disable the toggle

                $toggle.prop('disabled', true);

                $toggleSwitch.css('opacity', '0.5');

                $item.css('opacity', '0.6');

            }

        });

    }

    

    // Note: autoSaveSettings() is now a global function defined outside this ready block

    

    // Initialize: Check master toggle state on page load

    const masterToggle = $('.sensfrx-combined-toggle[data-combined="sensfrx_master_fraud"]');

    if (masterToggle.length && !masterToggle.prop('checked')) {

        toggleProtectionControls(false);

    }

    

    // Auto-save functionality for email alerts and other toggles

    $('#sensfrx-fraud-protection-form input[type="checkbox"]:not(.sensfrx-combined-toggle)').on('change', function() {

        // Don't auto-save for master toggles as they handle it themselves

        if (!$(this).closest('.sensfrx-master-toggle').length) {

            autoSaveSettings();

        }

    });

    

    // Admin alerts no longer have master toggles - they are cloud-managed

    // Individual toggles sync directly from the API

    

    // Admin alert master toggles removed - individual toggles work independently

    

    // Listen for changes on customer alerts master toggle

    $('.sensfrx-customer-master-toggle').on('change', function() {

        const isEnabled = $(this).prop('checked');

        const cardId = $(this).data('section');        

        // Update hidden input value

        const hiddenInput = $('input[type="hidden"][data-key="sensfrx_customer_fraud_alerts"]');

        hiddenInput.val(isEnabled ? '1' : '0');

        

        // Toggle card content (enable/disable child toggles)

        toggleCardContent(cardId, isEnabled);

    });

    

    // Admin alert initialization removed - toggles sync directly from API

});



// Global function to auto-save settings via AJAX

function autoSaveSettings() {

    jQuery('#sensfrx-save-text').text('Saving...');

    jQuery('#sensfrx-save-status').css('color', '#f59e0b');

    

    clearTimeout(window.saveTimeout);

    window.saveTimeout = setTimeout(function() {

        // Collect all form data

        const formData = {};

        

        // Get all hidden inputs and regular checkboxes

        jQuery('#sensfrx-fraud-protection-form input[type="hidden"].sensfrx-hidden-checkbox').each(function() {

            const key = jQuery(this).attr('data-key');

            const value = jQuery(this).val();

            formData[key] = value;

        });

        

        // Get email alert checkboxes

        jQuery('#sensfrx-fraud-protection-form input[type="checkbox"]:not(.sensfrx-combined-toggle)').each(function() {

            const name = jQuery(this).attr('name');

            if (name && name.includes('sensfrx_policy_options[')) {

                const key = name.replace('sensfrx_policy_options[', '').replace(']', '');

                formData[key] = jQuery(this).prop('checked') ? '1' : '0';

            }

        });

        

        // Get email and text inputs

        jQuery('#sensfrx-fraud-protection-form input[type="email"], #sensfrx-fraud-protection-form input[type="text"]').each(function() {

            const name = jQuery(this).attr('name');

            if (name && name.includes('sensfrx_policy_options[')) {

                const key = name.replace('sensfrx_policy_options[', '').replace(']', '');

                formData[key] = jQuery(this).val();

            }

        });

        

        // Make AJAX request to save

        jQuery.ajax({

            url: ajaxurl, // WordPress AJAX URL

            type: 'POST',

            data: {

                action: 'sensfrx_auto_save_settings',

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

                settings: formData

            },

            success: function(response) {

                if (response.success) {

                    jQuery('#sensfrx-save-text').text('All changes saved');

                    jQuery('#sensfrx-save-status').css('color', '#10b981');

                } else {

                    jQuery('#sensfrx-save-text').text('Save failed');

                    jQuery('#sensfrx-save-status').css('color', '#ef4444');

                    console.error('Save failed:', response.data);

                }

            },

            error: function(xhr, status, error) {

                jQuery('#sensfrx-save-text').text('Save failed');

                jQuery('#sensfrx-save-status').css('color', '#ef4444');

                console.error('AJAX error:', error);

            }

        });

    }, 1000); // Wait 1 second after last change before saving

}



// Toggle card collapse/expand

function toggleCard(cardId) {

    const card = jQuery('[data-card="' + cardId + '"]');

    card.toggleClass('sensfrx-card-collapsed');

    

    // Save collapsed state to localStorage

    const isCollapsed = card.hasClass('sensfrx-card-collapsed');

    localStorage.setItem('sensfrx_card_' + cardId, isCollapsed ? 'collapsed' : 'expanded');

}



// Toggle subsection collapse/expand (for admin alert subsections)

function toggleSubsection(subsectionId) {

    const subsection = jQuery('[data-subsection="' + subsectionId + '"]');

    const subsectionBody = jQuery('[data-subsection-body="' + subsectionId + '"]');

    const icon = subsection.find('.sensfrx-subsection-collapse-icon');

    

    subsection.toggleClass('sensfrx-subsection-collapsed');

    const isCollapsed = subsection.hasClass('sensfrx-subsection-collapsed');

    

    if (isCollapsed) {

        subsectionBody.css({

            'max-height': '0',

            'opacity': '0'

        });

        icon.css('transform', 'rotate(-90deg)');

    } else {

        subsectionBody.css({

            'max-height': '500px',

            'opacity': '1'

        });

        icon.css('transform', 'rotate(0deg)');

    }

    

    // Save state to localStorage

    localStorage.setItem('sensfrx_subsection_' + subsectionId, isCollapsed ? 'collapsed' : 'expanded');

}



// Toggle card content enabled/disabled state

function toggleCardContent(cardId, isEnabled) {

    const card = jQuery('[data-card="' + cardId + '"]');

    

    if (isEnabled) {

        card.removeClass('sensfrx-card-disabled');

        

        // Turn ON all child toggles when master is turned ON

        // Support both toggle types: .sensfrx-toggle-item (admin alerts) and .sensfrx-toggle-group (customer alerts)

        card.find('.sensfrx-toggle-item, .sensfrx-toggle-group').each(function() {

            const $item = jQuery(this);

            

            // Find the visible checkbox

            const $checkbox = $item.find('input[type="checkbox"]').first();

            // Find hidden input (only exists in admin alerts)

            const $hiddenInput = $item.find('input[type="hidden"].sensfrx-hidden-checkbox');

            

            if ($checkbox.length) {

                // Turn ON the visible checkbox

                $checkbox.prop('checked', true);

                $checkbox.prop('disabled', false);

                

                // If there's a hidden input (admin alerts only), update it too

                if ($hiddenInput.length) {

                    $hiddenInput.val('1');

                }

                

                // Visual feedback - fully visible

                $item.css('opacity', '1');

            }

        });

    } else {

        card.addClass('sensfrx-card-disabled');

        

        // Turn OFF all child toggles when master is turned OFF

        // Support both toggle types: .sensfrx-toggle-item (admin alerts) and .sensfrx-toggle-group (customer alerts)

        card.find('.sensfrx-toggle-item, .sensfrx-toggle-group').each(function() {

            const $item = jQuery(this);

            

            // Find the visible checkbox

            const $checkbox = $item.find('input[type="checkbox"]').first();

            // Find hidden input (only exists in admin alerts)

            const $hiddenInput = $item.find('input[type="hidden"].sensfrx-hidden-checkbox');

            

            if ($checkbox.length) {

                // Turn OFF the visible checkbox

                $checkbox.prop('checked', false);

                $checkbox.prop('disabled', true);

                

                // If there's a hidden input (admin alerts only), update it too

                if ($hiddenInput.length) {

                    $hiddenInput.val('0');

                }

                

                // Visual feedback - grayed out

                $item.css('opacity', '0.5');

            }

        });

    }

    

    // Auto-save settings

    // For customer alerts: checkboxes are read directly by autoSaveSettings()

    // For admin alerts: hidden inputs are read

    autoSaveSettings();

}



// Manual refresh alert settings (fetch latest settings from SensFRX dashboard)

function syncFromCloud() {

    jQuery('#sync-status').text('Refreshing settings...').css('color', '#f59e0b');

    jQuery('#sync-from-cloud-btn').prop('disabled', true);

    jQuery('#sync-icon').css('transform', 'rotate(360deg)');

    

    jQuery.ajax({

        url: ajaxurl,

        type: 'POST',

        data: {

            action: 'sensfrx_sync_from_cloud',

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

        },

        success: function(response) {

            if (response.success) {

                jQuery('#sync-status').text('✓ Settings updated! Reloading...').css('color', '#10b981');

                setTimeout(function() {

                    location.reload();

                }, 1000);

            } else {

                jQuery('#sync-status').text('✗ ' + (response.data?.message || 'Refresh failed')).css('color', '#ef4444');

                jQuery('#sync-from-cloud-btn').prop('disabled', false);

                jQuery('#sync-icon').css('transform', 'rotate(0deg)');

            }

        },

        error: function(xhr, status, error) {

            jQuery('#sync-status').text('✗ Connection error').css('color', '#ef4444');

            jQuery('#sync-from-cloud-btn').prop('disabled', false);

            jQuery('#sync-icon').css('transform', 'rotate(0deg)');

            console.error('Refresh error:', error);

        }

    });

}



// Restore card states from localStorage on page load

jQuery(document).ready(function($) {

    $('.sensfrx-collapsible-card').each(function() {

        const cardId = $(this).data('card');

        const savedState = localStorage.getItem('sensfrx_card_' + cardId);

        

        // Admin alerts and Customer alerts should be expanded by default

        if (cardId === 'admin-alerts' || cardId === 'customer-alerts') {

            // Only collapse if explicitly saved as collapsed

            if (savedState === 'collapsed') {

                $(this).addClass('sensfrx-card-collapsed');

            } else {

                $(this).removeClass('sensfrx-card-collapsed');

            }

        } else {

            // Other cards: collapsed by default unless saved as expanded

            if (savedState === 'expanded') {

                $(this).removeClass('sensfrx-card-collapsed');

            } else if (savedState === 'collapsed' || !savedState) {

                $(this).addClass('sensfrx-card-collapsed');

            }

        }

    });



    // Initialize card disabled states based on master toggle values

    $('.sensfrx-collapsible-card').each(function() {

        const cardId = $(this).data('card');

        const masterToggle = $(this).find('.sensfrx-master-toggle input[type="checkbox"]');

        

        if (masterToggle.length) {

            const isEnabled = masterToggle.prop('checked');

            if (!isEnabled) {

                $(this).addClass('sensfrx-card-disabled');

                

                // Disable and gray out all child toggles

                $(this).find('.sensfrx-card-body .sensfrx-toggle-item').each(function() {

                    $(this).find('input[type="checkbox"]').prop('disabled', true);

                    $(this).css('opacity', '0.5');

                });

            }

        }

    });



    // Also get admin email field for user alerts

    $('#sensfrx-fraud-protection-form input[type="email"]').on('input', function() {

        autoSaveSettings();

    });



    // Restore subsection states from localStorage on page load

    $('.sensfrx-admin-subsection, .sensfrx-customer-subsection').each(function() {

        const subsectionId = $(this).data('subsection');

        const savedState = localStorage.getItem('sensfrx_subsection_' + subsectionId);

        

        // All subsections collapsed by default unless saved as expanded

        if (savedState === 'expanded') {

            const subsectionBody = $('[data-subsection-body="' + subsectionId + '"]');

            const icon = $(this).find('.sensfrx-subsection-collapse-icon');

            

            $(this).removeClass('sensfrx-subsection-collapsed');

            subsectionBody.css({

                'max-height': '500px',

                'opacity': '1'

            });

            icon.css('transform', 'rotate(0deg)');

        }

    });

});



// Toggle OFAC card collapse/expand

function toggleOfacCard() {

    const description = jQuery('#ofac-description');

    const configureBtn = jQuery('#ofac-configure-btn');

    const icon = jQuery('#ofac-collapse-icon');



    if (description.is(':visible')) {

        // Collapse - hide description and configure button

        description.slideUp(200);

        configureBtn.fadeOut(200);

        icon.css('transform', 'rotate(-90deg)');

    } else {

        // Expand - show description and configure button

        description.slideDown(200);

        configureBtn.fadeIn(200);

        icon.css('transform', 'rotate(0deg)');

    }

}

</script>

