<?php
require_once __DIR__ . '/rbac.php';
define('SESSION_TIMEOUT_MINUTES', 30);
define('SESSION_TIMEOUT_SECONDS', SESSION_TIMEOUT_MINUTES * 60);

function initSessionConfig(): void {
    if (session_status() === PHP_SESSION_NONE) {
        ini_set('session.gc_maxlifetime', (string)SESSION_TIMEOUT_SECONDS);
        session_set_cookie_params(SESSION_TIMEOUT_SECONDS, '/', '', false, true);
        session_start();
    }
}

function checkSessionTimeout(): void {
    $lastActivity = $_SESSION['_last_activity'] ?? 0;
    if ($lastActivity > 0 && (time() - $lastActivity) > SESSION_TIMEOUT_SECONDS) {
        $_SESSION = [];
        session_destroy();
        if (session_status() !== PHP_SESSION_NONE) {
            session_start();
        }
        session_regenerate_id(true);
        if (strpos($_SERVER['REQUEST_URI'] ?? '', 'api/') !== false) {
            http_response_code(401);
            echo json_encode(['status' => 'error', 'message' => 'Session expired']);
            exit;
        }
        header("Location: login.php?expired=1");
        exit;
    }
    $_SESSION['_last_activity'] = time();
}

function requireLogin(?PDO $pdo = null): void {
    initSessionConfig();
    if (empty($_SESSION['user_id'])) {
        header("Location: login.php");
        exit;
    }
    checkSessionTimeout();

    // Refresh role_name if missing, and permissions on every pageload
    if ($pdo === null) {
        global $pdo;
    }
    if (isset($pdo) && !empty($_SESSION['role_id'])) {
        if (empty($_SESSION['role_name'])) {
            $stmt = $pdo->prepare("SELECT name FROM roles WHERE id = ?");
            $stmt->execute([(int)$_SESSION['role_id']]);
            $name = $stmt->fetchColumn();
            if ($name) {
                $_SESSION['role_name'] = $name;
            }
        }
        refreshPermissions($pdo, (int)$_SESSION['role_id']);
    }
}

function loginUser(array $user, array $permissions): void {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    session_regenerate_id(true);
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_name'] = $user['name'];
    $_SESSION['role_id'] = $user['role_id'];
    $_SESSION['permissions'] = $permissions;
    $_SESSION['_last_activity'] = time();
}

function logoutUser(): void {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    $_SESSION = [];
    session_destroy();
}
