<?php
/**
 * auth.php
 *
 * Session-backed authentication helpers. config.php must be loaded first
 * (it bootstraps the secure session + libraries).
 */

require_once __DIR__ . '/config.php';

function current_user(): ?array
{
    if (!isset($_SESSION['user_id'])) return null;
    return [
        'id'          => (int) $_SESSION['user_id'],
        'username'    => $_SESSION['username']    ?? '',
        'full_name'   => $_SESSION['full_name']   ?? '',
        'role'        => $_SESSION['role']        ?? '',
        'facility_id' => isset($_SESSION['facility_id']) ? (int) $_SESSION['facility_id'] : null,
    ];
}

function require_login(): void
{
    if (!isset($_SESSION['user_id'])) {
        if (!headers_sent()) header('Location: login.php');
        exit;
    }
    // Idle timeout: 4h of inactivity = logout.
    $maxIdle = 4 * 3600;
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $maxIdle) {
        auth_logout();
        if (!headers_sent()) header('Location: login.php?reason=idle');
        exit;
    }
    $_SESSION['last_activity'] = time();
}

function require_super_admin(): void
{
    require_login();
    $u = current_user();
    if (!$u || $u['role'] !== 'super_admin') {
        http_response_code(403);
        echo "Forbidden";
        exit;
    }
}

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

function auth_login_user(PDO $pdo, array $user): void
{
    // Defence in depth: regenerate session id on privilege change.
    session_regenerate_id(true);

    $_SESSION['user_id']       = (int) $user['id'];
    $_SESSION['username']      = $user['username'];
    $_SESSION['full_name']     = $user['full_name'];
    $_SESSION['role']          = $user['role'];
    $_SESSION['facility_id']   = $user['facility_id'];
    $_SESSION['last_activity'] = time();

    csrf_rotate();
    audit_log($pdo, 'login_success', ['user_id' => (int)$user['id'], 'username' => $user['username']]);
}

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

// Used by candidates.php when creating new candidates.
function generate_barcode_from_id(int $id): string
{
    return 'C' . str_pad((string)$id, 6, '0', STR_PAD_LEFT);
}
