<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    $secureCookie = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https');
    if (!headers_sent()) {
        session_set_cookie_params([
            'lifetime' => 0,
            'path' => '/',
            'secure' => $secureCookie,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
    }
    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,
    ]);
    $db->exec("PRAGMA busy_timeout = 8000");
} catch (Throwable $e) {
    session_destroy();
    header("Location: index.php");
    exit;
}

require_once __DIR__ . "/revenda_schema.php";
revenda_ensure_schema($db);

$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") || revenda_is_expired($user["vencimento"] ?? "")) {
        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");
$revId = $isRev ? (int)($_SESSION["revendedor_id"] ?? ($user["id"] ?? 0)) : 0;

if ($isRev && $revId <= 0) {
    session_destroy();
    header("Location: index.php");
    exit;
}
?>
