<?php
/**
 * includes/auth.php — Session management and role-based access control
 */

function start_session(): void {
    if (session_status() === PHP_SESSION_NONE) {
        session_name(SESSION_NAME);

        // Detect HTTPS automatically so the secure flag is correct on live
        // cPanel sites without any manual config change.
        $is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
                 || (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443)
                 || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');

        session_set_cookie_params([
            'lifetime' => 0,           // cookie expires when browser closes
            'path'     => '/',
            'secure'   => $is_https,   // true on HTTPS, false on plain HTTP (local dev)
            'httponly' => true,         // JS cannot read session cookie
            'samesite' => 'Lax',
        ]);
        session_start();
    }
}

function is_logged_in(): bool {
    start_session();
    return !empty($_SESSION['user_id']) && !empty($_SESSION['role']);
}

/**
 * Require the user to be logged in.
 * If not, redirect to login page.
 */
function require_login(): void {
    if (!is_logged_in()) {
        header('Location: ' . base_url('login.php'));
        exit;
    }

    // Idle timeout check
    if (isset($_SESSION['last_activity'])) {
        if ((time() - $_SESSION['last_activity']) > SESSION_LIFETIME) {
            session_unset();
            session_destroy();
            header('Location: ' . base_url('login.php') . '?timeout=1');
            exit;
        }
    }
    $_SESSION['last_activity'] = time();
}

/**
 * Require the user to have a specific role.
 * $roles can be a string or array of strings.
 * If role check fails, redirect to dashboard with error.
 */
function require_role($roles): void {
    require_login();
    $roles = (array) $roles;
    if (!in_array($_SESSION['role'], $roles, true)) {
        set_flash('error', 'You do not have permission to access that page.');
        header('Location: ' . base_url('pages/dashboard.php'));
        exit;
    }
}

function is_super_admin(): bool {
    return is_logged_in() && $_SESSION['role'] === 'super_admin';
}

function current_user_id(): int {
    return (int) ($_SESSION['user_id'] ?? 0);
}

function current_user_role(): string {
    return $_SESSION['role'] ?? '';
}

function current_user_name(): string {
    return $_SESSION['name'] ?? 'User';
}

function current_user_agency_id(): ?int {
    return isset($_SESSION['agency_id']) ? (int) $_SESSION['agency_id'] : null;
}

/**
 * Log a user in. Call after verifying credentials.
 * Creates a new session ID to prevent session fixation.
 */
function login_user(array $user): void {
    start_session();
    session_regenerate_id(true);

    $_SESSION['user_id']    = $user['id'];
    $_SESSION['role']       = $user['role'];
    $_SESSION['name']       = $user['name'];
    $_SESSION['email']      = $user['email'];
    $_SESSION['username']   = $user['username'];
    $_SESSION['agency_id']  = $user['agency_id'];
    $_SESSION['last_activity'] = time();

    // Update last_login in the database
    $stmt = db()->prepare('UPDATE users SET last_login = NOW() WHERE id = ?');
    $stmt->execute([$user['id']]);
}

function logout_user(): void {
    start_session();
    session_unset();
    session_destroy();
}
