<?php

/**

 * SensFRX Fraud Management Center - Shop Owner Friendly Filters

 * Business-focused filters that make sense to non-technical users

 */



// Add to existing fraud management page

add_action('sensfrx_fraud_management_before_table', 'sensfrx_render_friendly_filters');



/**

 * Render shop owner friendly filters

 */

function sensfrx_render_friendly_filters() {

    ?>

    <div id="sensfrx-fraud-filters" class="sensfrx-filter-panel">



        <!-- Quick Filters Bar (Most Used) -->

        <div class="quick-filters-bar" style="background: #f9fafb; padding: 15px; border-radius: 8px; margin-bottom: 20px;">

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



                <!-- Time Range (What shop owners ask most) -->

                <div class="filter-group">

                    <label style="font-weight: 600; margin-right: 8px;">Show:</label>

                    <select id="time-range-filter" class="sensfrx-filter" style="padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 6px;">

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

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

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

                        <option value="last-week">Last Week</option>

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

                        <option value="last-month">Last Month</option>

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

                        <option value="custom">Custom Range...</option>

                    </select>

                </div>



                <!-- Action Status (What happened to the order?) -->

                <div class="filter-group">

                    <label style="font-weight: 600; margin-right: 8px;">Status:</label>

                    <div class="status-pills" style="display: inline-flex; gap: 5px;">

                        <button class="filter-pill active" data-status="all" style="padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 20px; background: #4f46e5; color: white; cursor: pointer;">

                            All

                        </button>

                        <button class="filter-pill" data-status="deny" style="padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 20px; background: white; cursor: pointer;">

                            🚫 Blocked

                        </button>

                        <button class="filter-pill" data-status="challenge" style="padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 20px; background: white; cursor: pointer;">

                            ⚠️ Needs Review

                        </button>

                        <button class="filter-pill" data-status="allow" style="padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 20px; background: white; cursor: pointer;">

                            ✅ Allowed

                        </button>

                    </div>

                </div>



                <!-- Quick Search (Find specific customer) -->

                <div class="filter-group" style="flex: 1; min-width: 200px;">

                    <input type="text" id="quick-search" placeholder="🔍 Search email, IP, or order ID..."

                           style="width: 100%; padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 6px;">

                </div>



                <!-- Clear Filters -->

                <button id="clear-filters" style="padding: 6px 12px; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer;">

                    Clear

                </button>

            </div>

        </div>



        <!-- Advanced Filters (Collapsible) -->

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

            <button id="toggle-advanced" style="background: none; border: none; color: #4f46e5; cursor: pointer; font-weight: 600; margin-bottom: 15px;">

                ▼ More Filters

            </button>



            <div id="advanced-filters" style="display: none; background: #f9fafb; padding: 20px; border-radius: 8px; margin-bottom: 20px;">

                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">



                    <!-- Risk Level Filter -->

                    <div class="filter-group">

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

                        <div class="risk-checkboxes">

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

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

                                <span style="display: inline-block; padding: 2px 8px; background: #ef4444; color: white; border-radius: 4px; font-size: 12px;">High Risk (60-100)</span>

                            </label>

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

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

                                <span style="display: inline-block; padding: 2px 8px; background: #f59e0b; color: white; border-radius: 4px; font-size: 12px;">Medium Risk (30-59)</span>

                            </label>

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

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

                                <span style="display: inline-block; padding: 2px 8px; background: #10b981; color: white; border-radius: 4px; font-size: 12px;">Low Risk (0-29)</span>

                            </label>

                        </div>

                    </div>



                    <!-- Order Value Filter -->

                    <div class="filter-group">

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

                        <select name="order-value" style="width: 100%; padding: 6px; border: 1px solid #d1d5db; border-radius: 6px;">

                            <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 Filter -->

                    <div class="filter-group">

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

                        <select name="customer-type" style="width: 100%; padding: 6px; border: 1px solid #d1d5db; border-radius: 6px;">

                            <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 Filter -->

                    <div class="filter-group">

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

                        <select name="country" style="width: 100%; padding: 6px; border: 1px solid #d1d5db; border-radius: 6px;">

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



                    <!-- Payment Method Filter -->

                    <div class="filter-group">

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

                        <select name="payment-method" style="width: 100%; padding: 6px; border: 1px solid #d1d5db; border-radius: 6px;">

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

                            <option value="card">💳 Credit Card</option>

                            <option value="paypal">PayPal</option>

                            <option value="stripe">Stripe</option>

                            <option value="crypto">Cryptocurrency</option>

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

                        </select>

                    </div>



                    <!-- Fraud Type Filter -->

                    <div class="filter-group">

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

                        <select name="fraud-type" style="width: 100%; padding: 6px; border: 1px solid #d1d5db; border-radius: 6px;">

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

                            <option value="card-testing">Card Testing</option>

                            <option value="account-takeover">Account Takeover</option>

                            <option value="fake-account">Fake Account</option>

                            <option value="address-mismatch">Address Mismatch</option>

                            <option value="velocity">Too Many Orders</option>

                            <option value="bot">Bot Activity</option>

                        </select>

                    </div>

                </div>



                <!-- Apply Advanced Filters Button -->

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

                    <button id="apply-advanced" style="padding: 8px 16px; background: #4f46e5; color: white; border: none; border-radius: 6px; cursor: pointer;">

                        Apply Filters

                    </button>

                </div>

            </div>

        </div>



        <!-- Smart Filter Suggestions -->

        <div id="smart-suggestions" style="background: #fef3c7; border: 1px solid #fbbf24; padding: 10px; border-radius: 6px; margin-bottom: 20px; display: none;">

            <strong>💡 Suggested Filters:</strong>

            <div id="suggestion-pills" style="margin-top: 8px;">

                <!-- Dynamic suggestions will appear here -->

            </div>

        </div>



        <!-- Filter Summary Bar -->

        <div id="filter-summary" style="background: white; padding: 10px; border: 1px solid #e5e7eb; border-radius: 6px; margin-bottom: 20px; display: none;">

            <strong>Active Filters:</strong>

            <span id="active-filter-list" style="margin-left: 10px;">

                <!-- Active filters will be shown here as pills -->

            </span>

        </div>



        <!-- Results Summary -->

        <div id="results-summary" style="padding: 10px; background: #f3f4f6; border-radius: 6px; margin-bottom: 20px;">

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

            <span id="result-stats" style="margin-left: 20px; color: #6b7280;">

                <!-- Dynamic stats like "3 blocked, 2 under review, 5 allowed" -->

            </span>

        </div>

    </div>



    <!-- JavaScript for Filter Logic -->

    <script>

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

        // Quick filter pills

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

            $('.filter-pill').removeClass('active').css({'background': 'white', 'color': '#1f2937'});

            $(this).addClass('active').css({'background': '#4f46e5', 'color': 'white'});

            applyFilters();

        });



        // Toggle advanced filters

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

            $('#advanced-filters').slideToggle();

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

        });



        // Time range change

        $('#time-range-filter').on('change', function() {

            if ($(this).val() === 'custom') {

                showCustomDatePicker();

            } else {

                applyFilters();

            }

        });



        // Quick search with debounce

        let searchTimer;

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

            clearTimeout(searchTimer);

            searchTimer = setTimeout(function() {

                applyFilters();

            }, 500);

        });



        // Clear all filters

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

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

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

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

            $('#advanced-filters input').prop('checked', false);

            $('#advanced-filters select').val('');

            applyFilters();

        });



        // Apply advanced filters

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

            applyFilters();

            updateFilterSummary();

        });



        // Main filter function

        function applyFilters() {

            const filters = collectFilters();



            // Show loading

            showLoading();



            // AJAX call to get filtered data

            $.ajax({

                url: ajaxurl,

                type: 'POST',

                data: {

                    action: 'sensfrx_filter_fraud_data',

                    filters: filters,

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

                },

                success: function(response) {

                    if (response.success) {

                        updateTable(response.data);

                        updateResultsSummary(response.data);

                        showSmartSuggestions(response.data);

                    }

                },

                complete: function() {

                    hideLoading();

                }

            });

        }



        // Collect all active filters

        function collectFilters() {

            return {

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

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

                search: $('#quick-search').val(),

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

                orderValue: $('select[name="order-value"]').val(),

                customerType: $('select[name="customer-type"]').val(),

                country: $('select[name="country"]').val(),

                paymentMethod: $('select[name="payment-method"]').val(),

                fraudType: $('select[name="fraud-type"]').val()

            };

        }



        // Update results summary

        function updateResultsSummary(data) {

            const total = data.results.length;

            const blocked = data.results.filter(r => r.status === 'deny').length;

            const review = data.results.filter(r => r.status === 'challenge').length;

            const allowed = data.results.filter(r => r.status === 'allow').length;



            $('#result-count').html(`Showing <strong>${total}</strong> results`);



            let stats = [];

            if (blocked > 0) stats.push(`<span style="color: #ef4444;">${blocked} blocked</span>`);

            if (review > 0) stats.push(`<span style="color: #f59e0b;">${review} under review</span>`);

            if (allowed > 0) stats.push(`<span style="color: #10b981;">${allowed} allowed</span>`);



            $('#result-stats').html(stats.join(', '));

        }



        // Show smart suggestions based on data patterns

        function showSmartSuggestions(data) {

            if (data.suggestions && data.suggestions.length > 0) {

                $('#smart-suggestions').show();

                const pills = data.suggestions.map(s =>

                    `<button class="suggestion-pill" data-filter='${JSON.stringify(s.filter)}'

                             style="padding: 4px 12px; margin: 2px; background: white; border: 1px solid #fbbf24; border-radius: 20px; cursor: pointer;">

                        ${s.label}

                    </button>`

                ).join('');

                $('#suggestion-pills').html(pills);

            } else {

                $('#smart-suggestions').hide();

            }

        }



        // Apply suggested filter

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

            const filter = JSON.parse($(this).attr('data-filter'));

            // Apply the suggested filter

            Object.keys(filter).forEach(key => {

                // Set the filter values based on suggestion

            });

            applyFilters();

        });



        // Update filter summary bar

        function updateFilterSummary() {

            const filters = collectFilters();

            let activeFilters = [];



            if (filters.timeRange !== 'this-week') {

                activeFilters.push(`Time: ${filters.timeRange}`);

            }

            if (filters.status !== 'all') {

                activeFilters.push(`Status: ${filters.status}`);

            }

            if (filters.search) {

                activeFilters.push(`Search: "${filters.search}"`);

            }



            if (activeFilters.length > 0) {

                $('#filter-summary').show();

                $('#active-filter-list').html(

                    activeFilters.map(f =>

                        `<span style="padding: 2px 8px; margin: 0 3px; background: #e5e7eb; border-radius: 12px;">${f}</span>`

                    ).join('')

                );

            } else {

                $('#filter-summary').hide();

            }

        }



        // Initial load

        applyFilters();

    });

    </script>

    <?php

}



/**

 * AJAX handler for filtering fraud data

 */

add_action('wp_ajax_sensfrx_filter_fraud_data', 'sensfrx_handle_filter_fraud_data');

function sensfrx_handle_filter_fraud_data() {

    // Verify nonce

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

        wp_send_json_error('Security check failed');

    }



    $filters = isset( $_POST['filters'] ) ? sanitize_text_field( wp_unslash( $_POST['filters'] ) ) : '';



    // Get filtered data

    $results = sensfrx_get_filtered_fraud_data($filters);



    // Generate smart suggestions based on patterns

    $suggestions = sensfrx_generate_smart_suggestions($results);



    wp_send_json_success([

        'results' => $results,

        'suggestions' => $suggestions,

        'stats' => sensfrx_calculate_filter_stats($results)

    ]);

}



/**

 * Get filtered fraud data based on shop owner friendly filters

 */

function sensfrx_get_filtered_fraud_data($filters) {

    global $wpdb;



    // Build query based on filters

    $where_conditions = [];

    $params = [];



    // Time range filter

    $date_range = sensfrx_parse_time_range($filters['timeRange']);

    if ($date_range) {

        $where_conditions[] = "timestamp BETWEEN %s AND %s";

        $params[] = $date_range['start'];

        $params[] = $date_range['end'];

    }



    // Status filter

    if ($filters['status'] !== 'all') {

        $where_conditions[] = "status = %s";

        $params[] = $filters['status'];

    }



    // Search filter (email, IP, or order ID)

    if (!empty($filters['search'])) {

        $search_term = '%' . $wpdb->esc_like($filters['search']) . '%';

        $where_conditions[] = "(email LIKE %s OR ip_address LIKE %s OR order_id LIKE %s)";

        $params[] = $search_term;

        $params[] = $search_term;

        $params[] = $search_term;

    }



    // Risk level filter

    if (!empty($filters['risk'])) {

        $risk_conditions = [];

        foreach ($filters['risk'] as $risk) {

            switch ($risk) {

                case 'high':

                    $risk_conditions[] = "risk_score >= 70";

                    break;

                case 'medium':

                    $risk_conditions[] = "(risk_score >= 40 AND risk_score < 70)";

                    break;

                case 'low':

                    $risk_conditions[] = "risk_score < 40";

                    break;

            }

        }

        if (!empty($risk_conditions)) {

            $where_conditions[] = "(" . implode(' OR ', $risk_conditions) . ")";

        }

    }



    // For demo mode, return mock data

    if (sensfrx_is_demo_mode()) {

        return sensfrx_get_mock_filtered_data($filters);

    }



    // Real database query would go here

    // For now, return filtered mock data

    return sensfrx_get_mock_filtered_data($filters);

}



/**

 * Parse time range into date boundaries

 */

function sensfrx_parse_time_range($range) {

    $now = current_time('timestamp');



    switch ($range) {

        case 'today':

            return [

                'start' => date('Y-m-d 00:00:00', $now),

                'end' => date('Y-m-d 23:59:59', $now)

            ];

        case 'yesterday':

            return [

                'start' => date('Y-m-d 00:00:00', strtotime('-1 day', $now)),

                'end' => date('Y-m-d 23:59:59', strtotime('-1 day', $now))

            ];

        case 'this-week':

            return [

                'start' => date('Y-m-d 00:00:00', strtotime('this week', $now)),

                'end' => date('Y-m-d 23:59:59', $now)

            ];

        case 'last-week':

            return [

                'start' => date('Y-m-d 00:00:00', strtotime('last week', $now)),

                'end' => date('Y-m-d 23:59:59', strtotime('last week +6 days', $now))

            ];

        case 'this-month':

            return [

                'start' => date('Y-m-01 00:00:00', $now),

                'end' => date('Y-m-d 23:59:59', $now)

            ];

        case 'last-month':

            return [

                'start' => date('Y-m-01 00:00:00', strtotime('last month', $now)),

                'end' => date('Y-m-t 23:59:59', strtotime('last month', $now))

            ];

        case 'last-30-days':

            return [

                'start' => date('Y-m-d 00:00:00', strtotime('-30 days', $now)),

                'end' => date('Y-m-d 23:59:59', $now)

            ];

        default:

            return null;

    }

}



/**

 * Generate smart suggestions based on data patterns

 */

function sensfrx_generate_smart_suggestions($data) {

    $suggestions = [];



    // Count patterns

    $high_risk_count = count(array_filter($data, function($item) {

        return isset($item['risk_score']) && $item['risk_score'] >= 70;

    }));



    $repeat_offenders = [];

    $ip_counts = array_count_values(array_column($data, 'ip_address'));

    foreach ($ip_counts as $ip => $count) {

        if ($count > 2) {

            $repeat_offenders[] = $ip;

        }

    }



    // Generate suggestions

    if ($high_risk_count > 5) {

        $suggestions[] = [

            'label' => '🔴 Show only high-risk threats',

            'filter' => ['risk' => ['high'], 'status' => 'deny']

        ];

    }



    if (!empty($repeat_offenders)) {

        $suggestions[] = [

            'label' => '🔄 Show repeat offenders',

            'filter' => ['search' => $repeat_offenders[0]]

        ];

    }



    // Check for patterns by time

    $today_count = count(array_filter($data, function($item) {

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

    }));



    if ($today_count > 10) {

        $suggestions[] = [

            'label' => '⚠️ Unusual activity today',

            'filter' => ['timeRange' => 'today', 'status' => 'deny']

        ];

    }



    return $suggestions;

}



/**

 * Get mock filtered data for demo

 */

function sensfrx_get_mock_filtered_data($filters) {

    // Generate realistic mock data based on filters

    $data = [];

    $count = rand(5, 20);



    for ($i = 0; $i < $count; $i++) {

        $risk_score = rand(20, 95);

        $status = $risk_score > 70 ? 'deny' : ($risk_score > 50 ? 'challenge' : 'allow');



        // Apply status filter

        if ($filters['status'] !== 'all' && $status !== $filters['status']) {

            continue;

        }



        $data[] = [

            'id' => 'order_' . rand(1000, 9999),

            'email' => 'customer' . rand(1, 100) . '@example.com',

            'ip_address' => rand(1, 255) . '.' . rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255),

            'risk_score' => $risk_score,

            'status' => $status,

            'order_value' => rand(50, 500),

            'timestamp' => date('Y-m-d H:i:s', strtotime('-' . rand(0, 7) . ' days')),

            'country' => ['US', 'GB', 'CA', 'AU'][rand(0, 3)],

            'fraud_type' => ['Card Testing', 'Address Mismatch', 'Velocity Check', 'Bot Activity'][rand(0, 3)],

            'customer_type' => ['new', 'returning'][rand(0, 1)]

        ];

    }



    return $data;

}