<?php

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/helpers.php';

function sparrow_start_session(): void
{
    if (session_status() === PHP_SESSION_ACTIVE) {
        return;
    }

    session_name('sparrow_backyard_session');

    $is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');

    ini_set('session.use_strict_mode', '1');
    ini_set('session.use_only_cookies', '1');
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'httponly' => true,
        'samesite' => 'Lax',
        'secure' => $is_https,
    ]);

    session_start();
}

function sparrow_current_user(): ?array
{
    sparrow_start_session();

    if (empty($_SESSION['backyard_user_id'])) {
        return null;
    }

    $pdo = sparrow_db();

    $stmt = $pdo->prepare("
        SELECT id, name, email, role
        FROM backyard_users
        WHERE id = :id
        AND is_active = 1
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $_SESSION['backyard_user_id'],
    ]);

    $user = $stmt->fetch();

    return $user ?: null;
}

function sparrow_login(string $email, string $password): bool
{
    sparrow_start_session();

    $pdo = sparrow_db();

    $stmt = $pdo->prepare("
        SELECT id, name, email, password_hash, role
        FROM backyard_users
        WHERE email = :email
        AND is_active = 1
        LIMIT 1
    ");

    $stmt->execute([
        ':email' => $email,
    ]);

    $user = $stmt->fetch();

    if (!$user) {
        password_verify($password, '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.');
        return false;
    }

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

    session_regenerate_id(true);

    $_SESSION['backyard_user_id'] = $user['id'];

    return true;
}

function sparrow_require_backyard_login(): array
{
    $user = sparrow_current_user();

    if (!$user) {
        sparrow_redirect('/login.php');
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $source = (string) ($_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '');
        $expected_host = strtolower((string) ($_SERVER['HTTP_HOST'] ?? ''));
        $source_host = strtolower((string) parse_url($source, PHP_URL_HOST));
        if ($source === '' || $expected_host === '' || $source_host !== preg_replace('/:\d+$/', '', $expected_host)) {
            http_response_code(403);
            exit('Request validation failed. Please reload the page and try again.');
        }
    }

    return $user;
}

function sparrow_logout(): void
{
    sparrow_start_session();

    $_SESSION = [];

    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();

        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params['path'],
            $params['domain'] ?? '',
            $params['secure'],
            $params['httponly']
        );
    }

    session_destroy();
}
