<?php
session_start();

if (!isset($_SESSION['attempts'])) $_SESSION['attempts'] = 0;

function rate_limited(): bool
{
    if ($_SESSION['attempts'] >= 5) {
        if (!isset($_SESSION['lock_time'])) $_SESSION['lock_time'] = time();
        if (time() - $_SESSION['lock_time'] < 60) return true;
        $_SESSION['attempts'] = 0;
        unset($_SESSION['lock_time']);
    }
    return false;
}

function login(): void
{
    session_regenerate_id(true);
    $_SESSION['admin_logged_in'] = true;
    $_SESSION['login_time'] = time();
}

function logout(): void
{
    session_unset();
    session_destroy();
}

function is_logged_in(): bool
{
    if (!isset($_SESSION['admin_logged_in'])) return false;
    if (time() - ($_SESSION['login_time'] ?? 0) > 900) {
        logout();
        return false;
    }
    return true;
}

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
