<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_name('PKOADMIN');
    session_start();
}

if (empty($_SESSION['csrf_admin'])) {
    $_SESSION['csrf_admin'] = bin2hex(random_bytes(32));
}

function admin_csrf(): string
{
    return $_SESSION['csrf_admin'];
}

function admin_check_csrf(): void
{
    $token = (string) ($_POST['csrf'] ?? $_GET['csrf'] ?? '');
    if (!hash_equals($_SESSION['csrf_admin'], $token)) {
        http_response_code(419);
        exit('Invalid token. Reload the page and try again.');
    }
}

function admin_logged_in(): bool
{
    return !empty($_SESSION['admin_ok']);
}

function admin_require_login(): void
{
    if (!admin_logged_in()) {
        header('Location: index.php');
        exit;
    }
}

/** Returns [locked, minutesLeft]. */
function admin_lock_state(string $ip): array
{
    $stmt = db()->prepare('SELECT attempts, locked_until FROM login_attempts WHERE ip_address = ?');
    $stmt->execute([$ip]);
    $row = $stmt->fetch();
    if (!$row || !$row['locked_until']) {
        return [false, 0];
    }
    $left = strtotime($row['locked_until']) - time();
    return $left > 0 ? [true, (int) ceil($left / 60)] : [false, 0];
}

function admin_register_failure(string $ip): void
{
    $pdo = db();
    $pdo->prepare(
        'INSERT INTO login_attempts (ip_address, attempts, last_attempt)
         VALUES (?, 1, NOW())
         ON DUPLICATE KEY UPDATE attempts = attempts + 1, last_attempt = NOW()'
    )->execute([$ip]);

    $stmt = $pdo->prepare('SELECT attempts FROM login_attempts WHERE ip_address = ?');
    $stmt->execute([$ip]);
    if ((int) $stmt->fetchColumn() >= LOGIN_MAX_ATTEMPTS) {
        $pdo->prepare(
            'UPDATE login_attempts
                SET locked_until = DATE_ADD(NOW(), INTERVAL ? MINUTE), attempts = 0
              WHERE ip_address = ?'
        )->execute([LOGIN_LOCK_MINUTES, $ip]);
    }
}

function admin_clear_failures(string $ip): void
{
    db()->prepare('DELETE FROM login_attempts WHERE ip_address = ?')->execute([$ip]);
}
