<?php
function isAuthenticated(): bool {
    return isset($_SESSION["user"]) && is_array($_SESSION["user"]);
}

function currentUser(): ?array {
    return isAuthenticated() ? $_SESSION["user"] : null;
}

function getAuthUser(): array {
    return currentUser() ?? [];
}

function requireApiAuth(): void {
    if (!isAuthenticated()) {
        http_response_code(401);
        header("Content-Type: application/json; charset=utf-8");
        echo json_encode(["success" => false, "error" => "unauthorized"]);
        exit;
    }
}

function requirePageAuth(string $redirect = "index.php"): void {
    if (!isAuthenticated()) {
        header("Location: " . $redirect);
        exit;
    }

    if (!isset($GLOBALS["pdo"]) || !($GLOBALS["pdo"] instanceof PDO)) {
        return;
    }

    $path = basename(parse_url($_SERVER["REQUEST_URI"] ?? "", PHP_URL_PATH) ?: "");
    $skip = ["logout.php"];

    if (in_array($path, $skip, true)) {
        return;
    }

    require_once __DIR__ . "/subscription_guard.php";
    $user = getAuthUser();
    $target = enforceCompanyAccessOrRedirect($GLOBALS["pdo"], $user);

    if ($target !== null && $target !== $path) {
        header("Location: " . $target);
        exit;
    }
}

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

function checkAuth(){
    requireApiAuth();
}
