<?php

/**

 * Fraud Intelligence - Activity Analysis & Risk Monitoring

 * Comprehensive fraud detection dashboard with filtering and analytics

 *

 * @package    SensFRX

 * @subpackage SensFRX/admin/partials

 */



// If this file is called directly, abort.

if (!defined('WPINC')) {

    die;

}

?>



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

    <!-- Navigation -->

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



    <!-- Main Content -->

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



        <!-- Fraud Intelligence - Activity Analysis Dashboard -->

        <div class="fmc-wrapper" style="width: 100%; margin: 20px 0;">



            <!-- Header Dashboard with Statistics -->

            <div class="fmc-header" style="background: linear-gradient(135deg, #10367B 0%, #764ba2 100%); border-radius: 16px; padding: 30px; margin-bottom: 30px; color: white; box-shadow: 0 10px 40px rgba(0,0,0,0.15);">

                <div class="fmc-title" style="font-size: 28px; font-weight: 600; margin-bottom: 24px; display: flex; align-items: center; gap: 12px;">

                    <span style="font-size: 32px;">🧠</span>

                    <span>Fraud Intelligence</span>

                    <span style="margin-left: auto; font-size: 14px; opacity: 0.9;"><?php echo esc_html( 'Last updated: ' . date_i18n('F j, Y g:i A') ); ?></span>

                </div>



                <!-- Statistics Grid (Dynamic - Calculated from filtered data) -->

                <div class="fmc-stats" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">



                    <div class="fmc-stat" style="background: rgba(255,255,255,0.95); padding: 20px; border-radius: 12px;">

                        <div class="fmc-stat-value" id="stat-total-cases" style="font-size: 32px; font-weight: 700; color: #1a202c; margin-bottom: 8px;">

                            --

                        </div>

                        <div class="fmc-stat-label" style="font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">Total Cases</div>

                    </div>



                    <div class="fmc-stat" style="background: rgba(255,255,255,0.95); padding: 20px; border-radius: 12px;">

                        <div class="fmc-stat-value" id="stat-blocked-cases" style="font-size: 32px; font-weight: 700; color: #ef4444; margin-bottom: 8px;">

                            --

                        </div>

                        <div class="fmc-stat-label" style="font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">Blocked</div>

                    </div>



                    <div class="fmc-stat" style="background: rgba(255,255,255,0.95); padding: 20px; border-radius: 12px;">

                        <div class="fmc-stat-value" id="stat-saved-amount" style="font-size: 32px; font-weight: 700; color: #10b981; margin-bottom: 8px;">

                            --

                        </div>

                        <div class="fmc-stat-label" style="font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">Saved</div>

                    </div>



                    <div class="fmc-stat" style="background: rgba(255,255,255,0.95); padding: 20px; border-radius: 12px;">

                        <div class="fmc-stat-value" id="stat-review-cases" style="font-size: 32px; font-weight: 700; color: #f59e0b; margin-bottom: 8px;">

                            --

                        </div>

                        <div class="fmc-stat-label" style="font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">Review</div>

                    </div>

                </div>

            </div>



            <!-- Advanced Filter Panel -->

            <div class="fmc-filters" style="background: white; border-radius: 16px; padding: 24px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); margin-bottom: 24px;">



                <!-- Date Range Filter -->

                <div class="fmc-filter-row" style="margin-bottom: 20px;">

                    <label style="font-size: 12px; font-weight: 600; text-transform: uppercase; color: #64748b; letter-spacing: 0.5px; margin-bottom: 10px; display: block;">Time Period</label>

                    <div class="fmc-date-pills" style="display: flex; gap: 8px; padding: 4px; background: #f1f5f9; border-radius: 10px;">

                        <button class="fmc-pill" data-range="today" style="padding: 10px 16px; background: transparent; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; color: #64748b;">Today</button>

                        <button class="fmc-pill" data-range="yesterday" style="padding: 10px 16px; background: transparent; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; color: #64748b;">Yesterday</button>

                        <button class="fmc-pill active" data-range="7days" style="padding: 10px 16px; background: white; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; color: #10367B; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">This Week</button>

                        <button class="fmc-pill" data-range="30days" style="padding: 10px 16px; background: transparent; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; color: #64748b;">This Month</button>

                        <button class="fmc-pill" data-range="90days" style="padding: 10px 16px; background: transparent; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; color: #64748b;">3 Months</button>

                        <!-- <button class="fmc-pill" data-range="custom" style="padding: 10px 16px; background: transparent; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; color: #64748b;">Custom</button> -->

                    </div>



                    <!-- Custom Date Range (hidden by default) -->

                    <div id="custom-date-range" style="display: none; margin-top: 12px; padding: 12px; background: #f9fafb; border-radius: 8px;">

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

                            <input type="date" id="date-from" style="padding: 8px 12px; border: 1px solid #e2e8f0; border-radius: 6px;">

                            <span style="color: #64748b;">to</span>

                            <input type="date" id="date-to" style="padding: 8px 12px; border: 1px solid #e2e8f0; border-radius: 6px;">

                            <button onclick="applyCustomDateRange()" style="padding: 8px 16px; background: #10367B; color: white; border: none; border-radius: 6px; cursor: pointer;">Apply</button>

                        </div>

                    </div>

                </div>



                <!-- Risk Level Filter -->

                <div class="fmc-filter-row" style="margin-bottom: 20px;">

                    <label style="font-size: 12px; font-weight: 600; text-transform: uppercase; color: #64748b; letter-spacing: 0.5px; margin-bottom: 10px; display: block;">Risk Level</label>

                    <div class="fmc-risk-cards" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px;">

                        <div class="fmc-risk-card fmc-risk-high" data-risk="high" style="padding: 20px; border: 2px solid #e2e8f0; border-left: 4px solid #ef4444; border-radius: 12px; text-align: center; cursor: pointer; background: white; transition: all 0.2s;">

                            <div style="width: 48px; height: 48px; margin: 0 auto 12px; background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);"></div>

                            <div style="font-weight: 600; font-size: 15px; margin-bottom: 4px; color: #1f2937;">High Risk</div>

                            <div style="font-size: 12px; color: #64748b;">Score: 60-100</div>

                        </div>

                        <div class="fmc-risk-card fmc-risk-medium" data-risk="medium" style="padding: 20px; border: 2px solid #e2e8f0; border-left: 4px solid #f59e0b; border-radius: 12px; text-align: center; cursor: pointer; background: white; transition: all 0.2s;">

                            <div style="width: 48px; height: 48px; margin: 0 auto 12px; background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);"></div>

                            <div style="font-weight: 600; font-size: 15px; margin-bottom: 4px; color: #1f2937;">Medium Risk</div>

                            <div style="font-size: 12px; color: #64748b;">Score: 30-59</div>

                        </div>

                        <div class="fmc-risk-card fmc-risk-low" data-risk="low" style="padding: 20px; border: 2px solid #e2e8f0; border-left: 4px solid #10b981; border-radius: 12px; text-align: center; cursor: pointer; background: white; transition: all 0.2s;">

                            <div style="width: 48px; height: 48px; margin: 0 auto 12px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);"></div>

                            <div style="font-weight: 600; font-size: 15px; margin-bottom: 4px; color: #1f2937;">Low Risk</div>

                            <div style="font-size: 12px; color: #64748b;">Score: 0-29</div>

                        </div>

                    </div>

                </div>



                <!-- Event Type Filter -->

                <div class="fmc-filter-row" style="margin-bottom: 20px;">

                    <label style="font-size: 12px; font-weight: 600; text-transform: uppercase; color: #64748b; letter-spacing: 0.5px; margin-bottom: 10px; display: block;">Event Type</label>

                    <div class="fmc-event-types" style="display: flex; flex-wrap: wrap; gap: 10px;">

                        <label class="fmc-checkbox" style="display: flex; align-items: center; padding: 10px 14px; background: white; border: 2px solid #e2e8f0; border-left: 3px solid #8b5cf6; border-radius: 10px; cursor: pointer; transition: all 0.2s;">

                            <div style="width: 28px; height: 28px; margin-right: 10px; background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); border-radius: 50%; box-shadow: 0 2px 8px rgba(139, 92, 246, 0.25); flex-shrink: 0;"></div>

                            <input type="checkbox" value="payment" checked style="width: 16px; height: 16px; cursor: pointer; accent-color: #8b5cf6; margin-right: 8px;">

                            <span style="font-weight: 500; font-size: 14px; color: #1f2937;">Orders</span>

                        </label>

                        <label class="fmc-checkbox" style="display: flex; align-items: center; padding: 10px 14px; background: white; border: 2px solid #e2e8f0; border-left: 3px solid #3b82f6; border-radius: 10px; cursor: pointer; transition: all 0.2s;">

                            <div style="width: 28px; height: 28px; margin-right: 10px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); border-radius: 50%; box-shadow: 0 2px 8px rgba(59, 130, 246, 0.25); flex-shrink: 0;"></div>

                            <input type="checkbox" value="login" checked style="width: 16px; height: 16px; cursor: pointer; accent-color: #3b82f6; margin-right: 8px;">

                            <span style="font-weight: 500; font-size: 14px; color: #1f2937;">Login Attempts</span>

                        </label>

                        <label class="fmc-checkbox" style="display: flex; align-items: center; padding: 10px 14px; background: white; border: 2px solid #e2e8f0; border-left: 3px solid #06b6d4; border-radius: 10px; cursor: pointer; transition: all 0.2s;">

                            <div style="width: 28px; height: 28px; margin-right: 10px; background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); border-radius: 50%; box-shadow: 0 2px 8px rgba(6, 182, 212, 0.25); flex-shrink: 0;"></div>

                            <input type="checkbox" value="registration" checked style="width: 16px; height: 16px; cursor: pointer; accent-color: #06b6d4; margin-right: 8px;">

                            <span style="font-weight: 500; font-size: 14px; color: #1f2937;">Registration</span>

                        </label>

                        <!-- <label class="fmc-checkbox" style="display: flex; align-items: center; padding: 10px 14px; background: white; border: 2px solid #e2e8f0; border-left: 3px solid #ec4899; border-radius: 10px; cursor: pointer; transition: all 0.2s;">

                            <div style="width: 28px; height: 28px; margin-right: 10px; background: linear-gradient(135deg, #ec4899 0%, #db2777 100%); border-radius: 50%; box-shadow: 0 2px 8px rgba(236, 72, 153, 0.25); flex-shrink: 0;"></div>

                            <input type="checkbox" value="account_update" checked style="width: 16px; height: 16px; cursor: pointer; accent-color: #ec4899; margin-right: 8px;">

                            <span style="font-weight: 500; font-size: 14px; color: #1f2937;">Account Updates</span>

                        </label> -->

                    </div>

                </div>



                <!-- Search Bar -->

                <div class="fmc-filter-row" style="margin-bottom: 20px;">

                    <label style="font-size: 12px; font-weight: 600; text-transform: uppercase; color: #64748b; letter-spacing: 0.5px; margin-bottom: 10px; display: block;"> Search</label>

                    <div style="position: relative;">

                        <span style="position: absolute; left: 16px; top: 12px; color: #94a3b8;"></span>

                        <input type="text" id="fmc-search" class="fmc-search" placeholder="Search by USER, IP or Event type..." style="width: 100%; padding: 12px 16px 12px 44px; border: 2px solid #e2e8f0; border-radius: 10px; font-size: 14px;">

                    </div>

                </div>



                <!-- Action Buttons -->

                <div class="fmc-filter-row" style="display: flex; justify-content: space-between; align-items: center;">

                    

                    <button id="fmc-reset-filters" style="padding: 10px 24px; background: transparent; color: #64748b; border: 1px solid #e2e8f0; border-radius: 8px; font-weight: 500; cursor: pointer; transition: all 0.2s;">

                        Reset All

                    </button>

                    <button class="fmc-export-btn" style="padding: 10px 20px; background: #10b981; color: white; border: none; border-radius: 8px; font-weight: 500; cursor: pointer; transition: all 0.2s;">

                         Export Report

                    </button>

                </div>

            </div>

        </div>



        <!-- Fraud Cases Table (Original) -->

        <div class="sensfrx-card" style="padding: 0; overflow: hidden;">

            <div id="fraud-list-loading" style="text-align: center; padding: 60px 20px; color: #666;">

                <div class="sensfrx-spinner" style="width: 40px; height: 40px; border: 4px solid #f3f4f6; border-top-color: #047857; border-radius: 50%; margin: 0 auto 16px; animation: sensfrx-spin 1s linear infinite;"></div>

                Loading fraud cases...

            </div>



            <div id="fraud-list-content" style="display: none;">

                <table class="sensfrx-table" style="width: 100%; border-collapse: collapse;">

                    <thead style="background: #f9fafb; border-bottom: 1px solid #e5e7eb;">

                        <tr>

                            <th style="padding: 12px 16px; text-align: left; font-weight: 600; font-size: 12px; color: #6b7280; text-transform: uppercase;">Timestamp</th>

                            <th style="padding: 12px 16px; text-align: left; font-weight: 600; font-size: 12px; color: #6b7280; text-transform: uppercase;">Event Type</th>

                            <th style="padding: 12px 16px; text-align: left; font-weight: 600; font-size: 12px; color: #6b7280; text-transform: uppercase;">User/IP</th>

                            <th style="padding: 12px 16px; text-align: left; font-weight: 600; font-size: 12px; color: #6b7280; text-transform: uppercase;">Risk Score</th>

                            <th style="padding: 12px 16px; text-align: left; font-weight: 600; font-size: 12px; color: #6b7280; text-transform: uppercase;">Status</th>

                            <th style="padding: 12px 16px; text-align: left; font-weight: 600; font-size: 12px; color: #6b7280; text-transform: uppercase;">Actions</th>

                        </tr>

                    </thead>

                    <tbody id="fraud-list-tbody">

                        <!-- Populated by JavaScript -->

                    </tbody>

                </table>



                <!-- Pagination Controls -->

                <div id="fraud-pagination" style="display: none; margin-top: 24px; padding: 20px 24px; border-top: 1px solid #e5e7eb; background: #fafbfc;">

                    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">

                        <!-- Left: Showing info -->

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

                            <div id="pagination-info" style="font-size: 14px; color: #6B7280;">

                                Showing <strong id="page-start">1</strong>-<strong id="page-end">50</strong> of <strong id="total-items">0</strong>

                            </div>

                        <select id="items-per-page" style="padding: 6px 10px; border: 1.5px solid #E5E7EB; border-radius: 6px; font-size: 14px; color: #374151; cursor: pointer;">

                            <option value="10" selected>10 per page</option>

                            <option value="25">25 per page</option>

                            <option value="50">50 per page</option>

                            <option value="100">100 per page</option>

                        </select>

                        </div>

                        

                        <!-- Right: Page controls -->

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

                            <button id="page-prev" style="padding: 8px 14px; background: white; border: 1.5px solid #E5E7EB; border-radius: 6px; font-size: 14px; font-weight: 500; color: #374151; cursor: pointer; display: flex; align-items: center; gap: 4px;" disabled>

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

                                    <path d="M10 12L6 8l4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                </svg>

                                Previous

                            </button>

                            

                            <div id="page-numbers" style="display: flex; gap: 4px;">

                                <!-- Page numbers will be inserted here -->

                            </div>

                            

                            <button id="page-next" style="padding: 8px 14px; background: white; border: 1.5px solid #E5E7EB; border-radius: 6px; font-size: 14px; font-weight: 500; color: #374151; cursor: pointer; display: flex; align-items: center; gap: 4px;">

                                Next

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

                                    <path d="M6 12l4-4-4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                                </svg>

                            </button>

                        </div>

                    </div>

                </div>

            </div>



            <div id="fraud-list-empty" style="display: none; text-align: center; padding: 60px 20px;">

                <svg width="80" height="80" viewBox="0 0 80 80" fill="none" style="margin-bottom: 16px;">

                    <circle cx="40" cy="40" r="35" fill="#f0fdf4"/>

                    <path d="M40 25v30M25 40h30" stroke="#047857" stroke-width="3" stroke-linecap="round"/>

                </svg>

                <h3 style="margin: 0 0 8px; font-size: 18px; font-weight: 600; color: #1a1a1a;">No fraud cases detected</h3>

                <p style="margin: 0; color: #666; font-size: 14px;">Your site is protected and no suspicious activity has been detected.</p>

            </div>

        </div>

    </div>

</div>



<style>

    @keyframes sensfrx-spin {

        to { transform: rotate(360deg); }

    }



    .sensfrx-table tbody tr {

        border-bottom: 1px solid #e5e7eb;

        transition: background-color 0.15s;

    }



    .sensfrx-table tbody tr:hover {

        background-color: #f9fafb;

    }



    .sensfrx-risk-badge {

        display: inline-block;

        padding: 4px 12px;

        border-radius: 12px;

        font-size: 12px;

        font-weight: 600;

    }



    .sensfrx-risk-high {

        background: #fef2f2;

        color: #dc2626;

    }



    .sensfrx-risk-medium {

        background: #fef3c7;

        color: #f59e0b;

    }



    .sensfrx-risk-low {

        background: #f0fdf4;

        color: #047857;

    }



    .sensfrx-status-badge {

        display: inline-block;

        padding: 4px 12px;

        border-radius: 12px;

        font-size: 12px;

        font-weight: 600;

    }



    .sensfrx-status-blocked {

        background: #fef2f2;

        color: #dc2626;

    }



    .sensfrx-status-allowed {

        background: #f0fdf4;

        color: #047857;

    }



    .sensfrx-status-pending {

        background: #f0f9ff;

        color: #0284c7;

    }



    /* FMC Additional Styles */

    .fmc-pill:hover {

        transform: translateY(-1px);

        background: rgba(255,255,255,0.5) !important;

    }



    .fmc-risk-card:hover {

        transform: translateY(-2px);

        box-shadow: 0 4px 12px rgba(0,0,0,0.1);

    }



    .fmc-export-btn:hover {

        background: #059669 !important;

        transform: translateY(-1px);

    }



    .fmc-apply-btn:hover {

        background: #5a67d8 !important;

        transform: translateY(-1px);

    }



    .fmc-search:focus {

        outline: none;

        border-color: #10367B !important;

        box-shadow: 0 0 0 3px rgba(102,126,234,0.1) !important;

    }



    .fmc-checkbox:hover {

        background: #f9fafb !important;

        border-color: #10367B !important;

    }



    .fmc-checkbox input[type="checkbox"] {

        width: 18px !important;

        height: 18px !important;

        cursor: pointer !important;

        margin-right: 10px !important;

        flex-shrink: 0;

        accent-color: #10367B;

    }



    .fmc-checkbox input[type="checkbox"]:checked + span {

        color: #10367B;

        font-weight: 600;

    }



    /* Pagination Styles */

    #fraud-pagination button {

        transition: all 0.2s ease;

    }



    #fraud-pagination button:hover:not(:disabled) {

        background: #F3F4F6 !important;

        border-color: #10367B !important;

        transform: translateY(-1px);

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

    }



    #fraud-pagination button:disabled {

        opacity: 0.5;

        cursor: not-allowed !important;

    }



    #fraud-pagination button:disabled:hover {

        transform: none !important;

        box-shadow: none !important;

    }



    #items-per-page {

        transition: all 0.2s ease;

    }



    #items-per-page:hover {

        border-color: #10367B;

    }



    #items-per-page:focus {

        outline: none;

        border-color: #10367B;

        box-shadow: 0 0 0 3px rgba(16, 54, 123, 0.1);

    }



    .fmc-export-btn {

        background: #10b981;

        color: white;

    }



</style>



<script>

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

    // Initialize the FMC

    initializeFMC();

    

    // Initialize pagination events

    initPaginationEvents();



    // Load initial fraud cases

    loadFraudCasesWithFilters();

});

let allFraudCases = []; // store initially loaded data



// Pagination state

let currentPage = 1;

let itemsPerPage = 10;

let totalPages = 1;

let currentDisplayData = [];



function initializeFMC() {

    const $ = jQuery;



    // Date Range Pills

    $('.fmc-pill').on('click', function() {

        $('.fmc-pill').css({

            'background': 'transparent',

            'color': '#64748b',

            'box-shadow': 'none'

        }).removeClass('active');



        $(this).css({

            'background': 'white',

            'color': '#10367B',

            'box-shadow': '0 2px 8px rgba(0,0,0,0.1)'

        }).addClass('active');



        const range = $(this).data('range');



        if (range === 'custom') {

            $('#custom-date-range').slideDown();

        } else {

            $('#custom-date-range').slideUp();

        }

        loadFraudCasesWithFilters();

    });



    // Risk Level Cards

    $('.fmc-risk-card').on('click', function() {

        const isActive = $(this).hasClass('active');



        if (isActive) {

            $(this).removeClass('active').css({

                'border-color': '#e2e8f0',

                'background': 'white'

            });

        } else {

            $(this).addClass('active').css({

                'border-color': '#10367B',

                'background': '#e7e9f8'

            });

        }

        loadFraudCasesWithFilters();

    });



    // Event Type Checkboxes - Auto-trigger on change

    $('.fmc-checkbox input').on('change', function() {

        loadFraudCasesWithFilters();

    });



    // Search - real-time with delay

    $('#fmc-search').off('keyup input').on('keyup input', function() {

        clearTimeout(window.searchTimeout);

        window.searchTimeout = setTimeout(function() {

            // loadFraudCasesWithFilters();

            filterLocalFraudCases(); // only filter from loaded list

        }, 500);

    });



    // Reset Filters

    $('#fmc-reset-filters').on('click', function() {

        // Reset date range

        $('.fmc-pill').removeClass('active').css({

            'background': 'transparent',

            'color': '#64748b',

            'box-shadow': 'none'

        });

        $('.fmc-pill[data-range="7days"]').addClass('active').css({

            'background': 'white',

            'color': '#10367B',

            'box-shadow': '0 2px 8px rgba(0,0,0,0.1)'

        });



        // Reset risk levels - all deselected by default

        $('.fmc-risk-card').removeClass('active').css({

            'border-color': '#e2e8f0',

            'background': 'white'

        });



        // Reset event types

        $('.fmc-checkbox input').prop('checked', true);



        // Clear search

        $('#fmc-search').val('');



        // Reload data

        loadFraudCasesWithFilters();

    });



    // Search on Enter

    $('#fmc-search').on('keypress', function(e) {

        if (e.which === 13) {

            // loadFraudCasesWithFilters();

            filterLocalFraudCases();

        }

    });



    // Export functionality

    $('.fmc-export-btn').on('click', function() {

        exportFraudReport();

    });

}



function filterLocalFraudCases() {

    const $ = jQuery;

    const searchQuery = $('#fmc-search').val().toLowerCase();

    

    // Reset to page 1 when searching

    currentPage = 1;



    const filtered = allFraudCases.filter(item =>

        item.event_type?.toLowerCase().includes(searchQuery) ||

        item.ip_address?.toLowerCase().includes(searchQuery) ||

        item.user?.toLowerCase().includes(searchQuery)

    );

    

    // Update statistics for filtered results

    updateStatistics(filtered);

    renderFraudCases(filtered);

}



function loadFraudCasesWithFilters() {

    const $ = jQuery;

    

    // Reset to page 1 when filters change

    currentPage = 1;



    // Gather filter values

    const dateRange = $('.fmc-pill.active').data('range');

    const riskLevels = [];

    $('.fmc-risk-card.active').each(function() {

        riskLevels.push($(this).data('risk'));

    });

    const eventTypes = [];

    $('.fmc-checkbox input:checked').each(function() {

        eventTypes.push($(this).val());

    });

    const searchQuery = $('#fmc-search').val();



    $('#fraud-list-loading').show();

    $('#fraud-list-content').hide();

    $('#fraud-list-empty').hide();

    // API call with filters

    $.ajax({

        url: typeof sensfrxData !== 'undefined' ? sensfrxData.restUrl + 'fraud-cases-list' : ajaxurl,

        method: 'GET',

        data: {

            action: 'sensfrx_get_fraud_cases',

            date_range: dateRange,

            risk_levels: riskLevels,

            event_types: eventTypes,

            search: searchQuery

        },

        beforeSend: function(xhr) {

            if (typeof sensfrxData !== 'undefined' && sensfrxData.nonce) {

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

            }

        },

        success: function(response) {

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

                // Backend now handles all filtering - no need for client-side filtering

                allFraudCases = response.data;

                

                // Calculate and update statistics from filtered data

                updateStatistics(response.data);

                

                renderFraudCases(response.data);

                $('#fraud-list-loading').hide();

                $('#fraud-list-content').show();

            } else {

                // Show empty state with zero statistics

                updateStatistics([]);

                $('#fraud-list-loading').hide();

                $('#fraud-list-content').hide();

                $('#fraud-list-empty').show();

            }

        },

        error: function() {

            // Show sample data for demo

            showSampleFraudCases();

        }

    });

    // Fetch review count for fraud review badge

    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));

}



function showSampleFraudCases() {

    const $ = jQuery;



    // Get current date and calculate past dates

    const now = new Date();

    const today = now.toISOString().split('T')[0];

    const yesterday = new Date(now - 24*60*60*1000).toISOString().split('T')[0];

    const threeDaysAgo = new Date(now - 3*24*60*60*1000).toISOString().split('T')[0];

    const weekAgo = new Date(now - 7*24*60*60*1000).toISOString().split('T')[0];

    const twoWeeksAgo = new Date(now - 14*24*60*60*1000).toISOString().split('T')[0];

    const threeWeeksAgo = new Date(now - 21*24*60*60*1000).toISOString().split('T')[0];

    const oneMonthAgo = new Date(now - 30*24*60*60*1000).toISOString().split('T')[0];

    const twoMonthsAgo = new Date(now - 60*24*60*60*1000).toISOString().split('T')[0];

    const threeMonthsAgo = new Date(now - 90*24*60*60*1000).toISOString().split('T')[0];

    const fourMonthsAgo = new Date(now - 120*24*60*60*1000).toISOString().split('T')[0];





    // 40 DIVERSE CASES ACROSS 4 MONTHS - For comprehensive filter testing

    const sampleCases = [

        // TODAY - 4 cases

        { id: '1', timestamp: today + ' 10:30 AM', event_type: 'Payment Attempt', user: 'john.doe@example.com', ip_address: '192.168.1.1', risk_score: 85, status: 'deny', case_uuid: '134ae646-b612-4c64-8b33-33a12ac0214c' },

        { id: '2', timestamp: today + ' 09:15 AM', event_type: 'Login Attempt', user: 'suspicious.user@test.com', ip_address: '10.0.0.1', risk_score: 62, status: 'challenge', case_uuid: '2f8b9c45-d123-4a56-9e87-4b5c6d7e8f90' },

        { id: '3', timestamp: today + ' 02:45 PM', event_type: 'Account Update', user: 'user@example.org', ip_address: '100.200.50.60', risk_score: 45, status: 'challenge', case_uuid: '11223344-5566-7788-99aa-bbccddeeff00' },

        { id: '4', timestamp: today + ' 08:00 AM', event_type: 'Registration', user: 'newuser@gmail.com', ip_address: '88.99.100.10', risk_score: 22, status: 'allow', case_uuid: 'aabbccdd-1122-3344-5566-778899aabbcc' },



        // YESTERDAY - 5 cases

        { id: '5', timestamp: yesterday + ' 11:45 PM', event_type: 'Registration', user: 'new.user@domain.com', ip_address: '172.16.0.1', risk_score: 28, status: 'allow', case_uuid: '789abc01-2345-6789-abcd-ef0123456789' },

        { id: '6', timestamp: yesterday + ' 03:20 PM', event_type: 'Payment Attempt', user: 'fraud@test.com', ip_address: '45.67.89.10', risk_score: 95, status: 'deny', case_uuid: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' },

        { id: '7', timestamp: yesterday + ' 09:30 AM', event_type: 'Login Attempt', user: 'admin@mysite.com', ip_address: '203.45.67.1', risk_score: 18, status: 'allow', case_uuid: '99887766-5544-3322-1100-ffeeddccbbaa' },

        { id: '8', timestamp: yesterday + ' 05:15 PM', event_type: 'Account Update', user: 'updateuser@company.com', ip_address: '150.100.50.25', risk_score: 55, status: 'challenge', case_uuid: 'fedcba98-7654-3210-fedc-ba9876543210' },

        { id: '9', timestamp: yesterday + ' 01:00 PM', event_type: 'Payment Attempt', user: 'buyer@shop.com', ip_address: '220.130.40.50', risk_score: 42, status: 'allow', case_uuid: '12345678-abcd-efab-cdef-1234567890ab' },



        // 3 DAYS AGO - 3 cases

        { id: '10', timestamp: threeDaysAgo + ' 02:30 PM', event_type: 'Login Attempt', user: 'hacker@evil.com', ip_address: '66.77.88.99', risk_score: 92, status: 'deny', case_uuid: 'aaaa1111-bbbb-2222-cccc-3333dddd4444' },

        { id: '11', timestamp: threeDaysAgo + ' 10:00 AM', event_type: 'Registration', user: 'legit@customer.com', ip_address: '111.222.33.44', risk_score: 15, status: 'allow', case_uuid: 'bbbb2222-cccc-3333-dddd-4444eeee5555' },

        { id: '12', timestamp: threeDaysAgo + ' 06:45 PM', event_type: 'Payment Attempt', user: 'premium@buyer.net', ip_address: '99.88.77.66', risk_score: 38, status: 'allow', case_uuid: 'cccc3333-dddd-4444-eeee-5555ffff6666' },



        // WEEK AGO - 4 cases

        { id: '13', timestamp: weekAgo + ' 08:00 AM', event_type: 'Login Attempt', user: 'normal.user@company.com', ip_address: '203.45.67.89', risk_score: 15, status: 'allow', case_uuid: 'f0e1d2c3-b4a5-9687-fedc-ba0987654321' },

        { id: '14', timestamp: weekAgo + ' 04:30 PM', event_type: 'Account Update', user: 'settings@change.com', ip_address: '180.90.45.22', risk_score: 65, status: 'challenge', case_uuid: 'dddd4444-eeee-5555-ffff-66667777888' },

        { id: '15', timestamp: weekAgo + ' 11:15 AM', event_type: 'Payment Attempt', user: 'scammer@fake.org', ip_address: '1.2.3.4', risk_score: 88, status: 'deny', case_uuid: 'eeee5555-ffff-6666-7777-888899990000' },

        { id: '16', timestamp: weekAgo + ' 09:00 PM', event_type: 'Registration', user: 'signup@newbie.com', ip_address: '50.60.70.80', risk_score: 25, status: 'allow', case_uuid: 'ffff6666-7777-8888-9999-000011112222' },



        // 2 WEEKS AGO - 4 cases

        { id: '17', timestamp: twoWeeksAgo + ' 03:20 PM', event_type: 'Login Attempt', user: 'repeat@offender.com', ip_address: '200.100.50.25', risk_score: 78, status: 'deny', case_uuid: '77778888-9999-0000-1111-222233334444' },

        { id: '18', timestamp: twoWeeksAgo + ' 10:45 AM', event_type: 'Payment Attempt', user: 'customer@store.com', ip_address: '123.234.45.56', risk_score: 32, status: 'allow', case_uuid: '88889999-0000-1111-2222-333344445555' },

        { id: '19', timestamp: twoWeeksAgo + ' 07:30 PM', event_type: 'Account Update', user: 'profile@edit.net', ip_address: '77.88.99.100', risk_score: 48, status: 'allow', case_uuid: '99990000-1111-2222-3333-444455556666' },

        { id: '20', timestamp: twoWeeksAgo + ' 01:15 PM', event_type: 'Registration', user: 'member@join.org', ip_address: '155.166.177.188', risk_score: 19, status: 'allow', case_uuid: '00001111-2222-3333-4444-555566667777' },



        // 3 WEEKS AGO - 3 cases

        { id: '21', timestamp: threeWeeksAgo + ' 05:45 PM', event_type: 'Payment Attempt', user: 'suspicious@payment.com', ip_address: '71.72.73.74', risk_score: 72, status: 'deny', case_uuid: '11112222-3333-4444-5555-666677778888' },

        { id: '22', timestamp: threeWeeksAgo + ' 11:00 AM', event_type: 'Login Attempt', user: 'trusted@partner.com', ip_address: '90.80.70.60', risk_score: 12, status: 'allow', case_uuid: '22223333-4444-5555-6666-777788889999' },

        { id: '23', timestamp: threeWeeksAgo + ' 02:30 PM', event_type: 'Account Update', user: 'modify@account.net', ip_address: '44.55.66.77', risk_score: 58, status: 'challenge', case_uuid: '33334444-5555-6666-7777-888899990000' },



        // 1 MONTH AGO - 5 cases

        { id: '24', timestamp: oneMonthAgo + ' 09:15 AM', event_type: 'Registration', user: 'olduser@legacy.com', ip_address: '210.220.230.240', risk_score: 21, status: 'allow', case_uuid: '44445555-6666-7777-8888-99990000aaaa' },

        { id: '25', timestamp: oneMonthAgo + ' 04:00 PM', event_type: 'Payment Attempt', user: 'bigspender@rich.com', ip_address: '33.44.55.66', risk_score: 35, status: 'allow', case_uuid: '55556666-7777-8888-9999-0000aaaabbbb' },

        { id: '26', timestamp: oneMonthAgo + ' 08:30 PM', event_type: 'Login Attempt', user: 'bot@automation.com', ip_address: '8.8.8.8', risk_score: 81, status: 'deny', case_uuid: '66667777-8888-9999-0000-aaaabbbbcccc' },

        { id: '27', timestamp: oneMonthAgo + ' 12:45 PM', event_type: 'Account Update', user: 'change@password.org', ip_address: '199.188.177.166', risk_score: 44, status: 'allow', case_uuid: '77778888-9999-0000-aaaa-bbbbccccdddd' },

        { id: '28', timestamp: oneMonthAgo + ' 06:20 AM', event_type: 'Payment Attempt', user: 'earlybird@shop.com', ip_address: '111.112.113.114', risk_score: 52, status: 'challenge', case_uuid: '88889999-0000-aaaa-bbbb-ccccddddeeee' },



        // 2 MONTHS AGO - 4 cases

        { id: '29', timestamp: twoMonthsAgo + ' 10:30 AM', event_type: 'Login Attempt', user: 'oldlogin@historic.com', ip_address: '5.6.7.8', risk_score: 16, status: 'allow', case_uuid: '99990000-aaaa-bbbb-cccc-ddddeeeeffff' },

        { id: '30', timestamp: twoMonthsAgo + ' 03:45 PM', event_type: 'Registration', user: 'vintage@member.org', ip_address: '222.223.224.225', risk_score: 27, status: 'allow', case_uuid: '0000aaaa-bbbb-cccc-dddd-eeeeffff1111' },

        { id: '31', timestamp: twoMonthsAgo + ' 07:15 PM', event_type: 'Payment Attempt', user: 'fraud.attempt@bad.com', ip_address: '13.14.15.16', risk_score: 94, status: 'deny', case_uuid: 'aaaabbbb-cccc-dddd-eeee-ffff11112222' },

        { id: '32', timestamp: twoMonthsAgo + ' 01:00 PM', event_type: 'Account Update', user: 'settings@old.net', ip_address: '66.67.68.69', risk_score: 39, status: 'allow', case_uuid: 'bbbbcccc-dddd-eeee-ffff-111122223333' },



        // 3 MONTHS AGO - 4 cases

        { id: '33', timestamp: threeMonthsAgo + ' 11:20 AM', event_type: 'Payment Attempt', user: 'ancient@purchase.com', ip_address: '98.97.96.95', risk_score: 41, status: 'allow', case_uuid: 'ccccdddd-eeee-ffff-1111-222233334444' },

        { id: '34', timestamp: threeMonthsAgo + ' 05:30 PM', event_type: 'Login Attempt', user: 'classic@user.org', ip_address: '144.155.166.177', risk_score: 23, status: 'allow', case_uuid: 'ddddeeee-ffff-1111-2222-333344445555' },

        { id: '35', timestamp: threeMonthsAgo + ' 09:45 AM', event_type: 'Registration', user: 'threemonth@ago.com', ip_address: '75.76.77.78', risk_score: 29, status: 'allow', case_uuid: 'eeeeffff-1111-2222-3333-444455556666' },

        { id: '36', timestamp: threeMonthsAgo + ' 02:15 PM', event_type: 'Account Update', user: 'quarterly@update.net', ip_address: '188.189.190.191', risk_score: 61, status: 'challenge', case_uuid: 'ffff1111-2222-3333-4444-555566667777' },



        // 4 MONTHS AGO - 4 cases (won't show in "3 Months" filter, only in custom dates)

        { id: '37', timestamp: fourMonthsAgo + ' 08:45 AM', event_type: 'Login Attempt', user: 'oldest@record.com', ip_address: '250.240.230.220', risk_score: 14, status: 'allow', case_uuid: '11112222-3333-4444-5555-666677778888' },

        { id: '38', timestamp: fourMonthsAgo + ' 12:30 PM', event_type: 'Payment Attempt', user: 'archived@transaction.org', ip_address: '82.83.84.85', risk_score: 74, status: 'deny', case_uuid: '22223333-4444-5555-6666-777788889999' },

        { id: '39', timestamp: fourMonthsAgo + ' 04:15 PM', event_type: 'Registration', user: 'historical@signup.net', ip_address: '165.164.163.162', risk_score: 31, status: 'allow', case_uuid: '33334444-5555-6666-7777-888899990000' },

        { id: '40', timestamp: fourMonthsAgo + ' 06:50 PM', event_type: 'Account Update', user: 'longago@change.com', ip_address: '40.41.42.43', risk_score: 67, status: 'challenge', case_uuid: '44445555-6666-7777-8888-999900001111' }

    ];



    // ===== GATHER ALL FILTERS =====



    // Date Range Filter

    const dateRange = $('.fmc-pill.active').data('range') || 'week';

    const customFrom = $('#date-from').val();

    const customTo = $('#date-to').val();



    // Risk Levels Filter

    const riskLevels = [];

    $('.fmc-risk-card.active').each(function() {

        riskLevels.push($(this).data('risk'));

    });



    // Event Types Filter

    const eventTypes = [];

    $('.fmc-checkbox input:checked').each(function() {

        eventTypes.push($(this).val());

    });



    // Search Filter

    const searchQuery = $('#fmc-search').val().toLowerCase();



    if (dateRange === 'custom') {

    }



    // ===== HELPER FUNCTION: Parse timestamp to Date object =====

    function parseTimestamp(timestampStr) {

        // Format: "2025-11-25 10:30 AM"

        const parts = timestampStr.match(/(\d{4})-(\d{2})-(\d{2})\s+(\d{1,2}):(\d{2})\s*(AM|PM)?/);

        if (parts) {

            const year = parseInt(parts[1]);

            const month = parseInt(parts[2]) - 1; // JS months are 0-indexed

            const day = parseInt(parts[3]);

            let hour = parseInt(parts[4]);

            const minute = parseInt(parts[5]);

            const ampm = parts[6];



            // Convert to 24-hour format

            if (ampm === 'PM' && hour !== 12) hour += 12;

            if (ampm === 'AM' && hour === 12) hour = 0;



            return new Date(year, month, day, hour, minute);

        }

        return new Date(timestampStr);

    }



    // ===== HELPER FUNCTION: Check if date is in range =====

    function isDateInRange(timestampStr) {

        const itemDate = parseTimestamp(timestampStr);

        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());



        switch(dateRange) {

            case 'today':

                const todayEnd = new Date(todayStart);

                todayEnd.setDate(todayEnd.getDate() + 1);

                return itemDate >= todayStart && itemDate < todayEnd;



            case 'yesterday':

                const yesterdayStart = new Date(todayStart);

                yesterdayStart.setDate(yesterdayStart.getDate() - 1);

                return itemDate >= yesterdayStart && itemDate < todayStart;



            case 'week':

                const weekStart = new Date(todayStart);

                weekStart.setDate(weekStart.getDate() - 7);

                return itemDate >= weekStart;



            case 'month':

                const monthStart = new Date(todayStart);

                monthStart.setMonth(monthStart.getMonth() - 1);

                return itemDate >= monthStart;



            case '3months':

                const threeMonthsStart = new Date(todayStart);

                threeMonthsStart.setMonth(threeMonthsStart.getMonth() - 3);

                return itemDate >= threeMonthsStart;



            case 'custom':

                if (customFrom && customTo) {

                    const fromDate = new Date(customFrom);

                    const toDate = new Date(customTo);

                    toDate.setHours(23, 59, 59, 999); // End of day

                    return itemDate >= fromDate && itemDate <= toDate;

                }

                return true; // If custom selected but no dates, show all



            default:

                return true;

        }

    }



    // ===== APPLY ALL FILTERS =====

    const filteredCases = sampleCases.filter(function(item) {

        // DATE FILTER - This was completely missing!

        if (!isDateInRange(item.timestamp)) {

            return false;

        }



        // RISK FILTER - if no risks selected, show all

        if (riskLevels.length > 0) {

            const riskLevel = item.risk_score >= 70 ? 'high' : item.risk_score >= 40 ? 'medium' : 'low';

            if (!riskLevels.includes(riskLevel)) {

                return false;

            }

        }



        // EVENT TYPE FILTER - if no types checked, show all

        if (eventTypes.length > 0) {

            let typeValue = '';

            const eventLower = item.event_type.toLowerCase();



            if (eventLower.includes('payment')) typeValue = 'payment';

            else if (eventLower.includes('login')) typeValue = 'login';

            else if (eventLower.includes('registration') || eventLower.includes('register')) typeValue = 'registration';

            else if (eventLower.includes('account') || eventLower.includes('update')) typeValue = 'account_update';



            if (typeValue && !eventTypes.includes(typeValue)) {

                return false;

            }

        }



        // SEARCH FILTER

        if (searchQuery) {

            const searchStr = (item.user + ' ' + item.ip_address + ' ' + item.event_type + ' ' + item.status).toLowerCase();

            if (!searchStr.includes(searchQuery)) {

                return false;

            }

        }



        return true;

    });



    // Update statistics for filtered sample data

    updateStatistics(filteredCases);

    renderFraudCases(filteredCases);

    $('#fraud-list-loading').hide();

    $('#fraud-list-content').show();

}



/**

 * Update statistics based on filtered fraud cases data

 */

function updateStatistics(cases) {

    const $ = jQuery;

    

    // Calculate statistics

    const totalCases = cases.length;

    const blockedCases = cases.filter(c => c.status === 'deny').length;

    const reviewCases = cases.filter(c => c.status === 'challenge').length;

    

    // Calculate saved amount from blocked cases

    const savedAmount = cases

        .filter(c => c.status === 'deny')

        .reduce((sum, c) => {

            const amount = parseFloat(c.order_total || c.amount || 0);

            return sum + amount;

        }, 0);

    

    // Update the DOM with formatted numbers

    $('#stat-total-cases').text(totalCases.toLocaleString());

    $('#stat-blocked-cases').text(blockedCases.toLocaleString());

    $('#stat-saved-amount').text('$' + Math.round(savedAmount).toLocaleString());

    $('#stat-review-cases').text(reviewCases.toLocaleString());

}



function renderFraudCases(cases) {

    const $ = jQuery;

    

    // Store data for pagination

    currentDisplayData = cases;

    

    // Calculate pagination

    const totalItems = cases.length;

    

    // Hide pagination if less than minimum threshold

    if (totalItems <= 10) {

        $('#fraud-pagination').hide();

        currentPage = 1;

        displayPage(cases, 1, totalItems);

        return;

    }

    

    // Show pagination

    $('#fraud-pagination').show();

    totalPages = Math.ceil(totalItems / itemsPerPage);

    

    // Reset to page 1 if current page is out of bounds

    if (currentPage > totalPages) {

        currentPage = 1;

    }

    

    // Display current page

    displayPage(cases, currentPage, itemsPerPage);

    

    // Update pagination controls

    updatePaginationControls(totalItems);

}



function displayPage(allCases, page, perPage) {

    const $ = jQuery;

    const tbody = $('#fraud-list-tbody');

    tbody.empty();

    

    // Calculate slice indices

    const startIndex = (page - 1) * perPage;

    const endIndex = Math.min(startIndex + perPage, allCases.length);

    

    // Get cases for current page

    const pageCases = allCases.slice(startIndex, endIndex);

    

    // Render each case

    pageCases.forEach(function(fraudCase) {

        const riskLevel = fraudCase.risk_score >= 70 ? 'high' : fraudCase.risk_score >= 40 ? 'medium' : 'low';

        const riskClass = 'sensfrx-risk-' + riskLevel;

        // const statusClass = 'sensfrx-status-' + fraudCase.status;

        const statusMap = {

            allow: "allowed",

            deny: "blocked",

            challenge: "pending",



            // in case API sends already-correct names

            allowed: "allowed",

            blocked: "blocked",

            pending: "pending"

        };



        const mappedStatus = statusMap[fraudCase.status] || "pending";  

        const statusClass = "sensfrx-status-" + mappedStatus;



        const row = `

            <tr>

                <td style="padding: 12px 16px; font-size: 14px; color: #374151;">${fraudCase.timestamp}</td>

                <td style="padding: 12px 16px; font-size: 14px; color: #374151;">${fraudCase.event_type}</td>

                <td style="padding: 12px 16px; font-size: 14px; color: #374151;">

                    <div>${fraudCase.user || 'N/A'}</div>

                    <div style="font-size: 12px; color: #6b7280;">${fraudCase.ip_address}</div>

                </td>

                <td style="padding: 12px 16px;">

                    <span class="sensfrx-risk-badge ${riskClass}">${fraudCase.risk_score}</span>

                </td>

                <td style="padding: 12px 16px;">

                    <span class="sensfrx-status-badge ${statusClass}"> ${

                        fraudCase.status === "challenge" 

                        ? "Pending" 

                        : fraudCase.status === "deny" 

                            ? "Blocked" 

                            : fraudCase.status === "allow" 

                                ? "Allowed" 

                                : fraudCase.status

                    }</span>

                </td>

                <td style="padding: 12px 16px;">

                    <a href="javascript:void(0)"

                        class="sensfrx-view-detail-btn"

                        data-link="${fraudCase.link}"

                        style="display: inline-block; padding: 6px 12px; background: transparent; color: #047857; border: 1px solid #047857; border-radius: 4px; font-size: 13px; text-decoration: none;">

                        View Details

                    </a>

                </td>

            </tr>

        `;

        tbody.append(row);

    });

}



jQuery(document).on('click', '.sensfrx-view-detail-btn', function (e) {

    e.preventDefault();



    const detailLink = jQuery(this).data('link');



    fetch(sensfrxData.restUrl + 'onboarding-login-link', {

        method: 'GET',

        headers: {

            'Content-Type': 'application/json',

            'X-WP-Nonce': sensfrxData.nonce

        }

    })

    .then(async res => {

        const text = await res.text();

        try {

            return JSON.parse(text);

        } catch (e) {

            console.error("Invalid JSON:", text);

            throw new Error("Invalid JSON from server");

        }

    })

    .then(result => {

        if (result.status === "success" && result.login_link) {



            const redirectLink =

                result.login_link + '?next=' + encodeURIComponent(detailLink);



            window.open(redirectLink, "_blank");



        } else {

            console.error("Unable to generate secure login link.");

        }

    })

    .catch(err => {

        console.error("Login link error:", err);

    });

});



/**

 * Update pagination controls UI

 */

function updatePaginationControls(totalItems) {

    const $ = jQuery;

    

    // Update showing info

    const start = (currentPage - 1) * itemsPerPage + 1;

    const end = Math.min(currentPage * itemsPerPage, totalItems);

    $('#page-start').text(start);

    $('#page-end').text(end);

    $('#total-items').text(totalItems);

    

    // Update prev/next buttons

    $('#page-prev').prop('disabled', currentPage === 1);

    $('#page-next').prop('disabled', currentPage === totalPages);

    

    // Generate page numbers

    generatePageNumbers();

}



/**

 * Generate page number buttons

 */

function generatePageNumbers() {

    const $ = jQuery;

    const container = $('#page-numbers');

    container.empty();

    

    // Show max 7 page buttons with smart ellipsis

    const maxButtons = 7;

    let startPage, endPage;

    

    if (totalPages <= maxButtons) {

        // Show all pages

        startPage = 1;

        endPage = totalPages;

    } else {

        // Calculate range with current page in middle

        const middleButtons = maxButtons - 2; // Reserve space for first and last

        const sideButtons = Math.floor(middleButtons / 2);

        

        if (currentPage <= sideButtons + 2) {

            startPage = 1;

            endPage = maxButtons - 1;

        } else if (currentPage >= totalPages - sideButtons - 1) {

            startPage = totalPages - maxButtons + 2;

            endPage = totalPages;

        } else {

            startPage = currentPage - sideButtons;

            endPage = currentPage + sideButtons;

        }

    }

    

    // Always show first page

    if (startPage > 1) {

        container.append(createPageButton(1));

        if (startPage > 2) {

            container.append('<span style="padding: 8px 4px; color: #9CA3AF;">...</span>');

        }

    }

    

    // Show page range

    for (let i = startPage; i <= endPage; i++) {

        container.append(createPageButton(i));

    }

    

    // Always show last page

    if (endPage < totalPages) {

        if (endPage < totalPages - 1) {

            container.append('<span style="padding: 8px 4px; color: #9CA3AF;">...</span>');

        }

        container.append(createPageButton(totalPages));

    }

}



/**

 * Create a page button element

 */

function createPageButton(pageNum) {

    const isActive = pageNum === currentPage;

    const activeStyle = isActive 

        ? 'background: #10367B; color: white; border-color: #10367B;' 

        : 'background: white; color: #374151;';

    

    return jQuery('<button>')

        .text(pageNum)

        .attr('style', `padding: 8px 12px; border: 1.5px solid #E5E7EB; border-radius: 6px; font-size: 14px; font-weight: 500; cursor: pointer; min-width: 40px; ${activeStyle}`)

        .on('click', function() {

            goToPage(pageNum);

        });

}



/**

 * Navigate to specific page

 */

function goToPage(page) {

    currentPage = page;

    displayPage(currentDisplayData, currentPage, itemsPerPage);

    updatePaginationControls(currentDisplayData.length);

    

    // Scroll to top of table smoothly

    jQuery('#fraud-list-content').get(0).scrollIntoView({ behavior: 'smooth', block: 'start' });

}



/**

 * Initialize pagination event listeners

 */

function initPaginationEvents() {

    const $ = jQuery;

    

    // Previous button

    $('#page-prev').on('click', function() {

        if (currentPage > 1) {

            goToPage(currentPage - 1);

        }

    });

    

    // Next button

    $('#page-next').on('click', function() {

        if (currentPage < totalPages) {

            goToPage(currentPage + 1);

        }

    });

    

    // Items per page selector

    $('#items-per-page').on('change', function() {

        itemsPerPage = parseInt($(this).val());

        currentPage = 1; // Reset to first page

        renderFraudCases(currentDisplayData);

    });

}



function viewFraudDetails(caseId) {

    window.location.href = '?page=sensfrx_fpwoo&tab=review&case=' + caseId;

}



function exportFraudReport() {

    const $ = jQuery;

    const dateRange = $('.fmc-pill.active').data('range') || 'all';

    

    // Get the current filtered data (use allFraudCases if available)

    const dataToExport = typeof allFraudCases !== 'undefined' && allFraudCases.length > 0 

        ? allFraudCases 

        : [];

    

    if (dataToExport.length === 0) {

        alert('No fraud cases to export. Please wait for data to load or apply filters.');

        return;

    }

    

    // Prepare CSV content

    const headers = ['Timestamp', 'Event Type', 'User/Email', 'IP Address', 'Risk Score', 'Status', 'Details'];

    const csvRows = [];

    

    // Add headers

    csvRows.push(headers.join(','));

    

    // Add data rows

    dataToExport.forEach(item => {

        const row = [

            item.timestamp || '',

            item.event_type || '',

            item.user || item.email || '',

            item.ip_address || '',

            item.risk_score || '',

            item.status || '',

            (item.details || '').replace(/,/g, ';').replace(/\n/g, ' ') // Remove commas and newlines

        ];

        csvRows.push(row.map(field => `"${field}"`).join(','));

    });

    

    // Create CSV content

    const csvContent = csvRows.join('\n');

    

    // Create blob and download

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

    const link = document.createElement('a');

    const url = URL.createObjectURL(blob);

    

    // Generate filename with date range

    const now = new Date();

    const dateStr = now.toISOString().split('T')[0];

    const filename = `sensfrx-fraud-report-${dateRange}-${dateStr}.csv`;

    

    link.setAttribute('href', url);

    link.setAttribute('download', filename);

    link.style.visibility = 'hidden';

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);

    

    // Show success message

    const exportBtn = $('.fmc-export-btn');

    const originalText = exportBtn.html();

    exportBtn.html('✓ Exported!').css('background', '#10b981');

    

    setTimeout(() => {

        exportBtn.html(originalText).css('background', '#10b981');

    }, 2000);

}



function applyCustomDateRange() {

    const from = jQuery('#date-from').val();

    const to = jQuery('#date-to').val();



    if (from && to) {

        loadFraudCasesWithFilters();

    } else {

        alert('Please select both start and end dates');

    }

}



// Backward compatibility with original functions

function sensFrxRefreshFraudList() {

    loadFraudCasesWithFilters();

}



function loadFraudCases() {

    loadFraudCasesWithFilters();

}



// MINIMAL UI FIXES - Backend handles all filtering

jQuery(document).ready(function() {

    setTimeout(function() {

        // 1. Add Clear button to custom date range

        if (jQuery('#custom-date-clear').length === 0) {

            jQuery('#custom-date-range > div').append(

                '<button id="custom-date-clear" style="padding: 8px 16px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; margin-left: 8px;">Clear</button>'

            );

        }



        jQuery('#custom-date-clear').on('click', function(e) {

            e.preventDefault();

            jQuery('#date-from').val('');

            jQuery('#date-to').val('');

        });



    }, 500);

});

</script>