<?php
/**
 * Authentication Functions
 */

function hash_password(string $password): string
{
    return password_hash($password, PASSWORD_BCRYPT, ['cost' => HASH_COST]);
}

function verify_password(string $password, string $hash): bool
{
    return password_verify($password, $hash);
}

function login_user(int $id, string $username, string $role, string $fullName): void
{
    SessionManager::regenerate();
    SessionManager::set('user_id', $id);
    SessionManager::set('user_name', $fullName);
    SessionManager::set('user_username', $username);
    SessionManager::set('user_role', $role);
    SessionManager::set('login_time', time());
}

function logout_user(): void
{
    SessionManager::destroy();
}

function current_user(): ?array
{
    $id = SessionManager::getUserId();
    if (!$id) return null;

    $db = Database::getInstance();
    return $db->fetch("SELECT * FROM users WHERE id = ? AND status = 'active'", [$id]);
}

function require_login(): void
{
    if (!SessionManager::isLoggedIn()) {
        set_error('Please log in to continue.');
        redirect(APP_URL . '/login.php');
    }
}

function require_role(string ...$roles): void
{
    require_login();
    $role = SessionManager::getUserRole();
    if (!in_array($role, $roles)) {
        http_response_code(403);
        include APP_ROOT . '/templates/header.php';
        echo '<div class="container" style="padding:50px;text-align:center"><h2>403 - Access Denied</h2><p>You do not have permission to access this page.</p><a href="' . APP_URL . '" class="btn btn-primary">Go Home</a></div>';
        include APP_ROOT . '/templates/footer.php';
        exit;
    }
}

function is_admin(): bool
{
    return SessionManager::getUserRole() === ROLE_ADMIN;
}

function is_counter(): bool
{
    return SessionManager::getUserRole() === ROLE_COUNTER;
}

function is_checker(): bool
{
    return SessionManager::getUserRole() === ROLE_CHECKER;
}

function is_controller(): bool
{
    return SessionManager::getUserRole() === ROLE_CONTROLLER;
}
