<?php
require_once __DIR__ . '/../config.php';

// ── Sessão segura ────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params([
        'lifetime' => 7200,          // expira em 2h de inatividade
        'path'     => '/',
        'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,          // inacessível via JS
        'samesite' => 'Lax',         // compatível com redirect HTTP→HTTPS
    ]);
    session_start();
}

// Timeout de sessão: 2 horas sem atividade → logout
if (isset($_SESSION['admin_last_activity']) && (time() - $_SESSION['admin_last_activity']) > 7200) {
    session_unset();
    session_destroy();
    header('Location: login.php?reason=timeout');
    exit;
}
$_SESSION['admin_last_activity'] = time();

if (empty($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
            DB_USER, DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
    }
    return $pdo;
}

// ── CSRF ────────────────────────────────────────────────────
function csrf_token(): string {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function csrf_field(): string {
    return '<input type="hidden" name="csrf_token" value="' . csrf_token() . '">';
}

function csrf_verify(): void {
    $token = $_POST['csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    if (!hash_equals(csrf_token(), $token)) {
        http_response_code(403);
        die('<p style="font-family:sans-serif;padding:2rem;color:#dc2626">Requisição inválida (token CSRF). Volte e tente novamente.</p>');
    }
}

function generate_key(): string {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $key = '';
    for ($g = 0; $g < 4; $g++) {
        if ($g > 0) $key .= '-';
        for ($i = 0; $i < 5; $i++) $key .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $key;
}

function generate_api_secret(): string {
    return bin2hex(random_bytes(32));
}

function generate_install_token(): string {
    return bin2hex(random_bytes(32));
}

function license_badge(array $lic): string {
    if (!$lic['active']) return '<span class="badge badge-revoked">Revogada</span>';
    $exp   = new DateTime($lic['expires_at']);
    $today = new DateTime('today');
    $grace = (clone $exp)->modify('+' . GRACE_DAYS . ' days');
    if ($today > $grace)  return '<span class="badge badge-expired">Bloqueada</span>';
    if ($today > $exp)    return '<span class="badge badge-grace">Carência</span>';
    $diff = (int)$today->diff($exp)->days;
    if ($diff <= 5)       return '<span class="badge badge-grace">Vence em ' . $diff . 'd</span>';
    return '<span class="badge badge-ok">Ativa</span>';
}

function h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

$admin_name = $_SESSION['admin_name'] ?? 'Admin';
