<?php
if (!defined('ABSPATH')) exit;

$nonce = wp_create_nonce('auctionforge_admin');
?>
<div class="wrap">
    <h1>AuctionForge User Tracking</h1>
    <p class="description">Search by IP address, name, email, device ID, or fingerprint. Rows highlighted in <span style="color:#d63638;font-weight:600;">red</span> share a device or fingerprint with another email — potential duplicate accounts.</p>

    <div style="margin: 20px 0; display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
        <input type="text" id="af-ip-search" placeholder="Search by IP, name, email, device ID..." style="width: 400px; padding: 6px 10px; font-size: 14px;" />
        <button id="af-ip-search-btn" class="button button-primary">Search</button>
        <button id="af-ip-export-btn" class="button">Export CSV</button>
        <span id="af-ip-status" style="margin-left: 10px; color: #666;"></span>
    </div>

    <div id="af-ip-results">
        <table class="wp-list-table widefat striped" id="af-ip-table" style="table-layout:auto;">
            <thead>
                <tr>
                    <th style="width:180px;">Email</th>
                    <th style="width:100px;">First Name</th>
                    <th style="width:100px;">Last Name</th>
                    <th style="width:130px;">IP Address</th>
                    <th>Device ID</th>
                    <th>Fingerprint</th>
                    <th style="width:60px;">Count</th>
                    <th style="width:70px;">Last Event</th>
                    <th style="width:130px;">First Seen</th>
                    <th style="width:130px;">Last Seen</th>
                    <th style="width:50px;">Links</th>
                </tr>
            </thead>
            <tbody id="af-ip-tbody">
                <tr><td colspan="11" style="text-align:center; padding: 20px; color: #666;">Click Search to view all entries, or enter a search term.</td></tr>
            </tbody>
        </table>
    </div>

    <div id="af-ip-pagination" style="margin-top: 15px; display: flex; gap: 10px; align-items: center;">
        <button id="af-ip-prev" class="button" disabled>&laquo; Previous</button>
        <span id="af-ip-page-info" style="color: #666;"></span>
        <button id="af-ip-next" class="button" disabled>Next &raquo;</button>
    </div>

    <!-- Linked accounts modal -->
    <div id="af-linked-modal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.5); z-index:100000;">
        <div style="background:#fff; max-width:800px; margin:80px auto; padding:20px 30px; border-radius:6px; max-height:70vh; overflow-y:auto; box-shadow:0 4px 20px rgba(0,0,0,0.3);">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px;">
                <h2 id="af-linked-title" style="margin:0;">Linked Accounts</h2>
                <button id="af-linked-close" class="button">&times; Close</button>
            </div>
            <table class="wp-list-table widefat striped">
                <thead>
                    <tr>
                        <th>Email</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>IP Address</th>
                        <th>Device ID</th>
                        <th>Fingerprint</th>
                        <th>First Seen</th>
                        <th>Last Seen</th>
                        <th>Count</th>
                    </tr>
                </thead>
                <tbody id="af-linked-tbody"></tbody>
            </table>
        </div>
    </div>
</div>

    <!-- Advanced Metrics modal -->
    <div id="af-metrics-modal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.5); z-index:100000;">
        <div style="background:#fff; max-width:600px; margin:80px auto; padding:20px 30px; border-radius:6px; max-height:70vh; overflow-y:auto; box-shadow:0 4px 20px rgba(0,0,0,0.3);">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; border-bottom: 1px solid #ddd; padding-bottom: 10px;">
                <h2 style="margin:0;">Device Fingerprint Forensics</h2>
                <button id="af-metrics-close" class="button">&times; Close</button>
            </div>
            <ul id="af-metrics-list" style="list-style-type: disc; padding-left: 20px; font-family: monospace; font-size: 13px; color: #2c3338; line-height: 1.8;">
            </ul>
        </div>
    </div>
<style>
    #af-ip-table .event-register { color: #2271b1; font-weight: 600; }
    #af-ip-table .event-login { color: #00a32a; font-weight: 600; }
    #af-ip-table td { vertical-align: middle; font-size: 12.5px; }
    #af-ip-table .flagged { background: #fce4e4 !important; }
    #af-ip-table .flag-badge { background: #d63638; color: #fff; padding: 2px 6px; border-radius: 3px; font-size: 11px; font-weight: 600; cursor: pointer; }
    #af-ip-table .lookup-link { color: #2271b1; cursor: pointer; text-decoration: underline; font-size: 11px; }
    #af-ip-table .device-short { font-family: monospace; font-size: 11px; color: #666; word-break: break-all; }
    #af-ip-search:focus { border-color: #2271b1; box-shadow: 0 0 0 1px #2271b1; outline: none; }
</style>

<script>
(function($) {
    var currentPage = 1;
    var perPage = 50;
    var nonce = '<?php echo esc_js($nonce); ?>';

    function doSearch(page) {
        currentPage = page || 1;
        var search = $('#af-ip-search').val();

        $('#af-ip-status').text('Searching...');
        $('#af-ip-search-btn').prop('disabled', true);

        $.post(ajaxurl, {
            action: 'auctionforge_search_ip_logs',
            nonce: nonce,
            search: search,
            page: currentPage,
            per_page: perPage
        }, function(response) {
            $('#af-ip-search-btn').prop('disabled', false);

            if (!response.success) {
                $('#af-ip-status').text('Error: ' + (response.data || 'Unknown error'));
                return;
            }

            var data = response.data;
            var flagged = data.flagged || {};
            var tbody = $('#af-ip-tbody');
            tbody.empty();

            if (data.results.length === 0) {
                tbody.append('<tr><td colspan="11" style="text-align:center; padding: 20px; color: #666;">No results found.</td></tr>');
                $('#af-ip-status').text('0 results');
            } else {
                $.each(data.results, function(i, row) {
                    var isFlagged = flagged[row.id] !== undefined;
                    var rowClass = isFlagged ? 'flagged' : '';
                    var eventClass = 'event-' + row.last_event_type;
                    var eventLabel = row.last_event_type === 'register' ? 'Register' : 'Login';
                    var devShort = row.device_id || '-';
                    var fpShort = row.device_fingerprint || '-';

                    var flagHtml = '';
                    if (isFlagged) {
                        var f = flagged[row.id];
                        var parts = [];
                        if (f.shared_device) parts.push(f.shared_device + ' accounts share device');
                        if (f.shared_fingerprint) parts.push(f.shared_fingerprint + ' accounts share fingerprint');
                        flagHtml = '<span class="flag-badge" title="' + escHtml(parts.join(', ')) + '">&#9888;</span> ';
                    }

                    var linksHtml = '';
                    if (row.device_id) linksHtml += '<span class="lookup-link" data-type="device_id" data-value="' + escHtml(row.device_id) + '">Dev</span> ';
                    if (row.device_fingerprint) linksHtml += '<span class="lookup-link" data-type="device_fingerprint" data-value="' + escHtml(row.device_fingerprint) + '">FP</span> ';
                    linksHtml += '<span class="lookup-link" data-type="ip_address" data-value="' + escHtml(row.ip_address) + '">IP</span>';
                    
                    var metricsHtml = '';
                    var mparts = [];
                    if (row.gpu_vendor) mparts.push('GPU Vendor: ' + row.gpu_vendor);
                    if (row.gpu_renderer) mparts.push('GPU Renderer: ' + row.gpu_renderer);
                    if (row.canvas_hash) mparts.push('Canvas: ' + row.canvas_hash);
                    if (row.audio_hash) mparts.push('Audio: ' + row.audio_hash);
                    if (row.screen_res) mparts.push('Screen: ' + row.screen_res);
                    if (row.hardware_cores) mparts.push('CPU Cores: ' + row.hardware_cores);
                    if (row.math_hash) mparts.push('Math FP: ' + row.math_hash);
                    if (row.webrtc_ips) mparts.push('WebRTC IPs: ' + row.webrtc_ips);
                    if (row.media_devices) mparts.push('Media Devices: ' + row.media_devices);
                    if (row.voices_hash) mparts.push('Voices: ' + row.voices_hash);
                    if (row.battery_info) mparts.push('Battery: ' + row.battery_info);
                    if (row.connection_type) mparts.push('Connection: ' + row.connection_type);
                    if (row.color_profile) mparts.push('Color: ' + row.color_profile);
                    if (row.accessibility) mparts.push('Accessibility: ' + row.accessibility);
                    if (row.form_fill_ms && parseInt(row.form_fill_ms) > 0) mparts.push('Form Fill: ' + row.form_fill_ms + 'ms');
                    if (mparts.length > 0) {
                        var botWarning = '';
                        if (row.form_fill_ms && parseInt(row.form_fill_ms) > 0 && parseInt(row.form_fill_ms) < 500) {
                            botWarning = ' <span style="background:#d63638; color:#fff; padding:1px 4px; border-radius:3px; font-size:9px;">BOT?</span>';
                        }
                        var mpartsHtml = mparts.map(function(p) { return '<li>' + escHtml(p) + '</li>'; }).join('');
                        metricsHtml = '<div style="margin-top:4px; font-size:10px; color:#666; font-weight:normal;"><span class="af-metric-badge" style="background:#f0f0f1; padding:1px 4px; border-radius:3px; cursor:pointer;" data-metrics="' + encodeURIComponent(mpartsHtml) + '">&#128269; ' + mparts.length + ' Identifiers</span>' + botWarning + '</div>';
                    }

                    tbody.append(
                        '<tr class="' + rowClass + '">' +
                        '<td>' + flagHtml + escHtml(row.email) + '</td>' +
                        '<td>' + escHtml(row.first_name) + '</td>' +
                        '<td>' + escHtml(row.last_name) + '</td>' +
                        '<td>' + escHtml(row.ip_address) + '</td>' +
                        '<td class="device-short" title="' + escHtml(row.device_id) + '">' + escHtml(devShort) + '</td>' +
                        '<td class="device-short" title="' + escHtml(row.device_fingerprint) + '">' + escHtml(fpShort) + metricsHtml + '</td>' +
                        '<td>' + row.event_count + '</td>' +
                        '<td><span class="' + eventClass + '">' + eventLabel + '</span></td>' +
                        '<td>' + escHtml(row.first_seen) + '</td>' +
                        '<td>' + escHtml(row.last_seen) + '</td>' +
                        '<td>' + linksHtml + '</td>' +
                        '</tr>'
                    );
                });
                $('#af-ip-status').text(data.total + ' record' + (data.total !== 1 ? 's' : ''));
            }

            $('#af-ip-prev').prop('disabled', currentPage <= 1);
            $('#af-ip-next').prop('disabled', currentPage >= data.pages);
            $('#af-ip-page-info').text(data.pages > 1 ? 'Page ' + currentPage + ' of ' + data.pages : '');
        }).fail(function() {
            $('#af-ip-search-btn').prop('disabled', false);
            $('#af-ip-status').text('Request failed');
        });
    }

    function lookupLinked(type, value) {
        var typeLabels = {device_id: 'Device ID', device_fingerprint: 'Fingerprint', ip_address: 'IP Address'};
        $('#af-linked-title').text('Accounts linked by ' + typeLabels[type] + ': ' + value);
        $('#af-linked-tbody').html('<tr><td colspan="9" style="text-align:center;">Loading...</td></tr>');
        $('#af-linked-modal').show();

        $.post(ajaxurl, {
            action: 'auctionforge_lookup_linked',
            nonce: nonce,
            type: type,
            value: value
        }, function(response) {
            if (!response.success) {
                $('#af-linked-tbody').html('<tr><td colspan="9">Error</td></tr>');
                return;
            }
            var tbody = $('#af-linked-tbody');
            tbody.empty();
            $.each(response.data.results, function(i, row) {
                var devShort = row.device_id || '-';
                var fpShort = row.device_fingerprint || '-';
                tbody.append(
                    '<tr>' +
                    '<td>' + escHtml(row.email) + '</td>' +
                    '<td>' + escHtml(row.first_name) + '</td>' +
                    '<td>' + escHtml(row.last_name) + '</td>' +
                    '<td>' + escHtml(row.ip_address) + '</td>' +
                    '<td style="font-family:monospace;font-size:11px;" title="' + escHtml(row.device_id) + '">' + escHtml(devShort) + '</td>' +
                    '<td style="font-family:monospace;font-size:11px;" title="' + escHtml(row.device_fingerprint) + '">' + escHtml(fpShort) + '</td>' +
                    '<td>' + escHtml(row.first_seen) + '</td>' +
                    '<td>' + escHtml(row.last_seen) + '</td>' +
                    '<td>' + row.event_count + '</td>' +
                    '</tr>'
                );
            });
        });
    }

    function escHtml(str) {
        if (!str) return '';
        return $('<span>').text(str).html();
    }

    $('#af-ip-search-btn').on('click', function() { doSearch(1); });
    $('#af-ip-search').on('keypress', function(e) { if (e.which === 13) doSearch(1); });
    $('#af-ip-prev').on('click', function() { doSearch(currentPage - 1); });
    $('#af-ip-next').on('click', function() { doSearch(currentPage + 1); });

    $(document).on('click', '.lookup-link', function() {
        lookupLinked($(this).data('type'), $(this).data('value'));
    });

    $(document).on('click', '.af-metric-badge', function() {
        var metricsHtml = decodeURIComponent($(this).data('metrics'));
        $('#af-metrics-list').html(metricsHtml);
        $('#af-metrics-modal').show();
    });

    $('#af-metrics-close').on('click', function() { $('#af-metrics-modal').hide(); });
    $('#af-metrics-modal').on('click', function(e) { if (e.target === this) $(this).hide(); });

    $('#af-linked-close').on('click', function() { $('#af-linked-modal').hide(); });
    $('#af-linked-modal').on('click', function(e) { if (e.target === this) $(this).hide(); });

    $('#af-ip-export-btn').on('click', function() {
        var search = encodeURIComponent($('#af-ip-search').val());
        window.location.href = ajaxurl + '?action=auctionforge_export_ip_logs&nonce=' + nonce + '&search=' + search;
    });

    doSearch(1);

})(jQuery);
</script>
