<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';

if (current_user() && is_admin(current_user())) {
    redirect(url('admin/index.php'));
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login = (string) ($_POST['username'] ?? '');
    $password = (string) ($_POST['password'] ?? '');
    $user = find_user_by_login($login);

    if (!$user || !password_verify($password, $user['password'] ?? '') || !is_admin($user)) {
        $error = 'Kullanıcı adı veya şifre hatalı.';
    } else {
        login_user($user);
        flash('success', 'Panele hoş geldin.');
        redirect(url('admin/index.php'));
    }
}

$pageTitle = 'Yönetim Girişi';
$pageClass = 'page-admin page-admin-login';
require __DIR__ . '/../includes/header.php';
?>
<link rel="stylesheet" href="<?= e(url('assets/css/admin.css')) ?>">

<div class="admin-login-page">
    <form method="post" class="admin-login-card">
        <div class="admin-login-brand">
            <span class="admin-login-mark"><?= e(mb_strtoupper(mb_substr(site_name(), 0, 1))) ?></span>
            <div>
                <strong><?= e(site_name()) ?></strong>
                <p>Yönetim paneli girişi</p>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="admin-alert error"><?= e($error) ?></div>
        <?php endif; ?>

        <label>
            Kullanıcı adı
            <input type="text" name="username" autocomplete="username" required autofocus placeholder="admin">
        </label>
        <label>
            Şifre
            <input type="password" name="password" autocomplete="current-password" required placeholder="••••••">
        </label>
        <button class="admin-btn" type="submit">Giriş Yap</button>
    </form>
</div>

<?php require __DIR__ . '/../includes/footer.php'; ?>
