<?php
/**
 * Admin Login
 */

require_once __DIR__ . '/bootstrap.php';

$pdo = $GLOBALS['pdo'];

// If no users exist, redirect to installer
$userCount = $pdo->query("SELECT COUNT(*) as count FROM users")->fetch();
if (!\Core\Auth::check() && ($userCount['count'] ?? 0) == 0) {
    header('Location: /admin/install.php');
    exit;
}

if (\Core\Auth::check()) {
    header('Location: /admin/index.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (\Core\Auth::login($_POST['username'] ?? '', $_POST['password'] ?? '', $pdo)) {
        if (\Core\Auth::needsPasswordReset()) {
            header('Location: /admin/force-password.php');
            exit;
        }
        header('Location: /admin/index.php');
        exit;
    } else {
        $error = 'Invalid username or password.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - AI-Native CMS</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@1/css/pico.min.css">
    <style>
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }

        article {
            width: 100%;
            max-width: 400px;
        }
    </style>
</head>

<body>
    <article>
        <header>
            <strong>Login to Admin</strong>
        </header>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
            <?php if ($error): ?>
                <p style="color: red;"><?= $error ?></p><?php endif; ?>
            <label>Username
                <input type="text" name="username" required>
            </label>
            <label>Password
                <input type="password" name="password" required>
            </label>
            <button type="submit">Login</button>
        </form>
    </article>
</body>

</html>
