<?php
declare(strict_types=1);

require_once __DIR__ . '/database.php';

function gpc_session_start(): void
{
    if (session_status() === PHP_SESSION_NONE) {
        session_name(GPC_SESSION);
        session_start([
            'cookie_httponly' => true,
            'cookie_secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
            'cookie_samesite' => 'Lax',
        ]);
    }
}

function gpc_logged_in(): bool
{
    gpc_session_start();
    return !empty($_SESSION['admin_id']);
}

function gpc_require_login(): void
{
    if (!gpc_logged_in()) {
        header('Location: index.php');
        exit;
    }
    if (!empty($_SESSION['admin_last_activity']) && time() - (int)$_SESSION['admin_last_activity'] > 3600) {
        gpc_logout();
        header('Location: index.php');
        exit;
    }
    $_SESSION['admin_last_activity'] = time();
}

function gpc_login(string $user, string $pass): bool
{
    $stmt = gpc_db()->prepare('SELECT id, password FROM admins WHERE username = :u LIMIT 1');
    $stmt->execute([':u' => $user]);
    $row = $stmt->fetch();
    if (!$row || !password_verify($pass, $row['password'])) {
        return false;
    }
    gpc_session_start();
    session_regenerate_id(true);
    $_SESSION['admin_id'] = (int) $row['id'];
    $_SESSION['admin_user'] = $user;
    $_SESSION['admin_last_activity'] = time();
    return true;
}

function gpc_logout(): void
{
    gpc_session_start();
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
    }
    session_destroy();
}

function gpc_csrf_token(): string
{
    gpc_session_start();
    if (empty($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf'];
}

function gpc_csrf_check(?string $token): bool
{
    gpc_session_start();
    return is_string($token) && isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $token);
}

function gpc_admin_user(): string
{
    gpc_session_start();
    return (string) ($_SESSION['admin_user'] ?? 'admin');
}

function gpc_public_url(string $path = ''): string
{
    $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $dir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
    if (preg_match('#/api$#', $dir)) {
        $dir = dirname($dir);
    }
    $base = rtrim($dir, '/');
    $url = $proto . '://' . $host . $base;
    if ($path !== '') {
        $url .= '/' . ltrim(str_replace('\\', '/', $path), '/');
    }
    return $url;
}

function gpc_flash(string $type, string $msg): void
{
    gpc_session_start();
    $_SESSION['flash'] = ['type' => $type, 'msg' => $msg];
}

function gpc_take_flash(): ?array
{
    gpc_session_start();
    if (empty($_SESSION['flash'])) {
        return null;
    }
    $f = $_SESSION['flash'];
    unset($_SESSION['flash']);
    return $f;
}

function gpc_h(?string $s): string
{
    return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
}

function gpc_format_mac(string $mac): string
{
    $raw = strtoupper(preg_replace('/[^A-F0-9]/', '', $mac));
    if (strlen($raw) !== 12) {
        return strtoupper(trim($mac));
    }
    return implode(':', str_split($raw, 2));
}

function gpc_page_title(string $title): string
{
    return gpc_h(gpc_setting('panel_name', 'GPC Panel')) . ' — ' . gpc_h($title);
}
