<?php
// Conecta ao banco no caminho correto
$dbPath = __DIR__ . '/api/max.db';
$db = new PDO('sqlite:' . $dbPath);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Atualiza dados se enviado
$successMessage = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['code'])) {
    $stmt = $db->prepare("UPDATE activations SET status = :status, expiration_date = :expiration_date, id_dispositivo = :id_dispositivo WHERE code = :code");
    $stmt->execute([
        ':status' => $_POST['status'],
        ':expiration_date' => $_POST['expiration_date'],
        ':id_dispositivo' => $_POST['id_dispositivo'],
        ':code' => $_POST['code']
    ]);
    $successMessage = "Atualizado com sucesso!";
}

// Busca todos os registros (agora incluindo id_dispositivo)
$rows = $db->query("SELECT code, user, status, expiration_date, id_dispositivo FROM activations ORDER BY code")->fetchAll(PDO::FETCH_ASSOC);
?>
<?php include './includes/header.php'; ?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Gerenciar Ativações</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { 
            font-family: Arial, sans-serif; 
            padding: 20px; 
            background: #f5f5f5; 
            margin: 0; 
            color: #333;
        }
        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        .cards-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            justify-content: center;
        }
        .card {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            width: 320px; /* Aumentei um pouco para caber o novo campo */
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .card input[type="text"], .card select {
            width: 100%; 
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .card input[type="submit"] { 
            padding: 8px 16px; 
            background-color: #28a745; 
            color: white; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer; 
            margin-top: 10px;
        }
        .card input[type="submit"]:hover { 
            background-color: #218838; 
        }
        .card h3 {
            font-size: 18px;
            margin-bottom: 10px;
            color: #333;
        }
        .card p {
            font-size: 14px;
            color: #666;
            margin: 5px 0;
        }
        .success-message {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background-color: #28a745;
            color: white;
            border-radius: 5px;
            display: none;
            font-size: 16px;
        }
        @media (max-width: 768px) {
            .card {
                width: 100%;
                margin-bottom: 20px;
            }
        }
    </style>
    <script>
        function showSuccessMessage() {
            var message = document.getElementById('successMessage');
            message.style.display = 'block';
            setTimeout(function() {
                message.style.display = 'none';
            }, 3000);
        }
    </script>
</head>
<body>
    <h2>Gerenciar Códigos de Ativação</h2>

    <?php if ($successMessage): ?>
    <div id="successMessage" class="success-message">
        <?= htmlspecialchars($successMessage) ?>
    </div>
    <script>
        window.onload = showSuccessMessage;
    </script>
    <?php endif; ?>

    <div class="cards-container">
        <?php foreach ($rows as $row): ?>
        <div class="card">
            <h3>Código: <?= htmlspecialchars($row['code']) ?></h3>
            <p><strong>Usuário:</strong> <?= htmlspecialchars($row['user']) ?></p>
            <p><strong>ID Dispositivo:</strong> <?= htmlspecialchars($row['id_dispositivo'] ?? 'Não informado') ?></p>
            
            <form method="post">
                <input type="hidden" name="code" value="<?= htmlspecialchars($row['code']) ?>">
                
                <label>Status:</label>
                <select name="status">
                    <option value="pending" <?= $row['status'] === 'pending' ? 'selected' : '' ?>>Pendente</option>
                    <option value="active" <?= $row['status'] === 'active' ? 'selected' : '' ?>>Ativo</option>
                    <option value="blocked" <?= $row['status'] === 'blocked' ? 'selected' : '' ?>>Bloqueado</option>
                </select>
                
                <label>Data de Expiração:</label>
                <input type="text" name="expiration_date" value="<?= htmlspecialchars($row['expiration_date']) ?>" placeholder="AAAA-MM-DD">
                
                <label>ID do Dispositivo:</label>
                <input type="text" name="id_dispositivo" value="<?= htmlspecialchars($row['id_dispositivo'] ?? '') ?>" placeholder="ID do dispositivo">
                
                <input type="submit" value="Salvar">
            </form>
        </div>
        <?php endforeach; ?>
    </div>
</body>
</html>
<?php include './includes/footer.php'; ?>