<?php
session_start();
ini_set("display_errors", 0);
if (!isset($_SESSION['id'])) { header("Location: login.php"); exit(); }

$id_store = $_SESSION['id'];
$db = new SQLite3("./api/.ansdb.db");
$dbUsers = new SQLite3("./api/.anspanel.db");

if (isset($_GET["activate"])) {
    $activate_id = (int)$_GET["activate"];
    $userRow = $dbUsers->query("SELECT * FROM USERS WHERE id = '$id_store'")->fetchArray(SQLITE3_ASSOC);
    $coluna = isset($userRow['mac_amount']) ? 'mac_amount' : 'credits';
    $saldo = (int)$userRow[$coluna];

    if ($saldo >= 1) {
        $dbUsers->exec("UPDATE USERS SET $coluna = $coluna - 1 WHERE id = '$id_store'");
        $vencimento = date('Y-m-d', strtotime('+1 year'));
        $db->exec("UPDATE ibo SET active = 1, expire_date = '$vencimento' WHERE id = $activate_id AND id_user = '$id_store'");
        header("Location: users_mac.php?status=sucesso");
        exit();
    } else {
        header("Location: users_mac.php?status=sem_saldo");
        exit();
    }
}

if (isset($_GET["delete"])) {
    $del_id = (int)$_GET["delete"];
    $db->exec("DELETE FROM ibo WHERE id = $del_id AND id_user = '$id_store'");
    header("Location: users_mac.php");
    exit();
}

$resUsers = $dbUsers->query("SELECT * FROM USERS WHERE id = '$id_store'")->fetchArray(SQLITE3_ASSOC);
$saldo_exibir = isset($resUsers['mac_amount']) ? $resUsers['mac_amount'] : $resUsers['credits'];

$clientes = $db->query("SELECT * FROM ibo WHERE id_user = '$id_store' ORDER BY id DESC");
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap" rel="stylesheet">
    <style>
        body { background: #0a0a0b; color: #fff; font-family: 'Inter', sans-serif; margin: 0; }
        .header { background: #141417; padding: 20px; text-align: center; }
        .container { padding: 20px; max-width: 500px; margin: 0 auto; }
        .card { background: #1c1c21; border-radius: 15px; padding: 15px; margin-bottom: 15px; }
    </style>
</head>
<body>
    <div class="header">
        <h1>Saldo: <?= $saldo_exibir ?></h1>
    </div>
    <div class="container">
        <a href="users_mac_create.php" style="color:#fff; display:block; text-align:center; margin-bottom:20px;">+ NOVO MAC</a>
        <?php while($row = $clientes->fetchArray(SQLITE3_ASSOC)): ?>
            <div class="card">
                <div>MAC: <?= $row['mac_address'] ?></div>
                <a href="?activate=<?= $row['id'] ?>">Ativar</a> | 
                <a href="?delete=<?= $row['id'] ?>">Excluir</a>
            </div>
        <?php endwhile; ?>
    </div>
</body>
</html>
