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

if (is_logged_in()) {
    redirect(APP_URL . '/main.php');
}

$errors = [];
$old_name = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = __('err_csrf');
    } else {
        $name = trim((string)($_POST['name'] ?? ''));
        $pass = (string)($_POST['password'] ?? '');
        $old_name = $name;

        if ($name === '' || $pass === '') {
            $errors[] = __('err_login_failed');
        } else {
            $user = User::authenticate($name, $pass);
            if (!$user) {
                $errors[] = __('err_login_failed');
            } elseif ((int)$user['is_banned'] === 1) {
                $errors[] = __('err_account_banned', ['reason' => $user['ban_reason'] ?? '-']);
            } else {
                User::loginSession($user);
                redirect(APP_URL . '/main.php');
            }
        }
    }
}

$page_title = __('login_title');
$hide_menu = true;
require __DIR__ . '/includes/header.php';
?>

<div class="auth-page">
    <h1><?= e(__('login_title')) ?></h1>

    <div class="tabs">
        <a href="<?= APP_URL ?>/login.php" class="active"><?= __('login') ?></a>
        <a href="<?= APP_URL ?>/register.php"><?= __('register') ?></a>
    </div>

    <?php foreach ($errors as $err): ?>
        <div class="flash flash-error"><?= e($err) ?></div>
    <?php endforeach; ?>

    <form method="post" action="<?= APP_URL ?>/login.php">
        <?= csrf_field() ?>

        <div class="form-row">
            <label for="name"><?= __('username') ?></label>
            <input type="text" id="name" name="name" required
                   value="<?= e($old_name) ?>" autofocus>
        </div>

        <div class="form-row">
            <label for="password"><?= __('password') ?></label>
            <input type="password" id="password" name="password" required>
        </div>

        <button type="submit" style="width:100%;"><?= __('login') ?></button>
    </form>

    <p class="text-center mt-1 text-muted">
        <?= __('no_account') ?> <a href="<?= APP_URL ?>/register.php"><?= __('register') ?></a>
    </p>
</div>

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