<?php

/**

 * SensFRX Fraud Management Table - Shop Owner Friendly Display

 * Visual, intuitive fraud data presentation

 */



/**

 * Render the fraud management table with shop owner friendly display

 */

function sensfrx_render_fraud_management_table($data = null) {

    // Get data if not provided

    if ($data === null) {

        $data = sensfrx_get_fraud_table_data();

    }

    ?>



    <!-- Fraud Management Table -->

    <div id="sensfrx-fraud-table-container">



        <!-- Table Controls -->

        <div class="table-controls" style="display: flex; justify-content: space-between; margin-bottom: 15px;">

            <div class="view-options">

                <label style="margin-right: 10px;">

                    <input type="radio" name="view-mode" value="detailed" checked> Detailed View

                </label>

                <label style="margin-right: 10px;">

                    <input type="radio" name="view-mode" value="compact"> Compact View

                </label>

                <label>

                    <input type="radio" name="view-mode" value="cards"> Card View

                </label>

            </div>



            <div class="per-page">

                Show:

                <select id="per-page" style="padding: 4px; border: 1px solid #d1d5db; border-radius: 4px;">

                    <option value="10">10</option>

                    <option value="25" selected>25</option>

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

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

                </select>

                per page

            </div>

        </div>



        <!-- Main Table -->

        <table id="fraud-management-table" class="sensfrx-table" style="width: 100%; border-collapse: separate; border-spacing: 0; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">

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

                <tr>

                    <th style="padding: 12px; text-align: left;">

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

                    </th>

                    <th style="padding: 12px; text-align: left;">Time</th>

                    <th style="padding: 12px; text-align: left;">Customer</th>

                    <th style="padding: 12px; text-align: left;">Risk</th>

                    <th style="padding: 12px; text-align: left;">Threat Type</th>

                    <th style="padding: 12px; text-align: left;">Value</th>

                    <th style="padding: 12px; text-align: left;">Status</th>

                    <th style="padding: 12px; text-align: center;">Actions</th>

                </tr>

            </thead>

            <tbody>

                <?php foreach ($data as $index => $item): ?>

                <tr class="fraud-row" data-id="<?php echo esc_attr($item['id']); ?>"

                    style="border-bottom: 1px solid #f3f4f6; <?php echo $index % 2 ? 'background: #fafafa;' : ''; ?>">



                    <!-- Checkbox -->

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

                        <input type="checkbox" class="fraud-item-checkbox" value="<?php echo esc_attr($item['id']); ?>">

                    </td>



                    <!-- Time (Human Friendly) -->

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

                        <div style="font-weight: 500;"><?php echo esc_html( sensfrx_human_time_diff($item['timestamp']) ); ?></div>

                        <div style="font-size: 12px; color: #6b7280;"><?php echo esc_html( date('M j, g:i a', strtotime($item['timestamp'])) ); ?></div>

                    </td>



                    <!-- Customer Info -->

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

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

                            <!-- Customer Avatar/Icon -->

                            <div style="width: 40px; height: 40px; border-radius: 50%; background: <?php echo esc_html( sensfrx_get_customer_color($item['email']) ); ?>; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold;">

                                <?php echo esc_html( strtoupper(substr($item['email'], 0, 1)) ); ?>

                            </div>

                            <div>

                                <div style="font-weight: 500;">

                                    <?php echo esc_html($item['email']); ?>

                                    <?php if ($item['customer_type'] === 'new'): ?>

                                        <span style="background: #dbeafe; color: #1e40af; padding: 2px 6px; border-radius: 4px; font-size: 11px; margin-left: 5px;">NEW</span>

                                    <?php elseif ($item['customer_type'] === 'vip'): ?>

                                        <span style="background: #fef3c7; color: #92400e; padding: 2px 6px; border-radius: 4px; font-size: 11px; margin-left: 5px;">⭐ VIP</span>

                                    <?php endif; ?>

                                </div>

                                <div style="font-size: 12px; color: #6b7280;">

                                    IP: <?php echo esc_html($item['ip_address']); ?>

                                    <?php if (!empty($item['country'])): ?>

                                        · <?php echo esc_html( sensfrx_get_country_flag($item['country']) ); ?> <?php echo esc_html($item['country']); ?>

                                    <?php endif; ?>

                                </div>

                            </div>

                        </div>

                    </td>



                    <!-- Risk Score (Visual) -->

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

                        <?php

                        $risk_color = $item['risk_score'] >= 60 ? '#ef4444' : ($item['risk_score'] >= 30 ? '#f59e0b' : '#10b981');

                        $risk_label = $item['risk_score'] >= 60 ? 'High' : ($item['risk_score'] >= 30 ? 'Medium' : 'Low');

                        ?>

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

                            <!-- Risk Score Bar -->

                            <div style="width: 60px; height: 8px; background: #e5e7eb; border-radius: 4px; overflow: hidden;">

                                <div style="width: <?php echo esc_html( $item['risk_score'] ); ?>%; height: 100%; background: <?php echo esc_html( $risk_color ); ?>;"></div>

                            </div>

                            <!-- Score Number -->

                            <span style="font-weight: 600; color: <?php echo esc_html( $risk_color ); ?>;">

                                <?php echo esc_html( $item['risk_score'] ); ?>%

                            </span>

                        </div>

                        <div style="font-size: 12px; color: <?php echo esc_html( $risk_color ); ?>; margin-top: 2px;">

                            <?php echo esc_html( $risk_label ); ?> Risk

                        </div>

                    </td>



                    <!-- Threat Type (Icon + Label) -->

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

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

                            <?php echo esc_html( sensfrx_get_threat_icon($item['fraud_type']) ); ?>

                            <span><?php echo esc_html($item['fraud_type']); ?></span>

                        </div>

                        <?php if (!empty($item['fraud_details'])): ?>

                            <div style="font-size: 12px; color: #6b7280; margin-top: 2px;">

                                <?php echo esc_html($item['fraud_details']); ?>

                            </div>

                        <?php endif; ?>

                    </td>



                    <!-- Order Value -->

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

                        <?php if (!empty($item['order_value'])): ?>

                            <div style="font-weight: 600; font-size: 16px;">

                                $<?php echo number_format($item['order_value'], 2); ?>

                            </div>

                            <?php if ($item['order_value'] > 500): ?>

                                <span style="background: #fee2e2; color: #991b1b; padding: 2px 6px; border-radius: 4px; font-size: 11px;">Large Order</span>

                            <?php endif; ?>

                        <?php else: ?>

                            <span style="color: #9ca3af;">N/A</span>

                        <?php endif; ?>

                    </td>



                    <!-- Status (Visual Badge) -->

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

                        <?php

                        $status_config = [

                            'deny' => ['color' => '#ef4444', 'bg' => '#fee2e2', 'icon' => '🚫', 'label' => 'Blocked'],

                            'challenge' => ['color' => '#f59e0b', 'bg' => '#fef3c7', 'icon' => '⚠️', 'label' => 'Review'],

                            'allow' => ['color' => '#10b981', 'bg' => '#d1fae5', 'icon' => '✅', 'label' => 'Allowed'],

                            'processing' => ['color' => '#3b82f6', 'bg' => '#dbeafe', 'icon' => '⏳', 'label' => 'Processing']

                        ];

                        $status = $status_config[$item['status']] ?? $status_config['processing'];

                        ?>

                        <div style="display: inline-block; padding: 6px 12px; background: <?php echo esc_html( $status['bg'] ); ?>; color: <?php echo esc_html( $status['color'] ); ?>; border-radius: 20px; font-weight: 500; font-size: 14px;">

                            <?php echo esc_html( $status['icon'] ); ?> <?php echo esc_html( $status['label'] ); ?>

                        </div>

                    </td>



                    <!-- Actions (Quick Actions) -->

                    <td style="padding: 12px; text-align: center;">

                        <div class="action-buttons" style="display: flex; gap: 5px; justify-content: center;">



                            <!-- View Details -->

                            <button class="action-btn view-details" data-id="<?php echo esc_attr($item['id']); ?>"

                                    style="padding: 6px 10px; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer;"

                                    title="View Details">

                                👁️

                            </button>



                            <?php if ($item['status'] === 'challenge'): ?>

                                <!-- Approve -->

                                <button class="action-btn quick-approve" data-id="<?php echo esc_attr($item['id']); ?>"

                                        style="padding: 6px 10px; background: #d1fae5; border: 1px solid #10b981; border-radius: 6px; cursor: pointer;"

                                        title="Approve">

                                    ✅

                                </button>



                                <!-- Block -->

                                <button class="action-btn quick-block" data-id="<?php echo esc_attr($item['id']); ?>"

                                        style="padding: 6px 10px; background: #fee2e2; border: 1px solid #ef4444; border-radius: 6px; cursor: pointer;"

                                        title="Block">

                                    🚫

                                </button>

                            <?php elseif ($item['status'] === 'allow'): ?>

                                <!-- Add to blacklist -->

                                <button class="action-btn add-blacklist" data-email="<?php echo esc_attr($item['email']); ?>" data-ip="<?php echo esc_attr($item['ip_address']); ?>"

                                        style="padding: 6px 10px; background: #fee2e2; border: 1px solid #ef4444; border-radius: 6px; cursor: pointer;"

                                        title="Block This Customer">

                                    🚫

                                </button>

                            <?php elseif ($item['status'] === 'deny'): ?>

                                <!-- Add to whitelist -->

                                <button class="action-btn add-whitelist" data-email="<?php echo esc_attr($item['email']); ?>" data-ip="<?php echo esc_attr($item['ip_address']); ?>"

                                        style="padding: 6px 10px; background: #d1fae5; border: 1px solid #10b981; border-radius: 6px; cursor: pointer;"

                                        title="Trust This Customer">

                                    ✅

                                </button>

                            <?php endif; ?>



                            <!-- More Options -->

                            <button class="action-btn more-options" data-id="<?php echo esc_attr($item['id']); ?>"

                                    style="padding: 6px 10px; background: white; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer;"

                                    title="More Options">

                                ⋮

                            </button>

                        </div>

                    </td>

                </tr>

                <?php endforeach; ?>

            </tbody>

        </table>



        <!-- Empty State -->

        <?php if (empty($data)): ?>

        <div class="empty-state" style="text-align: center; padding: 60px 20px; background: white; border-radius: 8px; margin-top: 20px;">

            <div style="font-size: 48px; margin-bottom: 20px;">🛡️</div>

            <h3 style="font-size: 20px; margin-bottom: 10px;">No Fraud Attempts Found</h3>

            <p style="color: #6b7280;">Great news! No suspicious activity has been detected based on your current filters.</p>

            <button onclick="clearFilters()" style="margin-top: 20px; padding: 10px 20px; background: #4f46e5; color: white; border: none; border-radius: 6px; cursor: pointer;">

                Clear Filters

            </button>

        </div>

        <?php endif; ?>



        <!-- Pagination -->

        <div class="pagination" style="display: flex; justify-content: space-between; align-items: center; margin-top: 20px; padding: 15px; background: white; border-radius: 8px;">

            <div class="pagination-info" style="color: #6b7280;">

                Showing <strong>1-<?php echo esc_html( min(25, count($data)) ); ?></strong> of <strong><?php echo count($data); ?></strong> results

            </div>



            <div class="pagination-controls" style="display: flex; gap: 5px;">

                <button class="page-btn" data-page="prev" style="padding: 8px 12px; background: white; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer;">

                    ← Previous

                </button>



                <?php for ($i = 1; $i <= min(5, ceil(count($data) / 25)); $i++): ?>

                <button class="page-btn" data-page="<?php echo esc_html( $i ); ?>"

                        style="padding: 8px 12px; background: <?php echo $i === 1 ? '#4f46e5' : 'white'; ?>;

                               color: <?php echo $i === 1 ? 'white' : '#1f2937'; ?>;

                               border: 1px solid <?php echo $i === 1 ? '#4f46e5' : '#d1d5db'; ?>;

                               border-radius: 6px; cursor: pointer;">

                    <?php echo esc_html( $i ); ?>

                </button>

                <?php endfor; ?>



                <button class="page-btn" data-page="next" style="padding: 8px 12px; background: white; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer;">

                    Next →

                </button>

            </div>

        </div>

    </div>



    <!-- More Options Dropdown Menu -->

    <div id="more-options-menu" style="display: none; position: absolute; background: white; border: 1px solid #e5e7eb; border-radius: 6px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); z-index: 1000; min-width: 150px;">

        <a href="#" class="menu-item" data-action="view-order" style="display: block; padding: 8px 12px; color: #1f2937; text-decoration: none; border-bottom: 1px solid #f3f4f6;">

            🛒 View Order

        </a>

        <a href="#" class="menu-item" data-action="view-customer" style="display: block; padding: 8px 12px; color: #1f2937; text-decoration: none; border-bottom: 1px solid #f3f4f6;">

            👤 View Customer

        </a>

        <a href="#" class="menu-item" data-action="add-note" style="display: block; padding: 8px 12px; color: #1f2937; text-decoration: none; border-bottom: 1px solid #f3f4f6;">

            📝 Add Note

        </a>

        <a href="#" class="menu-item" data-action="export-details" style="display: block; padding: 8px 12px; color: #1f2937; text-decoration: none;">

            📊 Export Details

        </a>

    </div>



    <script>

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

        // Row hover effect

        $('.fraud-row').hover(

            function() { $(this).css('background', '#f9fafb'); },

            function() { $(this).css('background', $(this).index() % 2 ? '#fafafa' : 'white'); }

        );



        // Quick actions

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

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

            processQuickAction('approve', id, $(this));

        });



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

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

            processQuickAction('block', id, $(this));

        });



        $('.add-blacklist').on('click', function() {

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

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



            if (confirm(`Block this customer?\n\nEmail: ${email}\nIP: ${ip}`)) {

                addToList('blacklist', email, ip, $(this));

            }

        });



        $('.add-whitelist').on('click', function() {

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

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



            if (confirm(`Trust this customer?\n\nEmail: ${email}\nIP: ${ip}`)) {

                addToList('whitelist', email, ip, $(this));

            }

        });



        // View details

        $('.view-details').on('click', function() {

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

            showDetailsModal(id);

        });



        // More options menu

        $('.more-options').on('click', function(e) {

            e.stopPropagation();

            const $menu = $('#more-options-menu');

            const $btn = $(this);

            const offset = $btn.offset();



            $menu.css({

                top: offset.top + $btn.outerHeight(),

                left: offset.left - $menu.outerWidth() + $btn.outerWidth()

            }).toggle();



            $menu.data('target-id', $(this).data('id'));

        });



        // Close menu when clicking outside

        $(document).on('click', function() {

            $('#more-options-menu').hide();

        });



        // Menu item clicks

        $('.menu-item').on('click', function(e) {

            e.preventDefault();

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

            const targetId = $('#more-options-menu').data('target-id');



            handleMenuAction(action, targetId);

            $('#more-options-menu').hide();

        });



        // View mode toggle

        $('input[name="view-mode"]').on('change', function() {

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

            changeViewMode(mode);

        });



        // Pagination

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

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

            loadPage(page);

        });



        // Helper functions

        function processQuickAction(action, id, $button) {

            $button.prop('disabled', true).text('...');



            $.ajax({

                url: ajaxurl,

                type: 'POST',

                data: {

                    action: 'sensfrx_quick_action',

                    quick_action: action,

                    item_id: id,

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

                },

                success: function(response) {

                    if (response.success) {

                        // Update row status

                        const $row = $button.closest('.fraud-row');

                        $row.fadeOut(300, function() {

                            $row.remove();

                        });



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

                    } else {

                        showNotification('Action failed', 'error');

                        $button.prop('disabled', false);

                    }

                }

            });

        }



        function addToList(listType, email, ip, $button) {

            $button.prop('disabled', true);



            $.ajax({

                url: ajaxurl,

                type: 'POST',

                data: {

                    action: 'sensfrx_add_to_list',

                    list_type: listType,

                    email: email,

                    ip: ip,

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

                },

                success: function(response) {

                    if (response.success) {

                        $button.text(listType === 'blacklist' ? '🚫 Blocked' : '✅ Trusted')

                               .css('opacity', '0.5')

                               .prop('disabled', true);



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

                    } else {

                        showNotification('Failed to update list', 'error');

                        $button.prop('disabled', false);

                    }

                }

            });

        }

    });

    </script>

    <?php

}



/**

 * Helper Functions

 */



function sensfrx_human_time_diff($timestamp) {

    $time_diff = current_time('timestamp') - strtotime($timestamp);



    if ($time_diff < 60) {

        return 'Just now';

    } elseif ($time_diff < 3600) {

        $minutes = floor($time_diff / 60);

        return $minutes . ' min' . ($minutes > 1 ? 's' : '') . ' ago';

    } elseif ($time_diff < 86400) {

        $hours = floor($time_diff / 3600);

        return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';

    } elseif ($time_diff < 604800) {

        $days = floor($time_diff / 86400);

        return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';

    } else {

        return date('M j', strtotime($timestamp));

    }

}



function sensfrx_get_customer_color($email) {

    // Generate consistent color based on email

    $colors = ['#ef4444', '#f59e0b', '#10b981', '#3b82f6', '#8b5cf6', '#ec4899'];

    $index = crc32($email) % count($colors);

    return $colors[$index];

}



function sensfrx_get_country_flag($country_code) {

    $flags = [

        'US' => '🇺🇸',

        'GB' => '🇬🇧',

        'CA' => '🇨🇦',

        'AU' => '🇦🇺',

        'DE' => '🇩🇪',

        'FR' => '🇫🇷',

        'JP' => '🇯🇵',

        'CN' => '🇨🇳',

        'IN' => '🇮🇳',

        'BR' => '🇧🇷'

    ];

    return $flags[$country_code] ?? '🌍';

}



function sensfrx_get_threat_icon($threat_type) {

    $icons = [

        'Card Testing' => '💳',

        'Account Takeover' => '🔓',

        'Bot Activity' => '🤖',

        'Address Mismatch' => '📍',

        'Velocity Check' => '⚡',

        'Fake Account' => '👤',

        'High Risk Country' => '🌍',

        'Disposable Email' => '📧',

        'VPN/Proxy' => '🔒'

    ];

    return $icons[$threat_type] ?? '⚠️';

}



function sensfrx_get_fraud_table_data() {

    // Check if in demo mode

    if (sensfrx_is_demo_mode()) {

        // Return demo data with clear indicators

        return sensfrx_get_demo_table_data();

    }



    // Get real data from API or database

    // This would connect to your actual data source

    return [];

}



function sensfrx_get_demo_table_data() {

    // Generate realistic demo data for shop owners

    return [

        [

            'id' => 'demo_001',

            'timestamp' => date('Y-m-d H:i:s', strtotime('-2 hours')),

            'email' => 'suspicious.buyer@tempmail.com',

            'ip_address' => '192.168.1.100',

            'risk_score' => 85,

            'status' => 'deny',

            'fraud_type' => 'Disposable Email',

            'fraud_details' => 'Temporary email service detected',

            'order_value' => 750.00,

            'country' => 'US',

            'customer_type' => 'new'

        ],

        [

            'id' => 'demo_002',

            'timestamp' => date('Y-m-d H:i:s', strtotime('-4 hours')),

            'email' => 'john.doe@gmail.com',

            'ip_address' => '10.0.0.50',

            'risk_score' => 55,

            'status' => 'challenge',

            'fraud_type' => 'Address Mismatch',

            'fraud_details' => 'Billing and shipping addresses don\'t match',

            'order_value' => 325.50,

            'country' => 'CA',

            'customer_type' => 'returning'

        ],

        [

            'id' => 'demo_003',

            'timestamp' => date('Y-m-d H:i:s', strtotime('-1 day')),

            'email' => 'trusted.customer@company.com',

            'ip_address' => '172.16.0.25',

            'risk_score' => 15,

            'status' => 'allow',

            'fraud_type' => 'None',

            'fraud_details' => '',

            'order_value' => 150.00,

            'country' => 'GB',

            'customer_type' => 'vip'

        ]

    ];

}