<?php
// Ajusta la ruta de tu base de datos
$dbFile = __DIR__ . '/api/.db.db';

// Procesar acciones (kill, kill_by_code, etc.)
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    $connection_id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $code = isset($_POST['code']) ? trim($_POST['code']) : '';
    
    try {
        $pdo = new PDO('sqlite:' . $dbFile);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        if ($action === 'kill' && $connection_id > 0) {
            $stmt = $pdo->prepare("DELETE FROM code_connections WHERE id = :id");
            $stmt->execute([':id' => $connection_id]);
            $message = "Conexión eliminada correctamente";
            $messageType = "success";
        }
        elseif ($action === 'kill_by_code' && !empty($code)) {
            $stmt = $pdo->prepare("DELETE FROM code_connections WHERE code = :code");
            $stmt->execute([':code' => $code]);
            $message = "Todas las conexiones del código $code fueron eliminadas";
            $messageType = "success";
        }
        elseif ($action === 'reset_all') {
            $stmt = $pdo->query("DELETE FROM code_connections");
            $message = "Todas las conexiones fueron eliminadas";
            $messageType = "success";
        }
        elseif ($action === 'toggle_active' && $connection_id > 0) {
            // Cambiar entre activo/inactivo
            $stmt = $pdo->prepare("SELECT is_active FROM code_connections WHERE id = :id");
            $stmt->execute([':id' => $connection_id]);
            $current = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($current) {
                $newStatus = $current['is_active'] == 1 ? 0 : 1;
                $stmt = $pdo->prepare("UPDATE code_connections SET is_active = :status, last_activity = CURRENT_TIMESTAMP WHERE id = :id");
                $stmt->execute([':status' => $newStatus, ':id' => $connection_id]);
                $message = $newStatus == 1 ? "Conexión reactivada" : "Conexión desactivada";
                $messageType = "success";
            }
        }
    } catch (Throwable $e) {
        $message = "Error: " . $e->getMessage();
        $messageType = "error";
    }
}

// Obtener todas las conexiones
try {
    $pdo = new PDO('sqlite:' . $dbFile);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $stmt = $pdo->query("
        SELECT 
            cc.id,
            cc.code,
            substr(cc.device_id, 1, 20) || '...' as device_id_short,
            cc.device_id as device_id_full,
            cc.ip_address,
            cc.connected_at,
            cc.last_activity,
            cc.is_active,
            c.expires_at,
            (SELECT COUNT(*) FROM code_connections WHERE code = cc.code AND is_active = 1) as active_count
        FROM code_connections cc
        LEFT JOIN codes c ON cc.code = c.code
        ORDER BY cc.code, cc.is_active DESC, cc.last_activity DESC
    ");
    $connections = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Estadísticas por código
    $stmtStats = $pdo->query("
        SELECT 
            code,
            COUNT(*) as total,
            SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active
        FROM code_connections
        GROUP BY code
        ORDER BY code
    ");
    $stats = $stmtStats->fetchAll(PDO::FETCH_ASSOC);
    
    $totalConnections = count($connections);
    
} catch (Throwable $e) {
    $connections = [];
    $stats = [];
    $totalConnections = 0;
    $message = "Error al leer la base de datos: " . $e->getMessage();
    $messageType = "error";
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Conexiones por Código</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #1a1a2e;
            color: #eee;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        h1 {
            color: #ff0000;
            margin-bottom: 10px;
        }
        
        .subtitle {
            color: #888;
            margin-bottom: 30px;
        }
        
        .stats-bar {
            background: #16213e;
            border-radius: 10px;
            padding: 15px 20px;
            margin-bottom: 20px;
            display: flex;
            gap: 30px;
            flex-wrap: wrap;
        }
        
        .stat-card {
            background: #0f3460;
            padding: 10px 20px;
            border-radius: 8px;
        }
        
        .stat-card .number {
            font-size: 28px;
            font-weight: bold;
            color: #ff0000;
        }
        
        .stat-card .label {
            font-size: 12px;
            color: #aaa;
        }
        
        .message {
            background: #0f3460;
            padding: 12px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #ff0000;
        }
        
        .message.success {
            background: #0a2e1f;
            border-left-color: #00ff00;
        }
        
        .message.error {
            background: #3e1a1a;
            border-left-color: #ff0000;
        }
        
        .code-stats {
            background: #0f3460;
            border-radius: 10px;
            padding: 15px 20px;
            margin-bottom: 20px;
        }
        
        .code-stats h3 {
            margin-bottom: 15px;
            color: #ff0000;
        }
        
        .code-badge {
            display: inline-block;
            background: #1a1a2e;
            padding: 8px 15px;
            border-radius: 20px;
            margin: 5px;
        }
        
        .code-badge .code {
            font-weight: bold;
            font-family: monospace;
            font-size: 16px;
        }
        
        .code-badge .count {
            color: #00ff00;
            margin-left: 8px;
        }
        
        .code-badge .max {
            color: #ffaa00;
            font-size: 12px;
        }
        
        .reset-btn {
            background: #ff0000;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 10px;
        }
        
        .reset-btn:hover {
            background: #cc0000;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            background: #16213e;
            border-radius: 10px;
            overflow: hidden;
        }
        
        th {
            background: #0f3460;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #ff0000;
        }
        
        td {
            padding: 10px 12px;
            border-bottom: 1px solid #0f3460;
        }
        
        tr:hover {
            background: #1a2a4a;
        }
        
        .active-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .active-yes {
            background: #0a5a2e;
            color: #00ff00;
        }
        
        .active-no {
            background: #5a1a1a;
            color: #ff6666;
        }
        
        .btn-kill {
            background: #ff0000;
            color: white;
            border: none;
            padding: 5px 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .btn-kill:hover {
            background: #cc0000;
        }
        
        .btn-toggle {
            background: #ffaa00;
            color: #1a1a2e;
            border: none;
            padding: 5px 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 5px;
        }
        
        .btn-toggle:hover {
            background: #ffcc44;
        }
        
        .btn-code {
            background: #ffaa00;
            color: #1a1a2e;
            border: none;
            padding: 4px 10px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 11px;
            margin-left: 8px;
        }
        
        .device-id {
            font-family: monospace;
            font-size: 12px;
            max-width: 200px;
            word-break: break-all;
        }
        
        .footer {
            margin-top: 30px;
            text-align: center;
            color: #666;
            font-size: 12px;
        }
        
        @media (max-width: 768px) {
            th, td {
                font-size: 12px;
                padding: 6px 8px;
            }
            .device-id {
                max-width: 100px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <h1>🔗 Administrador de Conexiones</h1>
    <div class="subtitle">Control de dispositivos conectados por código</div>
    
    <div class="stats-bar">
        <div class="stat-card">
            <div class="number"><?php echo $totalConnections; ?></div>
            <div class="label">Total Conexiones</div>
        </div>
        <div class="stat-card">
            <div class="number"><?php 
                $activeCount = 0;
                foreach ($connections as $conn) {
                    if ($conn['is_active'] == 1) $activeCount++;
                }
                echo $activeCount;
            ?></div>
            <div class="label">Activas</div>
        </div>
        <div class="stat-card">
            <div class="number"><?php echo count($stats); ?></div>
            <div class="label">Códigos con conexiones</div>
        </div>
        <div style="flex:1"></div>
        <form method="POST" style="display: inline;" onsubmit="return confirm('¿Eliminar TODAS las conexiones? Esta acción no se puede deshacer.')">
            <input type="hidden" name="action" value="reset_all">
            <button type="submit" class="reset-btn">🗑️ RESET TOTAL</button>
        </form>
    </div>
    
    <?php if ($message): ?>
    <div class="message <?php echo $messageType; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>
    
    <div class="code-stats">
        <h3>📊 Resumen por código</h3>
        <?php foreach ($stats as $stat): ?>
        <div class="code-badge">
            <span class="code">📱 Código: <?php echo htmlspecialchars($stat['code']); ?></span>
            <span class="count"><?php echo $stat['active']; ?>/<?php echo $stat['total']; ?> activas</span>
            <span class="max">(máx 5)</span>
            <form method="POST" style="display: inline;" onsubmit="return confirm('¿Eliminar TODAS las conexiones del código <?php echo htmlspecialchars($stat['code']); ?>?')">
                <input type="hidden" name="action" value="kill_by_code">
                <input type="hidden" name="code" value="<?php echo htmlspecialchars($stat['code']); ?>">
                <button type="submit" class="btn-code">🗑️ Eliminar todas</button>
            </form>
        </div>
        <?php endforeach; ?>
        <?php if (empty($stats)): ?>
        <div style="color: #888;">No hay conexiones registradas</div>
        <?php endif; ?>
    </div>
    
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Código</th>
                <th>Device ID</th>
                <th>IP</th>
                <th>Conectado</th>
                <th>Última actividad</th>
                <th>Estado</th>
                <th>Expira</th>
                <th>Acciones</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($connections)): ?>
            <tr>
                <td colspan="9" style="text-align: center; padding: 40px;">
                    No hay conexiones registradas
                </td>
            </tr>
            <?php else: ?>
                <?php foreach ($connections as $conn): ?>
                <tr>
                    <td><?php echo $conn['id']; ?></td>
                    <td>
                        <strong><?php echo htmlspecialchars($conn['code']); ?></strong>
                        <br>
                        <small style="color:#aaa;"><?php echo $conn['active_count']; ?>/5 activos</small>
                    </td>
                    <td class="device-id" title="<?php echo htmlspecialchars($conn['device_id_full']); ?>">
                        <?php echo htmlspecialchars($conn['device_id_short']); ?>
                    </td>
                    <td><?php echo htmlspecialchars($conn['ip_address'] ?: '-'); ?></td>
                    <td><small><?php echo htmlspecialchars($conn['connected_at']); ?></small></td>
                    <td><small><?php echo htmlspecialchars($conn['last_activity']); ?></small></td>
                    <td>
                        <?php if ($conn['is_active'] == 1): ?>
                            <span class="active-badge active-yes">✅ Activo</span>
                        <?php else: ?>
                            <span class="active-badge active-no">❌ Inactivo</span>
                        <?php endif; ?>
                    </td>
                    <td><small><?php echo htmlspecialchars($conn['expires_at'] ?: '-'); ?></small></td>
                    <td>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="toggle_active">
                            <input type="hidden" name="id" value="<?php echo $conn['id']; ?>">
                            <button type="submit" class="btn-toggle">
                                <?php echo $conn['is_active'] == 1 ? '🔌 Desactivar' : '▶️ Activar'; ?>
                            </button>
                        </form>
                        <form method="POST" style="display: inline;" onsubmit="return confirm('¿Eliminar esta conexión?')">
                            <input type="hidden" name="action" value="kill">
                            <input type="hidden" name="id" value="<?php echo $conn['id']; ?>">
                            <button type="submit" class="btn-kill">🗑️ Matar</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
    
    <div class="footer">
        <strong>Límite actual:</strong> 5 dispositivos por código | 
        <strong>Conexiones inactivas:</strong> No se limpian automáticamente
    </div>
</div>
</body>
</html>