<?php

/**

 * SensFRX Fraud Management - Export & Bulk Actions

 * Shop owner friendly export and bulk management features

 */



/**

 * Add export and bulk action buttons to fraud management

 */

add_action('sensfrx_fraud_management_after_filters', 'sensfrx_render_export_bulk_actions');



function sensfrx_render_export_bulk_actions() {

    ?>

    <!-- Export & Bulk Actions Bar -->

    <div id="sensfrx-action-bar" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding: 15px; background: white; border: 1px solid #e5e7eb; border-radius: 8px;">



        <!-- Bulk Actions (Left Side) -->

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

            <input type="checkbox" id="select-all" style="margin-right: 5px;">

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



            <select id="bulk-action" style="padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 6px;" disabled>

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

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

                <option value="trust">✅ Add to Trust List</option>

                <option value="review">⚠️ Mark for Review</option>

                <option value="export">📊 Export Selected</option>

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

            </select>



            <button id="apply-bulk" class="button" style="padding: 6px 16px; background: #4f46e5; color: white; border: none; border-radius: 6px;" disabled>

                Apply

            </button>



            <span id="selection-count" style="color: #6b7280; font-size: 14px;">

                <!-- Shows "3 items selected" -->

            </span>

        </div>



        <!-- Export Options (Right Side) -->

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

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



            <!-- Quick Export Buttons -->

            <button class="export-btn" data-format="csv" style="padding: 6px 12px; background: white; border: 1px solid #10b981; color: #10b981; border-radius: 6px; cursor: pointer;">

                📄 CSV

            </button>



            <button class="export-btn" data-format="excel" style="padding: 6px 12px; background: white; border: 1px solid #10b981; color: #10b981; border-radius: 6px; cursor: pointer;">

                📊 Excel

            </button>



            <button class="export-btn" data-format="pdf" style="padding: 6px 12px; background: white; border: 1px solid #10b981; color: #10b981; border-radius: 6px; cursor: pointer;">

                📑 PDF Report

            </button>



            <!-- Advanced Export -->

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

                ⚙️ Custom Export

            </button>

        </div>

    </div>



    <!-- Custom Export Modal -->

    <div id="export-modal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">

        <div class="modal-content" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 8px; max-width: 500px; width: 90%;">

            <h2 style="margin-top: 0;">📊 Custom Export Options</h2>



            <!-- Date Range -->

            <div class="export-field" style="margin-bottom: 20px;">

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

                <select id="export-date-range" style="width: 100%; padding: 8px; border: 1px solid #d1d5db; border-radius: 6px;">

                    <option value="current">Current Filter Results</option>

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

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

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

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

                </select>

            </div>



            <!-- Fields to Include -->

            <div class="export-field" style="margin-bottom: 20px;">

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

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">

                    <label><input type="checkbox" name="export_fields[]" value="timestamp" checked> Date/Time</label>

                    <label><input type="checkbox" name="export_fields[]" value="email" checked> Email</label>

                    <label><input type="checkbox" name="export_fields[]" value="ip_address" checked> IP Address</label>

                    <label><input type="checkbox" name="export_fields[]" value="risk_score" checked> Risk Score</label>

                    <label><input type="checkbox" name="export_fields[]" value="status" checked> Status</label>

                    <label><input type="checkbox" name="export_fields[]" value="order_value" checked> Order Value</label>

                    <label><input type="checkbox" name="export_fields[]" value="country"> Country</label>

                    <label><input type="checkbox" name="export_fields[]" value="fraud_type"> Fraud Type</label>

                    <label><input type="checkbox" name="export_fields[]" value="device_info"> Device Info</label>

                    <label><input type="checkbox" name="export_fields[]" value="notes"> Notes</label>

                </div>

            </div>



            <!-- Format Options -->

            <div class="export-field" style="margin-bottom: 20px;">

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

                <div style="display: flex; gap: 10px;">

                    <label style="flex: 1;">

                        <input type="radio" name="export_format" value="csv" checked>

                        <span>CSV (Excel Compatible)</span>

                    </label>

                    <label style="flex: 1;">

                        <input type="radio" name="export_format" value="xlsx">

                        <span>Excel (.xlsx)</span>

                    </label>

                    <label style="flex: 1;">

                        <input type="radio" name="export_format" value="pdf">

                        <span>PDF Report</span>

                    </label>

                </div>

            </div>



            <!-- Additional Options -->

            <div class="export-field" style="margin-bottom: 20px;">

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

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

                    <input type="checkbox" name="include_summary" checked>

                    Include summary statistics

                </label>

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

                    <input type="checkbox" name="email_export">

                    Email export to: <input type="email" placeholder="admin@example.com" style="padding: 4px; border: 1px solid #d1d5db; border-radius: 4px;">

                </label>

            </div>



            <!-- Modal Actions -->

            <div style="display: flex; justify-content: flex-end; gap: 10px;">

                <button id="cancel-export" style="padding: 8px 16px; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer;">

                    Cancel

                </button>

                <button id="confirm-export" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">

                    Export Now

                </button>

            </div>

        </div>

    </div>



    <!-- Quick View Modal (for reviewing items) -->

    <div id="quick-view-modal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">

        <div class="modal-content" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 8px; max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto;">

            <h2 style="margin-top: 0;">🔍 Fraud Details</h2>

            <div id="quick-view-content">

                <!-- Dynamic content will be loaded here -->

            </div>

            <div style="margin-top: 20px; display: flex; justify-content: space-between;">

                <div>

                    <button class="quick-action-btn" data-action="block" style="padding: 8px 16px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer;">

                        🚫 Block

                    </button>

                    <button class="quick-action-btn" data-action="trust" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">

                        ✅ Trust

                    </button>

                </div>

                <button id="close-quick-view" style="padding: 8px 16px; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer;">

                    Close

                </button>

            </div>

        </div>

    </div>



    <!-- JavaScript for Export and Bulk Actions -->

    <script>

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

        let selectedItems = new Set();



        // Select all checkbox

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

            const isChecked = $(this).is(':checked');

            $('.fraud-item-checkbox').prop('checked', isChecked);



            if (isChecked) {

                $('.fraud-item-checkbox').each(function() {

                    selectedItems.add($(this).val());

                });

            } else {

                selectedItems.clear();

            }



            updateSelectionUI();

        });



        // Individual checkbox selection

        $(document).on('change', '.fraud-item-checkbox', function() {

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

            if ($(this).is(':checked')) {

                selectedItems.add(value);

            } else {

                selectedItems.delete(value);

            }

            updateSelectionUI();

        });



        // Update UI based on selection

        function updateSelectionUI() {

            const count = selectedItems.size;



            if (count > 0) {

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

                $('#selection-count').text(`${count} item${count > 1 ? 's' : ''} selected`);

            } else {

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

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

            }



            // Update select-all checkbox state

            const totalCheckboxes = $('.fraud-item-checkbox').length;

            if (count === totalCheckboxes && totalCheckboxes > 0) {

                $('#select-all').prop('checked', true).prop('indeterminate', false);

            } else if (count > 0) {

                $('#select-all').prop('checked', false).prop('indeterminate', true);

            } else {

                $('#select-all').prop('checked', false).prop('indeterminate', false);

            }

        }



        // Apply bulk action

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

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

            if (!action || selectedItems.size === 0) return;



            const itemsArray = Array.from(selectedItems);



            if (action === 'delete' && !confirm(`Are you sure you want to delete ${itemsArray.length} items?`)) {

                return;

            }



            // Show loading

            $(this).text('Processing...').prop('disabled', true);



            $.ajax({

                url: ajaxurl,

                type: 'POST',

                data: {

                    action: 'sensfrx_bulk_action',

                    bulk_action: action,

                    items: itemsArray,

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

                },

                success: function(response) {

                    if (response.success) {

                        showNotification(response.data.message, 'success');



                        // Clear selection and reload data

                        selectedItems.clear();

                        $('#select-all').prop('checked', false);

                        updateSelectionUI();



                        // Reload the table

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

                            applyFilters();

                        }

                    } else {

                        showNotification('Error: ' + response.data, 'error');

                    }

                },

                complete: function() {

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

                }

            });

        });



        // Quick export buttons

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

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

            exportData(format, 'current');

        });



        // Advanced export modal

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

            $('#export-modal').fadeIn();

        });



        $('#cancel-export, #export-modal').on('click', function(e) {

            if (e.target === this) {

                $('#export-modal').fadeOut();

            }

        });



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

            const fields = $('input[name="export_fields[]"]:checked').map(function() {

                return $(this).val();

            }).get();



            const format = $('input[name="export_format"]:checked').val();

            const dateRange = $('#export-date-range').val();

            const includeSummary = $('input[name="include_summary"]').is(':checked');



            exportData(format, dateRange, fields, includeSummary);

            $('#export-modal').fadeOut();

        });



        // Export function

        function exportData(format, dateRange, fields, includeSummary) {

            // Show loading

            showNotification('Generating export...', 'info');



            // Collect current filters

            const filters = typeof collectFilters === 'function' ? collectFilters() : {};



            $.ajax({

                url: ajaxurl,

                type: 'POST',

                data: {

                    action: 'sensfrx_export_fraud_data',

                    format: format,

                    date_range: dateRange,

                    fields: fields || [],

                    include_summary: includeSummary,

                    filters: filters,

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

                },

                xhrFields: {

                    responseType: 'blob'

                },

                success: function(blob, status, xhr) {

                    // Create download link

                    const filename = xhr.getResponseHeader('Content-Disposition')?.split('filename=')[1] ||

                                   `fraud-export-${Date.now()}.${format}`;



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

                    link.href = window.URL.createObjectURL(blob);

                    link.download = filename;

                    link.click();



                    showNotification('Export completed!', 'success');

                },

                error: function() {

                    showNotification('Export failed. Please try again.', 'error');

                }

            });

        }



        // Show notification

        function showNotification(message, type) {

            const bgColor = {

                'success': '#10b981',

                'error': '#ef4444',

                'info': '#3b82f6',

                'warning': '#f59e0b'

            }[type] || '#6b7280';



            const notification = $(`

                <div style="position: fixed; top: 20px; right: 20px; padding: 12px 20px;

                           background: ${bgColor}; color: white; border-radius: 6px;

                           box-shadow: 0 4px 6px rgba(0,0,0,0.1); z-index: 10000;">

                    ${message}

                </div>

            `);



            $('body').append(notification);

            setTimeout(() => notification.fadeOut(() => notification.remove()), 3000);

        }



        // Quick view functionality

        $(document).on('click', '.quick-view-btn', function() {

            const itemId = $(this).data('id');

            loadQuickView(itemId);

        });



        function loadQuickView(itemId) {

            $('#quick-view-modal').fadeIn();

            $('#quick-view-content').html('<p>Loading...</p>');



            $.ajax({

                url: ajaxurl,

                type: 'POST',

                data: {

                    action: 'sensfrx_get_fraud_details',

                    item_id: itemId,

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

                },

                success: function(response) {

                    if (response.success) {

                        $('#quick-view-content').html(response.data.html);

                    } else {

                        $('#quick-view-content').html('<p>Error loading details.</p>');

                    }

                }

            });

        }



        $('#close-quick-view').on('click', function() {

            $('#quick-view-modal').fadeOut();

        });



        // Quick action buttons in modal

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

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

            const itemId = $('#quick-view-content').data('item-id');



            // Process action

            processQuickAction(action, itemId);

            $('#quick-view-modal').fadeOut();

        });

    });

    </script>

    <?php

}



/**

 * Handle bulk actions AJAX

 */

add_action('wp_ajax_sensfrx_bulk_action', 'sensfrx_handle_bulk_action');

function sensfrx_handle_bulk_action() {

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

        wp_send_json_error('Security check failed');

    }



    $action = sanitize_text_field($_POST['bulk_action']);

    $items = array_map('sanitize_text_field', $_POST['items']);



    $result = sensfrx_process_bulk_action($action, $items);



    if ($result['success']) {

        wp_send_json_success([

            'message' => $result['message'],

            'processed' => $result['processed']

        ]);

    } else {

        wp_send_json_error($result['message']);

    }

}



/**

 * Process bulk actions

 */

function sensfrx_process_bulk_action($action, $items) {

    $processed = 0;



    foreach ($items as $item) {

        switch ($action) {

            case 'block':

                // Add to blacklist

                sensfrx_add_to_blacklist_bulk($item);

                $processed++;

                break;



            case 'trust':

                // Add to whitelist

                sensfrx_add_to_whitelist_bulk($item);

                $processed++;

                break;



            case 'review':

                // Mark for review

                sensfrx_mark_for_review($item);

                $processed++;

                break;



            case 'delete':

                // Delete record

                sensfrx_delete_fraud_record($item);

                $processed++;

                break;

        }

    }



    $action_labels = [

        'block' => 'blocked',

        'trust' => 'added to trust list',

        'review' => 'marked for review',

        'delete' => 'deleted'

    ];



    return [

        'success' => true,

        'message' => sprintf('%d item%s %s successfully',

            $processed,

            $processed > 1 ? 's' : '',

            $action_labels[$action]

        ),

        'processed' => $processed

    ];

}



/**

 * Handle export AJAX

 */

add_action('wp_ajax_sensfrx_export_fraud_data', 'sensfrx_handle_export_fraud_data');

function sensfrx_handle_export_fraud_data() {

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

        wp_send_json_error('Security check failed');

    }



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

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

    $fields = array_map('sanitize_text_field', $_POST['fields'] ?? []);

    $include_summary = !empty($_POST['include_summary']);

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



    // Get data to export

    $data = sensfrx_get_export_data($filters, $date_range);



    switch ($format) {

        case 'csv':

            sensfrx_export_csv($data, $fields, $include_summary);

            break;

        case 'excel':

            sensfrx_export_excel($data, $fields, $include_summary);

            break;

        case 'pdf':

            sensfrx_export_pdf($data, $fields, $include_summary);

            break;

    }

}



/**

 * Export as CSV

 */

function sensfrx_export_csv($data, $fields, $include_summary) {

    $filename = 'fraud-export-' . date('Y-m-d-His') . '.csv';



    header('Content-Type: text/csv');

    header('Content-Disposition: attachment; filename="' . $filename . '"');



    $output = fopen('php://output', 'w');



    // Add summary if requested

    if ($include_summary) {

        fputcsv($output, ['Summary Report'], ',', '"', '\\');

        fputcsv($output, ['Total Records:', count($data)], ',', '"', '\\');

        fputcsv($output, ['Date Generated:', date('Y-m-d H:i:s')], ',', '"', '\\');

        fputcsv($output, [], ',', '"', '\\'); // Empty row

    }



    // Headers

    if (empty($fields)) {

        $fields = ['timestamp', 'email', 'ip_address', 'risk_score', 'status', 'order_value'];

    }



    $headers = array_map(function($field) {

        return ucwords(str_replace('_', ' ', $field));

    }, $fields);



    fputcsv($output, $headers, ',', '"', '\\');



    // Data rows

    foreach ($data as $row) {

        $csv_row = [];

        foreach ($fields as $field) {

            $csv_row[] = $row[$field] ?? '';

        }

        fputcsv($output, $csv_row, ',', '"', '\\');

    }



    fclose($output);

    exit;

}