<?php
declare(strict_types=1);
require __DIR__ . '/lib/Auth.php';
require __DIR__ . '/lib/Layout.php';

use PSLauncher\Admin\Auth;
use PSLauncher\Admin\Layout;

Auth::start();

// Si déjà connecté, on redirige
if (Auth::isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$config = require __DIR__ . '/../api/config.php';
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Auth::checkCsrf();
    $user = trim($_POST['username'] ?? '');
    $pass = $_POST['password'] ?? '';
    if (Auth::login($user, $pass, $config)) {
        header('Location: index.php');
        exit;
    }
    $error = 'Identifiants invalides';
    sleep(1); // throttling très basique
}

Layout::header('Connexion');
?>
<div style="max-width: 400px; margin: 80px auto;">
    <div class="card">
        <h1 style="margin-bottom: 8px;">PS_Launcher</h1>
        <p class="muted" style="margin-top: 0; margin-bottom: 24px;">Backoffice administration</p>
        <?php Layout::flash($error, 'error'); ?>
        <form method="post">
            <?= Layout::csrfField() ?>
            <div class="field">
                <label>Utilisateur</label>
                <input type="text" name="username" required autofocus value="admin">
            </div>
            <div class="field">
                <label>Mot de passe</label>
                <input type="password" name="password" required>
            </div>
            <button class="btn btn-primary" type="submit" style="width:100%; padding: 10px;">Connexion</button>
        </form>
    </div>
</div>
<?php Layout::footer();
