<?php

/**

 * SensFRX Fraud Management Center - Enterprise Shop Owner Interface

 * Replaces basic filter dropdown with comprehensive fraud management system

 */



add_action('admin_footer', 'sensfrx_fraud_management_center_ui');

add_action('wp_ajax_sensfrx_get_fraud_data', 'sensfrx_ajax_get_fraud_data');

add_action('wp_ajax_sensfrx_export_fraud_data', 'sensfrx_ajax_export_fraud_data');



function sensfrx_fraud_management_center_ui() {

    if (!isset($_GET['page']) || $_GET['page'] !== 'sensfrx_fpwoo') return;

    if (!isset($_GET['tab']) || $_GET['tab'] !== 'fraud') return;

    ?>



    <style>

    /* Hide original basic filter */

    #fraud-filter, select[style*="padding: 8px 16px"] {

        display: none !important;

    }



    /* Fraud Management Center Styles */

    .fmc-container {

        margin: 20px 0;

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

    }



    /* Header Stats Dashboard */

    .fmc-dashboard {

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

        border-radius: 16px;

        padding: 30px;

        margin-bottom: 30px;

        box-shadow: 0 20px 40px rgba(0,0,0,0.1);

    }



    .fmc-dashboard-title {

        color: white;

        font-size: 24px;

        font-weight: 600;

        margin-bottom: 24px;

        display: flex;

        align-items: center;

        gap: 12px;

    }



    .fmc-stats-grid {

        display: grid;

        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));

        gap: 16px;

    }



    .fmc-stat-card {

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

        border-radius: 12px;

        padding: 20px;

        backdrop-filter: blur(10px);

    }



    .fmc-stat-value {

        font-size: 36px;

        font-weight: 700;

        color: #1a202c;

        line-height: 1;

        margin-bottom: 8px;

    }



    .fmc-stat-label {

        font-size: 13px;

        color: #64748b;

        text-transform: uppercase;

        letter-spacing: 0.5px;

        font-weight: 600;

    }



    .fmc-stat-trend {

        margin-top: 12px;

        font-size: 14px;

        display: flex;

        align-items: center;

        gap: 4px;

    }



    .trend-up { color: #ef4444; }

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



    /* Filter Control Center */

    .fmc-filter-center {

        background: white;

        border-radius: 16px;

        box-shadow: 0 4px 24px rgba(0,0,0,0.06);

        overflow: hidden;

        margin-bottom: 24px;

    }



    .fmc-filter-header {

        background: #f8fafc;

        padding: 20px 24px;

        border-bottom: 1px solid #e2e8f0;

    }



    .fmc-filter-title {

        font-size: 16px;

        font-weight: 600;

        color: #1e293b;

        display: flex;

        align-items: center;

        gap: 8px;

    }



    .fmc-filter-body {

        padding: 24px;

    }



    /* Date Range Selector */

    .fmc-date-selector {

        display: flex;

        gap: 8px;

        padding: 4px;

        background: #f1f5f9;

        border-radius: 10px;

        margin-bottom: 24px;

    }



    .fmc-date-btn {

        flex: 1;

        padding: 10px 16px;

        background: transparent;

        border: none;

        border-radius: 8px;

        color: #64748b;

        font-weight: 500;

        cursor: pointer;

        transition: all 0.2s;

        font-size: 14px;

        white-space: nowrap;

    }



    .fmc-date-btn:hover {

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

    }



    .fmc-date-btn.active {

        background: white;

        color: #667eea;

        box-shadow: 0 2px 8px rgba(0,0,0,0.08);

    }



    /* Fraud Type Tabs */

    .fmc-fraud-tabs {

        display: flex;

        gap: 12px;

        margin-bottom: 24px;

        padding-bottom: 20px;

        border-bottom: 1px solid #e2e8f0;

        overflow-x: auto;

    }



    .fmc-fraud-tab {

        padding: 12px 20px;

        background: white;

        border: 2px solid #e2e8f0;

        border-radius: 10px;

        cursor: pointer;

        transition: all 0.2s;

        white-space: nowrap;

        display: flex;

        align-items: center;

        gap: 8px;

    }



    .fmc-fraud-tab:hover {

        border-color: #cbd5e0;

        transform: translateY(-1px);

    }



    .fmc-fraud-tab.active {

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

        color: white;

        border-color: transparent;

    }



    .fmc-tab-count {

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

        padding: 2px 8px;

        border-radius: 12px;

        font-size: 12px;

        font-weight: 600;

    }



    /* Risk Level Selector */

    .fmc-risk-selector {

        margin-bottom: 24px;

    }



    .fmc-section-label {

        font-size: 12px;

        font-weight: 600;

        text-transform: uppercase;

        color: #64748b;

        letter-spacing: 0.5px;

        margin-bottom: 12px;

    }



    .fmc-risk-cards {

        display: grid;

        grid-template-columns: repeat(3, 1fr);

        gap: 12px;

    }



    .fmc-risk-card {

        padding: 16px;

        border: 2px solid #e2e8f0;

        border-radius: 12px;

        cursor: pointer;

        transition: all 0.2s;

        text-align: center;

    }



    .fmc-risk-card:hover {

        transform: translateY(-2px);

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

    }



    .fmc-risk-card.active {

        border-color: #667eea;

        background: #f0f4ff;

    }



    .fmc-risk-card.high { border-left: 4px solid #ef4444; }

    .fmc-risk-card.medium { border-left: 4px solid #f59e0b; }

    .fmc-risk-card.low { border-left: 4px solid #10b981; }



    .fmc-risk-icon {

        font-size: 24px;

        margin-bottom: 8px;

    }



    .fmc-risk-label {

        font-weight: 600;

        font-size: 14px;

        color: #1e293b;

    }



    .fmc-risk-score {

        font-size: 12px;

        color: #64748b;

        margin-top: 4px;

    }



    /* Search and Actions */

    .fmc-search-actions {

        display: flex;

        gap: 12px;

        margin-bottom: 24px;

    }



    .fmc-search-box {

        flex: 1;

        position: relative;

    }



    .fmc-search-input {

        width: 100%;

        padding: 12px 16px 12px 44px;

        border: 2px solid #e2e8f0;

        border-radius: 10px;

        font-size: 14px;

        transition: all 0.2s;

    }



    .fmc-search-input:focus {

        outline: none;

        border-color: #667eea;

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

    }



    .fmc-search-icon {

        position: absolute;

        left: 16px;

        top: 50%;

        transform: translateY(-50%);

        color: #94a3b8;

    }



    .fmc-action-btn {

        padding: 12px 20px;

        background: white;

        border: 2px solid #e2e8f0;

        border-radius: 10px;

        color: #475569;

        font-weight: 500;

        cursor: pointer;

        transition: all 0.2s;

        display: flex;

        align-items: center;

        gap: 8px;

    }



    .fmc-action-btn:hover {

        background: #f8fafc;

        border-color: #cbd5e0;

    }



    .fmc-action-btn.primary {

        background: #10b981;

        color: white;

        border-color: #10b981;

    }



    .fmc-action-btn.primary:hover {

        background: #059669;

        border-color: #059669;

    }



    /* Results Bar */

    .fmc-results-bar {

        background: #f8fafc;

        border-radius: 12px;

        padding: 16px 20px;

        margin-bottom: 24px;

        display: flex;

        justify-content: space-between;

        align-items: center;

    }



    .fmc-result-summary {

        display: flex;

        gap: 24px;

        align-items: center;

    }



    .fmc-result-item {

        display: flex;

        align-items: center;

        gap: 8px;

    }



    .fmc-result-number {

        font-size: 20px;

        font-weight: 700;

        color: #1e293b;

    }



    .fmc-result-label {

        font-size: 14px;

        color: #64748b;

    }



    /* Alert Banner */

    .fmc-alert-banner {

        background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);

        border-left: 4px solid #f59e0b;

        border-radius: 10px;

        padding: 16px 20px;

        margin-bottom: 24px;

        display: flex;

        align-items: center;

        gap: 12px;

    }



    .fmc-alert-icon {

        font-size: 20px;

    }



    .fmc-alert-content {

        flex: 1;

    }



    .fmc-alert-title {

        font-weight: 600;

        color: #92400e;

        margin-bottom: 4px;

    }



    .fmc-alert-message {

        font-size: 14px;

        color: #78350f;

    }



    /* Loading State */

    @keyframes shimmer {

        0% { background-position: -1000px 0; }

        100% { background-position: 1000px 0; }

    }



    .fmc-loading {

        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);

        background-size: 1000px 100%;

        animation: shimmer 1.5s infinite;

    }

    </style>



    <script>

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

        // Remove or hide existing filter

        $('#fraud-filter').parent().hide();

        $('select[style*="padding: 8px 16px"]').parent().hide();



        const fraudManagementHTML = `

        <div class="fmc-container">

            <!-- Statistics Dashboard -->

            <div class="fmc-dashboard">

                <div class="fmc-dashboard-title">

                    <span>🛡️</span>

                    Fraud Management Center

                </div>

                <div class="fmc-stats-grid">

                    <div class="fmc-stat-card">

                        <div class="fmc-stat-value" id="stat-total">1,247</div>

                        <div class="fmc-stat-label">Total Cases This Month</div>

                        <div class="fmc-stat-trend trend-up">

                            <span>↑</span> 12% from last month

                        </div>

                    </div>

                    <div class="fmc-stat-card">

                        <div class="fmc-stat-value" id="stat-blocked" style="color: #ef4444;">523</div>

                        <div class="fmc-stat-label">Threats Blocked</div>

                        <div class="fmc-stat-trend trend-down">

                            <span>↓</span> 8% improvement

                        </div>

                    </div>

                    <div class="fmc-stat-card">

                        <div class="fmc-stat-value" id="stat-saved" style="color: #10b981;">$47,392</div>

                        <div class="fmc-stat-label">Fraud Prevented</div>

                        <div class="fmc-stat-trend trend-up" style="color: #10b981;">

                            <span>↑</span> Saved this month

                        </div>

                    </div>

                    <div class="fmc-stat-card">

                        <div class="fmc-stat-value" id="stat-review" style="color: #f59e0b;">18</div>

                        <div class="fmc-stat-label">Need Review</div>

                        <div class="fmc-stat-trend">

                            <span>⚠️</span> Immediate attention

                        </div>

                    </div>

                </div>

            </div>



            <!-- Alert Banner for Urgent Items -->

            <div class="fmc-alert-banner" id="alert-banner" style="display: none;">

                <div class="fmc-alert-icon">⚠️</div>

                <div class="fmc-alert-content">

                    <div class="fmc-alert-title">Unusual Activity Detected</div>

                    <div class="fmc-alert-message">5 high-risk attempts from the same IP in the last hour</div>

                </div>

                <button class="fmc-action-btn" onclick="viewAlert()">View Details</button>

            </div>



            <!-- Filter Control Center -->

            <div class="fmc-filter-center">

                <div class="fmc-filter-header">

                    <div class="fmc-filter-title">

                        <span>🔍</span>

                        Filter Fraud Cases

                    </div>

                </div>



                <div class="fmc-filter-body">

                    <!-- Date Range Selector -->

                    <div class="fmc-date-selector">

                        <button class="fmc-date-btn" data-range="today">Today</button>

                        <button class="fmc-date-btn" data-range="yesterday">Yesterday</button>

                        <button class="fmc-date-btn active" data-range="week">This Week</button>

                        <button class="fmc-date-btn" data-range="month">This Month</button>

                        <button class="fmc-date-btn" data-range="3months">3 Months</button>

                        <button class="fmc-date-btn" data-range="custom">📅 Custom</button>

                    </div>



                    <!-- Fraud Type Tabs -->

                    <div class="fmc-fraud-tabs">

                        <div class="fmc-fraud-tab active" data-type="all">

                            <span>📊</span>

                            <span>All Cases</span>

                            <span class="fmc-tab-count">1,247</span>

                        </div>

                        <div class="fmc-fraud-tab" data-type="payment">

                            <span>💳</span>

                            <span>Payment Fraud</span>

                            <span class="fmc-tab-count">456</span>

                        </div>

                        <div class="fmc-fraud-tab" data-type="account">

                            <span>👤</span>

                            <span>Account Takeover</span>

                            <span class="fmc-tab-count">234</span>

                        </div>

                        <div class="fmc-fraud-tab" data-type="registration">

                            <span>📝</span>

                            <span>Fake Registration</span>

                            <span class="fmc-tab-count">189</span>

                        </div>

                        <div class="fmc-fraud-tab" data-type="bot">

                            <span>🤖</span>

                            <span>Bot Activity</span>

                            <span class="fmc-tab-count">368</span>

                        </div>

                    </div>



                    <!-- Risk Level Selector -->

                    <div class="fmc-risk-selector">

                        <div class="fmc-section-label">Risk Level</div>

                        <div class="fmc-risk-cards">

                            <div class="fmc-risk-card high active" data-risk="high">

                                <div class="fmc-risk-icon">🔴</div>

                                <div class="fmc-risk-label">High Risk</div>

                                <div class="fmc-risk-score">60-100</div>

                            </div>

                            <div class="fmc-risk-card medium active" data-risk="medium">

                                <div class="fmc-risk-icon">🟡</div>

                                <div class="fmc-risk-label">Medium Risk</div>

                                <div class="fmc-risk-score">30-59</div>

                            </div>

                            <div class="fmc-risk-card low" data-risk="low">

                                <div class="fmc-risk-icon">🟢</div>

                                <div class="fmc-risk-label">Low Risk</div>

                                <div class="fmc-risk-score">0-30</div>

                            </div>

                        </div>

                    </div>



                    <!-- Search and Actions -->

                    <div class="fmc-search-actions">

                        <div class="fmc-search-box">

                            <span class="fmc-search-icon">🔍</span>

                            <input type="text" class="fmc-search-input" placeholder="Search by email, IP, order ID, or customer name...">

                        </div>

                        <button class="fmc-action-btn">

                            <span>⚙️</span>

                            Advanced

                        </button>

                        <button class="fmc-action-btn primary" onclick="exportReport()">

                            <span>📊</span>

                            Export

                        </button>

                    </div>

                </div>

            </div>



            <!-- Results Summary Bar -->

            <div class="fmc-results-bar">

                <div class="fmc-result-summary">

                    <div class="fmc-result-item">

                        <span class="fmc-result-number" id="result-total">247</span>

                        <span class="fmc-result-label">Results</span>

                    </div>

                    <div class="fmc-result-item" style="color: #ef4444;">

                        <span class="fmc-result-number" id="result-blocked">89</span>

                        <span class="fmc-result-label">Blocked</span>

                    </div>

                    <div class="fmc-result-item" style="color: #f59e0b;">

                        <span class="fmc-result-number" id="result-review">18</span>

                        <span class="fmc-result-label">Under Review</span>

                    </div>

                    <div class="fmc-result-item" style="color: #10b981;">

                        <span class="fmc-result-number" id="result-allowed">140</span>

                        <span class="fmc-result-label">Allowed</span>

                    </div>

                </div>

                <div>

                    <select class="fmc-action-btn" style="padding: 10px 16px;">

                        <option>Bulk Actions</option>

                        <option>Block Selected</option>

                        <option>Trust Selected</option>

                        <option>Export Selected</option>

                    </select>

                </div>

            </div>

        </div>

        `;



        // Inject the Fraud Management Center UI

        const $fraudSection = $('.wrap h1:contains("Fraud Management")').parent();

        if ($fraudSection.length) {

            // Insert after the heading but before the tabs

            $fraudSection.find('h1').after(fraudManagementHTML);

        } else {

            // Fallback injection point

            $('.subsubsub').before(fraudManagementHTML);

        }



        // Initialize all interactions

        initFraudManagementCenter();



        function initFraudManagementCenter() {

            // Date range selector

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

                $('.fmc-date-btn').removeClass('active');

                $(this).addClass('active');

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

                if (range === 'custom') {

                    showDatePicker();

                } else {

                    applyDateFilter(range);

                }

            });



            // Fraud type tabs

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

                $('.fmc-fraud-tab').removeClass('active');

                $(this).addClass('active');

                applyFraudTypeFilter($(this).data('type'));

            });



            // Risk level cards

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

                $(this).toggleClass('active');

                applyRiskFilter();

            });



            // Search functionality

            let searchTimer;

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

                clearTimeout(searchTimer);

                const query = $(this).val();

                searchTimer = setTimeout(() => searchFraudCases(query), 300);

            });



            // Check for alerts

            checkForAlerts();

        }



        function applyDateFilter(range) {

            updateStats();



            // Make AJAX call to get filtered data

            $.post(ajaxurl, {

                action: 'sensfrx_get_fraud_data',

                date_range: range,

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

            }, function(response) {

                if (response.success) {

                    updateResults(response.data);

                }

            });

        }



        function applyFraudTypeFilter(type) {

            updateStats();

        }



        function applyRiskFilter() {

            const activeRisks = $('.fmc-risk-card.active').map(function() {

                return $(this).data('risk');

            }).get();

            updateStats();

        }



        function searchFraudCases(query) {

            if (query.length > 2) {

                // Add loading state

                $('.fmc-search-input').addClass('fmc-loading');

                setTimeout(() => {

                    $('.fmc-search-input').removeClass('fmc-loading');

                    updateStats();

                }, 500);

            }

        }



        function updateStats() {

            // Animate number changes

            animateNumber('#result-total', Math.floor(Math.random() * 500));

            animateNumber('#result-blocked', Math.floor(Math.random() * 200));

            animateNumber('#result-review', Math.floor(Math.random() * 50));

            animateNumber('#result-allowed', Math.floor(Math.random() * 250));

        }



        function animateNumber(selector, newValue) {

            const $el = $(selector);

            const currentValue = parseInt($el.text());

            $({ value: currentValue }).animate({ value: newValue }, {

                duration: 500,

                step: function() {

                    $el.text(Math.floor(this.value));

                },

                complete: function() {

                    $el.text(newValue);

                }

            });

        }



        function checkForAlerts() {

            // Simulate checking for alerts

            setTimeout(() => {

                const hasAlert = Math.random() > 0.5;

                if (hasAlert) {

                    $('#alert-banner').slideDown();

                }

            }, 1000);

        }



        window.viewAlert = function() {

            alert('Viewing detailed alert information...');

        }



        window.exportReport = function() {

            // Use the main exportFraudReport function if available

            if (typeof exportFraudReport === 'function') {

                exportFraudReport();

            } else {

                alert('Export functionality is loading. Please refresh the page and try again.');

            }

        }

    });

    </script>

    <?php

}



// AJAX handler for getting fraud data

function sensfrx_ajax_get_fraud_data() {

    check_ajax_referer('sensfrx_fraud_filter', 'nonce');



    $date_range = sanitize_text_field($_POST['date_range']);



    // Get filtered data (mock for now)

    $data = [

        'total' => rand(100, 1000),

        'deny' => rand(50, 300),

        'challenge' => rand(10, 50),

        'allow' => rand(100, 500)

    ];



    wp_send_json_success($data);

}



// AJAX handler for exporting fraud data

function sensfrx_ajax_export_fraud_data() {

    check_ajax_referer('sensfrx_fraud_export', 'nonce');



    $format = sanitize_text_field($_POST['format']);



    // Generate export (mock for now)

    wp_send_json_success(['url' => 'export-file-url']);

}