<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';

if (is_admin_logged_in()) {
    header('Location: dashboard.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['csrf'] ?? null)) {
        $error = 'Невірний CSRF токен.';
    } else {
        $username = trim((string)($_POST['username'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        if (!admin_login($username, $password)) {
            $error = 'Невірний логін або пароль.';
        } else {
            header('Location: dashboard.php');
            exit;
        }
    }
}

$css = nestor_asset_url('assets/css/style.css');
echo '<!doctype html><html lang="uk"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Вхід — адмінка</title><link rel="stylesheet" href="' . e($css) . '"></head><body>';
echo '<main id="main-content" class="section"><div class="wrap" style="max-width:440px">';
echo '<article class="price-card"><h1 style="margin-bottom:1rem">Адмінка блогу</h1>';
if ($error !== '') {
    echo '<p class="prose-muted" style="color:#8b4040;margin-bottom:1rem">' . e($error) . '</p>';
}
echo '<form method="post" class="contact-form" style="max-width:none">';
echo '<input type="hidden" name="csrf" value="' . e(csrf_token()) . '">';
echo '<p><label>Логін<input required name="username" autocomplete="username"></label></p>';
echo '<p><label>Пароль<input required type="password" name="password" autocomplete="current-password"></label></p>';
echo '<button class="btn btn--primary" type="submit">Увійти</button>';
echo '</form></article></div></main></body></html>';
