<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

date_default_timezone_set('America/Sao_Paulo');

if (empty($_SESSION["panel_user"]) || empty($_SESSION["tipo_user"])) {
    header("Location: index.php");
    exit;
}

$dbPath = dirname(__DIR__) . "/api/db.db";
if (!is_file($dbPath)) {
    session_destroy();
    header("Location: index.php");
    exit;
}

try {
    $db = new PDO("sqlite:" . $dbPath, null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
} catch (Throwable $e) {
    session_destroy();
    header("Location: index.php");
    exit;
}

$username = trim((string)$_SESSION["panel_user"]);
$tipo = trim((string)$_SESSION["tipo_user"]);

if ($username === "" || strlen($username) > 80) {
    session_destroy();
    header("Location: index.php");
    exit;
}

$user = null;

$vencimento = null;
$creditos = null;

if ($tipo === "admin") {
    $stmt = $db->prepare("SELECT id, username FROM panel_users WHERE username=? LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user) {
        session_destroy();
        header("Location: index.php");
        exit;
    }

    $_SESSION["panel_id"] = (int)$user["id"];

} elseif ($tipo === "revendedor") {
    $stmt = $db->prepare("SELECT id, username, status, vencimento, creditos FROM revendedores WHERE username=? LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user) {
        session_destroy();
        header("Location: index.php");
        exit;
    }

    $status = trim((string)($user["status"] ?? ""));
    if ($status !== "" && $status !== "ativo") {
        session_destroy();
        header("Location: index.php");
        exit;
    }

    $_SESSION["revendedor_id"] = (int)$user["id"];

    $vencimento = $user["vencimento"] ?? null;
    $creditos = $user["creditos"] ?? null;

} else {
    session_destroy();
    header("Location: index.php");
    exit;
}

/* ===== Variáveis prontas pro header ===== */
$name_header = (string)($user["username"] ?? "");
$nivel_admin = ($tipo === "admin") ? 1 : 0;
$nivel_header = $nivel_admin;

/* ===== Flags prontas ===== */
$isAdmin = ($tipo === "admin");
$isRev = ($tipo === "revendedor");
?>
