<?php
// painel_activation.php (na raiz)

// 1. Conecta e cria a tabela se necessário
$db = new PDO('sqlite:api/max.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Cria a tabela se não existir
$db->exec("
    CREATE TABLE IF NOT EXISTS activations (
        code TEXT PRIMARY KEY,
        user TEXT,
        status TEXT,
        expiration_date TEXT,
        id_dispositivo TEXT
    )
");

// 2. Se vier POST sem ação, insere ou atualiza código
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST['action'])) {
    $code = trim($_POST['code'] ?? '');
    $user = trim($_POST['user'] ?? '');
    $expiration_date = trim($_POST['expiration_date'] ?? '');
    $id_dispositivo = trim($_POST['id_dispositivo'] ?? '');

    if ($code !== '' && $user !== '' && $expiration_date !== '') {
        $stmt = $db->prepare("
            INSERT INTO activations (code, user, status, expiration_date, id_dispositivo) 
            VALUES (:code, :user, 'active', :expiration_date, :id_dispositivo)
            ON CONFLICT(code) DO UPDATE SET
                user = excluded.user,
                status = 'active',
                expiration_date = excluded.expiration_date,
                id_dispositivo = excluded.id_dispositivo
        ");
        $stmt->execute([
            ':code' => $code,
            ':user' => $user,
            ':expiration_date' => $expiration_date,
            ':id_dispositivo' => $id_dispositivo
        ]);
        $message = "Código $code ativado para $user com validade até $expiration_date.";
    } else {
        $error = "Preencha todos os campos obrigatórios.";
    }
}

// 3. Se vier POST para ação (delete, activate, block)
if (isset($_POST['action'])) {
    $code = $_POST['code'] ?? '';
    $action = $_POST['action'] ?? '';

    if ($code !== '') {
        if ($action === 'block') {
            $status = 'blocked';
        } elseif ($action === 'activate') {
            $status = 'active';
        } elseif ($action === 'delete') {
            $stmt = $db->prepare("DELETE FROM activations WHERE code = :code");
            $stmt->execute([':code' => $code]);
            $message = "Código $code deletado com sucesso!";
        }

        if ($action !== 'delete') {
            $stmt = $db->prepare("
                UPDATE activations
                SET status = :status
                WHERE code = :code
            ");
            $stmt->execute([
                ':status' => $status,
                ':code' => $code
            ]);
            $message = "Status do código $code alterado para $status.";
        }
    }
}

// 4. Lê os registros
$rows = $db->query("SELECT * 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>Painel de Ativações</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body { font-family: Arial, sans-serif; padding: 5px; background-color: #f8f9fa; }
        form { margin-bottom: 5px; background-color: #fff; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }
        input { padding: 6px; margin-right: 8px; width: 250px; }
        input[type="date"] { width: 170px; }
        button { padding: 6px 12px; background-color: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #0056b3; }
        .message { color: green; margin-top: 10px; }
        .error { color: red; margin-top: 10px; }
        table { border-collapse: collapse; width: 100%; margin-top: 10px; }
        th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
        th { background-color: #f1f1f1; }
        .button-group button {
            margin-right: 5px;
            padding: 5px 5px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .button-group button.delete {
            background-color: #dc3545;
        }
        .button-group button:hover {
            background-color: #218838;
        }
        .button-group button.delete:hover {
            background-color: #c82333;
        }
    </style>
</head>
<body>

<h1>Painel de Ativações</h1>

<?php if (!empty($message)): ?>
    <div class="message"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<?php if (!empty($error)): ?>
    <div class="error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<form method="POST">
    <input type="text" name="code" placeholder="Código do dispositivo" required />
    <input type="text" name="user" placeholder="Nome do usuário" required />
    <input type="date" name="expiration_date" required />
    <input type="text" name="id_dispositivo" placeholder="ID do dispositivo (opcional)" />
    <button type="submit">Ativar</button>
</form>

<h2>Dispositivos Ativados</h2>
<table>
    <tr>
        <th>Código</th>
        <th>Usuário</th>
        <th>ID Dispositivo</th>
        <th>Status</th>
        <th>Validade</th>
        <th>Ações</th>
    </tr>
    <?php foreach ($rows as $r): ?>
    <tr>
        <td><?= htmlspecialchars($r['code'], ENT_QUOTES) ?></td>
        <td><?= htmlspecialchars($r['user'], ENT_QUOTES) ?></td>
        <td><?= htmlspecialchars($r['id_dispositivo'] ?? '---', ENT_QUOTES) ?></td>
        <td><?= htmlspecialchars($r['status'], ENT_QUOTES) ?></td>
        <td><?= htmlspecialchars($r['expiration_date'] ?? '---', ENT_QUOTES) ?></td>
        <td class="button-group">
            <form method="POST" style="display:inline;">
                <input type="hidden" name="code" value="<?= htmlspecialchars($r['code'], ENT_QUOTES) ?>">
                <input type="hidden" name="action" value="delete">
                <button type="submit" class="delete"><i class="fas fa-trash"></i> Deletar</button>
            </form>
        </td>
    </tr>
    <?php endforeach; ?>
</table>

</body>
</html>

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