<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/permissions.php';
require_once __DIR__ . '/audit.php';

function current_user(bool $refresh = false): ?array
{
    static $cachedUser = null;

    if ($refresh) {
        $cachedUser = null;
    }

    if ($cachedUser !== null) {
        return $cachedUser;
    }

    $userId = isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : 0;

    if ($userId <= 0) {
        return null;
    }

    $user = db_fetch_one(
        'SELECT u.*, r.name AS role_name, c.name AS club_name
         FROM users u
         INNER JOIN roles r ON r.id = u.role_id
         LEFT JOIN clubs c ON c.id = u.club_id
         WHERE u.id = :id
         LIMIT 1',
        ['id' => $userId]
    );

    if (!$user || $user['status'] !== 'active') {
        force_logout();
        return null;
    }

    $_SESSION['role_name'] = $user['role_name'];
    $_SESSION['user_club_id'] = $user['club_id'];
    $cachedUser = $user;

    return $cachedUser;
}

function is_logged_in(): bool
{
    return current_user() !== null;
}

function attempt_login(string $email, string $password): bool
{
    $email = strtolower(trim($email));

    $user = db_fetch_one(
        'SELECT u.*, r.name AS role_name
         FROM users u
         INNER JOIN roles r ON r.id = u.role_id
         WHERE u.email = :email
         LIMIT 1',
        ['email' => $email]
    );

    if (!$user || $user['status'] !== 'active') {
        return false;
    }

    if (!password_verify($password, $user['password_hash'])) {
        return false;
    }

    session_regenerate_id(true);
    $_SESSION['user_id'] = (int) $user['id'];
    $_SESSION['role_name'] = $user['role_name'];
    $_SESSION['user_club_id'] = $user['club_id'];
    unset($_SESSION['permissions'], $_SESSION['_permissions_loaded_for']);
    user_permissions((int) $user['id']);

    db_query(
        'UPDATE users SET last_login = NOW(), updated_at = NOW() WHERE id = :id',
        ['id' => $user['id']]
    );

    audit_log('login', 'auth', (int) $user['id'], null, ['email' => $user['email']]);

    return true;
}

function require_login(): void
{
    if (!is_logged_in()) {
        flash('error', ['type' => 'danger', 'message' => 'Please sign in to continue.']);
        $_SESSION['intended_url'] = $_SERVER['REQUEST_URI'] ?? null;
        redirect('login.php');
    }
}

function redirect_after_login(): void
{
    $intendedUrl = $_SESSION['intended_url'] ?? null;
    unset($_SESSION['intended_url']);

    if (is_string($intendedUrl) && $intendedUrl !== '') {
        header('Location: ' . $intendedUrl);
        exit;
    }

    redirect('dashboard.php');
}

function force_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 logout_user(): void
{
    $userId = isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : null;

    if ($userId !== null) {
        audit_log('logout', 'auth', $userId);
    }

    force_logout();
}
