<?php

/**

 * SensFRX Filter Injection

 * Adds filters to existing fraud management page

 * Add this to your existing fraud page or include it

 */



// Hook into admin footer to inject our filters via JavaScript

add_action('admin_footer', 'sensfrx_inject_fraud_filters');



function sensfrx_inject_fraud_filters() {

    // Only inject on the fraud management page

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

        return;

    }

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

        return;

    }

    ?>



    <!-- Inject Filter Styles -->

    <style>

    #sensfrx-injected-filters {

        margin: 20px 0;

        padding: 20px;

        background: white;

        border-radius: 8px;

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

    }



    .filter-bar {

        display: flex;

        gap: 15px;

        flex-wrap: wrap;

        align-items: center;

        padding: 15px;

        background: #f9fafb;

        border-radius: 8px;

        margin-bottom: 15px;

    }



    .filter-group {

        display: flex;

        align-items: center;

        gap: 8px;

    }



    .filter-group label {

        font-weight: 600;

        color: #374151;

    }



    .filter-select {

        padding: 8px 12px;

        border: 1px solid #d1d5db;

        border-radius: 6px;

        background: white;

        cursor: pointer;

    }



    .filter-search {

        flex: 1;

        min-width: 250px;

        padding: 8px 12px;

        border: 1px solid #d1d5db;

        border-radius: 6px;

    }



    .status-pills {

        display: flex;

        gap: 8px;

    }



    .status-pill {

        padding: 8px 16px;

        border: 1px solid #d1d5db;

        border-radius: 20px;

        background: white;

        cursor: pointer;

        transition: all 0.2s;

    }



    .status-pill:hover {

        transform: translateY(-1px);

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

    }



    .status-pill.active {

        background: #4f46e5;

        color: white;

        border-color: #4f46e5;

    }



    .advanced-filters-toggle {

        color: #4f46e5;

        cursor: pointer;

        font-weight: 600;

        background: none;

        border: none;

        padding: 8px;

    }



    .advanced-filters {

        display: none;

        margin-top: 15px;

        padding: 20px;

        background: #f9fafb;

        border-radius: 8px;

    }



    .advanced-filters.show {

        display: block;

    }



    .advanced-filters-grid {

        display: grid;

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

        gap: 15px;

        margin-bottom: 15px;

    }



    .results-summary {

        padding: 12px 15px;

        background: #f3f4f6;

        border-radius: 6px;

        margin-top: 15px;

    }



    .export-actions {

        display: flex;

        gap: 10px;

        margin-top: 15px;

    }



    .export-btn {

        padding: 8px 16px;

        background: white;

        border: 1px solid #10b981;

        color: #10b981;

        border-radius: 6px;

        cursor: pointer;

        transition: all 0.2s;

    }



    .export-btn:hover {

        background: #10b981;

        color: white;

    }



    .bulk-actions {

        display: flex;

        gap: 10px;

        align-items: center;

        margin-top: 15px;

        padding: 15px;

        background: white;

        border: 1px solid #e5e7eb;

        border-radius: 8px;

    }

    </style>



    <!-- Inject Filters HTML via JavaScript -->

    <script>

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

        // Create filter HTML

        const filterHTML = `

        <div id="sensfrx-injected-filters">

            <!-- Quick Filters Bar -->

            <div class="filter-bar">

                <!-- Time Range -->

                <div class="filter-group">

                    <label>Show:</label>

                    <select class="filter-select" id="time-filter">

                        <option value="today">Today</option>

                        <option value="yesterday">Yesterday</option>

                        <option value="week" selected>This Week</option>

                        <option value="month">This Month</option>

                        <option value="30days">Last 30 Days</option>

                        <option value="all">All Time</option>

                    </select>

                </div>



                <!-- Status Pills -->

                <div class="filter-group">

                    <label>Status:</label>

                    <div class="status-pills">

                        <button class="status-pill active" data-status="all">All</button>

                        <button class="status-pill" data-status="deny">🚫 Blocked</button>

                        <button class="status-pill" data-status="challenge">⚠️ Review</button>

                        <button class="status-pill" data-status="allow">✅ Allowed</button>

                    </div>

                </div>



                <!-- Search -->

                <div class="filter-group" style="flex: 1;">

                    <input type="text" class="filter-search" placeholder="🔍 Search email, IP, or order ID...">

                </div>



                <!-- Clear Button -->

                <button class="button button-secondary" id="clear-filters">Clear</button>

            </div>



            <!-- Advanced Filters Toggle -->

            <button class="advanced-filters-toggle">▼ More Filters</button>



            <!-- Advanced Filters Section -->

            <div class="advanced-filters" id="advanced-filters">

                <div class="advanced-filters-grid">

                    <!-- Risk Level -->

                    <div class="filter-group-adv">

                        <label style="display: block; margin-bottom: 5px; font-weight: 600;">Risk Level</label>

                        <div>

                            <label style="display: block; margin: 5px 0;">

                                <input type="checkbox" name="risk[]" value="high" checked>

                                <span style="background: #ef4444; color: white; padding: 2px 8px; border-radius: 4px;">High (60-100)</span>

                            </label>

                            <label style="display: block; margin: 5px 0;">

                                <input type="checkbox" name="risk[]" value="medium" checked>

                                <span style="background: #f59e0b; color: white; padding: 2px 8px; border-radius: 4px;">Medium (30-59)</span>

                            </label>

                            <label style="display: block; margin: 5px 0;">

                                <input type="checkbox" name="risk[]" value="low">

                                <span style="background: #10b981; color: white; padding: 2px 8px; border-radius: 4px;">Low (0-30)</span>

                            </label>

                        </div>

                    </div>



                    <!-- Order Value -->

                    <div class="filter-group-adv">

                        <label style="display: block; margin-bottom: 5px; font-weight: 600;">Order Value</label>

                        <select class="filter-select" style="width: 100%;">

                            <option value="">Any Amount</option>

                            <option value="0-50">$0 - $50</option>

                            <option value="50-100">$50 - $100</option>

                            <option value="100-250">$100 - $250</option>

                            <option value="250-500">$250 - $500</option>

                            <option value="500+">Over $500</option>

                        </select>

                    </div>



                    <!-- Customer Type -->

                    <div class="filter-group-adv">

                        <label style="display: block; margin-bottom: 5px; font-weight: 600;">Customer Type</label>

                        <select class="filter-select" style="width: 100%;">

                            <option value="">All Customers</option>

                            <option value="new">First Time Buyer</option>

                            <option value="returning">Returning Customer</option>

                            <option value="vip">VIP Customer</option>

                            <option value="suspicious">Repeat Offender</option>

                        </select>

                    </div>



                    <!-- Country -->

                    <div class="filter-group-adv">

                        <label style="display: block; margin-bottom: 5px; font-weight: 600;">Country</label>

                        <select class="filter-select" style="width: 100%;">

                            <option value="">All Countries</option>

                            <option value="high-risk">⚠️ High Risk Countries</option>

                            <option value="US">🇺🇸 United States</option>

                            <option value="GB">🇬🇧 United Kingdom</option>

                            <option value="CA">🇨🇦 Canada</option>

                            <option value="AU">🇦🇺 Australia</option>

                            <option value="other">Other Countries</option>

                        </select>

                    </div>

                </div>



                <button class="button button-primary" id="apply-advanced">Apply Filters</button>

            </div>



            <!-- Results Summary -->

            <div class="results-summary">

                <strong id="result-count">Showing 0 results</strong>

                <span id="result-details" style="margin-left: 15px; color: #6b7280;"></span>

            </div>



            <!-- Export & Bulk Actions -->

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

                <div class="bulk-actions">

                    <input type="checkbox" id="select-all">

                    <label for="select-all" style="font-weight: 600;">Select All</label>

                    <select class="filter-select" id="bulk-action" disabled>

                        <option value="">Bulk Actions...</option>

                        <option value="block">🚫 Block Selected</option>

                        <option value="trust">✅ Trust Selected</option>

                        <option value="delete">🗑️ Delete Records</option>

                    </select>

                    <button class="button button-primary" id="apply-bulk" disabled>Apply</button>

                    <span id="selection-count" style="color: #6b7280; margin-left: 10px;"></span>

                </div>



                <div class="export-actions">

                    <span style="font-weight: 600; margin-right: 10px;">Export:</span>

                    <button class="export-btn" data-format="csv">📄 CSV</button>

                    <button class="export-btn" data-format="excel">📊 Excel</button>

                    <button class="export-btn" data-format="pdf">📑 PDF Report</button>

                </div>

            </div>

        </div>

        `;



        // Find the fraud management content area and inject filters

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



        // Try multiple injection points

        if (contentArea.length) {

            // After the header

            contentArea.find('h1').after(filterHTML);

        } else if ($('.subsubsub').length) {

            // After the tabs

            $('.subsubsub').after(filterHTML);

        } else if ($('#wpbody-content .wrap').length) {

            // At the beginning of wrap

            $('#wpbody-content .wrap').prepend(filterHTML);

        } else {

            // Fallback: prepend to body content

            $('#wpbody-content').prepend(filterHTML);

        }



        // Initialize filter interactions

        initializeFilters();



        function initializeFilters() {

            // Status pill clicks

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

                $('.status-pill').removeClass('active');

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

                applyFilters();

            });



            // Advanced filters toggle

            $('.advanced-filters-toggle').on('click', function() {

                $('#advanced-filters').toggleClass('show');

                $(this).text($(this).text().includes('More') ? '▲ Less Filters' : '▼ More Filters');

            });



            // Time filter change

            $('#time-filter').on('change', applyFilters);



            // Search input

            let searchTimer;

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

                clearTimeout(searchTimer);

                searchTimer = setTimeout(applyFilters, 500);

            });



            // Clear filters

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

                $('#time-filter').val('week');

                $('.status-pill[data-status="all"]').click();

                $('.filter-search').val('');

                $('input[name="risk[]"]').prop('checked', false);

                $('input[name="risk[]"][value="high"], input[name="risk[]"][value="medium"]').prop('checked', true);

                applyFilters();

            });



            // Apply advanced filters

            $('#apply-advanced').on('click', applyFilters);



            // Export buttons

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

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

                exportData(format);

            });



            // Select all

            $('#select-all').on('change', function() {

                $('.fraud-checkbox').prop('checked', $(this).is(':checked'));

                updateBulkActions();

            });



            // Apply bulk action

            $('#apply-bulk').on('click', function() {

                const action = $('#bulk-action').val();

                if (action) {

                    processBulkAction(action);

                }

            });

        }



        function applyFilters() {

            // Collect filter values

            const filters = {

                time: $('#time-filter').val(),

                status: $('.status-pill.active').data('status'),

                search: $('.filter-search').val(),

                risk: $('input[name="risk[]"]:checked').map(function() { return $(this).val(); }).get()

            };





            // Update results summary

            $('#result-count').text('Filtering...');



            // In real implementation, this would make an AJAX call

            // For now, just update the summary

            setTimeout(() => {

                const count = Math.floor(Math.random() * 50);

                $('#result-count').text(`Showing ${count} results`);



                if (count > 0) {

                    const blocked = Math.floor(count * 0.3);

                    const review = Math.floor(count * 0.2);

                    const allowed = count - blocked - review;



                    $('#result-details').html(

                        `<span style="color: #ef4444;">${blocked} blocked</span>, ` +

                        `<span style="color: #f59e0b;">${review} under review</span>, ` +

                        `<span style="color: #10b981;">${allowed} allowed</span>`

                    );

                } else {

                    $('#result-details').html('No suspicious activity detected');

                }

            }, 300);

        }



        function exportData(format) {

            alert(`Exporting data as ${format.toUpperCase()}...`);



            // In real implementation, this would trigger download

        }



        function updateBulkActions() {

            const checkedCount = $('.fraud-checkbox:checked').length;

            if (checkedCount > 0) {

                $('#bulk-action, #apply-bulk').prop('disabled', false);

                $('#selection-count').text(`${checkedCount} selected`);

            } else {

                $('#bulk-action, #apply-bulk').prop('disabled', true);

                $('#selection-count').text('');

            }

        }



        function processBulkAction(action) {

            const selected = $('.fraud-checkbox:checked').length;

            if (confirm(`Are you sure you want to ${action} ${selected} items?`)) {

                alert(`Processing ${action} for ${selected} items...`);

            }

        }



        // Initialize with default filter

        applyFilters();

    });

    </script>

    <?php

}



// Also add a notice if this is the fraud page without filters

add_action('admin_notices', function() {

    if (isset($_GET['page']) && $_GET['page'] === 'sensfrx_fpwoo' && isset($_GET['tab']) && $_GET['tab'] === 'fraud') {

        ?>

        <div class="notice notice-info is-dismissible">

            <p><strong>🎉 New Fraud Management Filters Available!</strong> Advanced filtering, bulk actions, and export features have been added to help you manage fraud more efficiently.</p>

        </div>

        <?php

    }

});