<?php

declare(strict_types=1);

/**
 * Admin login.
 *
 * Replaces the legacy login.php which compared the username to a hardcoded
 * 'admin' and the password to a hardcoded md5 hash. This version:
 *   - reads the username and a bcrypt/argon password hash from the environment,
 *   - verifies with password_verify() and hash_equals() (constant-time),
 *   - protects the form with a CSRF token,
 *   - throttles repeated failures,
 *   - regenerates the session id on success (via Auth::login),
 *   - shows a single generic error (no user enumeration).
 */

use App\Auth;
use App\Request;
use App\Security;

/** @var array<string,mixed> $app */
$app = require __DIR__ . '/../bootstrap.php';

$config = $app['config'];
$admin  = $config['admin'];
$h      = static fn (string $v): string => Security::e($v);

// Already signed in? Go straight to the listing.
if (Auth::isAdmin()) {
    header('Location: contents.php', true, 302);
    exit;
}

$error = '';
$now   = time();

// --- Throttle state -------------------------------------------------------
$attempts  = (int) ($_SESSION['login_attempts'] ?? 0);
$lockUntil = (int) ($_SESSION['login_lock_until'] ?? 0);
$locked    = $lockUntil > $now;

if (Request::isPost()) {
    if ($locked) {
        $error = 'Too many attempts. Please try again later.';
    } elseif (!Security::verifyCsrf((string) ($_POST['csrf_token'] ?? ''))) {
        $error = 'Your session expired. Please try again.';
    } else {
        $username = (string) ($_POST['Username'] ?? '');
        $password = (string) ($_POST['Password'] ?? '');
        $hash     = (string) $admin['password_hash'];

        if ($hash === '') {
            // Misconfiguration: no hash set. Never silently allow access.
            \App\Logger::error('Admin login attempted but ADMIN_PASSWORD_HASH is not set');
            $error = 'Login is not configured. Contact the administrator.';
        } else {
            $userOk = hash_equals((string) $admin['username'], $username);
            $passOk = password_verify($password, $hash);

            if ($userOk && $passOk) {
                // Success: reset throttle, elevate session.
                unset($_SESSION['login_attempts'], $_SESSION['login_lock_until']);
                Auth::login();
                $_SESSION['UID'] = 'admin';
                header('Location: contents.php', true, 302);
                exit;
            }

            // Failure: count it, lock out if over the limit.
            $attempts++;
            $_SESSION['login_attempts'] = $attempts;
            if ($attempts >= (int) $admin['max_attempts']) {
                $_SESSION['login_lock_until'] = $now + (int) $admin['lockout_secs'];
                $_SESSION['login_attempts']   = 0;
            }
            \App\Logger::warning('Failed admin login', ['attempts' => $attempts]);
            $error = 'Incorrect login credentials!';
        }
    }
}

$csrf = Security::csrfToken();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>SlideServe - Admin Console</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400|Roboto:300,400,500,700,900|Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/pages/session/session.v1.min.css">
    <link rel="stylesheet" href="assets/css/main.bundle.min.css">
</head>
<body>
    <div class="page-wrap slate">
        <div class="session-form-hold">
            <div class="card text-center">
                <div class="card-body">
                    <img class="card-img-top signup" src="assets/images/logo-slideserve.png" alt="SlideServe">
                    <span class="text-primary text-18 d-block font-weight-bold"> SlideServe Admin </span>
                    <span class="mb-md text-muted mb-lg d-block">Sign in to SlideServe Site Admin</span>

                    <?php if ($error !== ''): ?>
                        <div class="alert alert-danger" role="alert"><?= $h($error) ?></div>
                    <?php endif; ?>

                    <form method="post" action="login.php">
                        <input type="hidden" name="csrf_token" value="<?= $h($csrf) ?>">
                        <div class="input-group input-light mb-md">
                            <input type="text" class="form-control" name="Username"
                                   placeholder="Username" autocomplete="username" required
                                   <?= $locked ? 'disabled' : '' ?>>
                        </div>
                        <div class="input-group input-light mb-md">
                            <input type="password" class="form-control" name="Password"
                                   placeholder="Password" autocomplete="current-password" required
                                   <?= $locked ? 'disabled' : '' ?>>
                        </div>
                        <button type="submit" class="btn btn-raised btn-raised-primary btn-block mb-xl"
                                <?= $locked ? 'disabled' : '' ?>>Sign In</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
