<?php

declare(strict_types=1);

function auth_start_session(): void
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
}

function auth_user(): ?array
{
    return $_SESSION['user'] ?? null;
}

function auth_is_logged_in(): bool
{
    return auth_user() !== null;
}

function auth_login(array $user): void
{
    $_SESSION['user'] = [
        'user_id' => (int)$user['user_id'],
        'email' => (string)$user['email'],
        'full_name' => (string)$user['full_name'],
        'user_type' => (string)$user['user_type'],
        'is_active' => (int)($user['is_active'] ?? 1),
    ];

    session_regenerate_id(true);
}

function auth_logout(): void
{
    $_SESSION = [];

    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], (bool)$params['secure'], (bool)$params['httponly']);
    }

    session_destroy();
}

function auth_require_login(): void
{
    if (!auth_is_logged_in()) {
        header('Location: ' . Constants::APP_ROOT . '/login.php');
        exit;
    }
}

function auth_require_role(array $roles): void
{
    auth_require_login();

    $user = auth_user();
    $role = $user['user_type'] ?? '';

    if (!in_array($role, $roles, true)) {
        http_response_code(403);
        echo 'Forbidden';
        exit;
    }
}

function auth_default_dashboard_path(): string
{
    $user = auth_user();
    $role = $user['user_type'] ?? null;

    switch ($role) {
        case 'admin':
            return Constants::APP_ROOT . '/admin/index.php';
        case 'staff':
            return Constants::APP_ROOT . '/staff/index.php';
        case 'customer':
            return Constants::APP_ROOT . '/customer/overview.php';
        default:
            return Constants::APP_ROOT . '/login.php';
    }
}

function auth_verify_password(string $password, string $storedHash): bool
{
    $prefixBcrypt = substr($storedHash, 0, 4) === '$2y$';
    $prefixArgon = substr($storedHash, 0, 6) === '$argon2';

    if ($prefixBcrypt || $prefixArgon) {
        return password_verify($password, $storedHash);
    }

    return hash_equals($storedHash, $password);
}
