<?php

require_once __DIR__ . '/../lib/init.php';

if (Auth::isLoggedIn()) {
    header('Location: dashboard.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username === '' || $password === '') {
        $error = 'Veuillez remplir tous les champs.';
    } elseif (!Auth::login($username, $password)) {
        $error = 'Identifiants incorrects.';
        AuditLog::log('login.failed', 'user', null, 'Tentative avec username: ' . $username);
    } else {
        AuditLog::log('login.success');
        header('Location: dashboard.php');
        exit;
    }
}

$appName = Settings::get('app_name', 'DHCPMan');
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= h($appName) ?> — Connexion</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
    <link rel="stylesheet" href="assets/css/app.css">
</head>
<body>
<div class="login-wrapper">
    <div class="login-card card p-4">
        <div class="login-logo">&#127760;</div>
        <h4 class="text-center mb-1 fw-bold"><?= h($appName) ?></h4>
        <p class="text-center text-muted small mb-4">Gestion des réservations DHCP</p>

        <?php if ($error): ?>
            <div class="alert alert-danger py-2">
                <i class="bi bi-exclamation-triangle"></i> <?= h($error) ?>
            </div>
        <?php endif; ?>

        <form method="post" autocomplete="off">
            <div class="mb-3">
                <label class="form-label fw-semibold">Utilisateur</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-person"></i></span>
                    <input type="text" name="username" class="form-control"
                           value="<?= h($_POST['username'] ?? '') ?>"
                           autofocus required>
                </div>
            </div>
            <div class="mb-4">
                <label class="form-label fw-semibold">Mot de passe</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-lock"></i></span>
                    <input type="password" name="password" class="form-control" required>
                </div>
            </div>
            <button type="submit" class="btn btn-primary w-100 fw-semibold">
                <i class="bi bi-box-arrow-in-right"></i> Se connecter
            </button>
        </form>

        <div class="text-center mt-3">
            <a href="reservation_request.php" class="text-muted small text-decoration-none">
                <i class="bi bi-envelope-plus me-1"></i>Faire une demande de réservation
            </a>
        </div>
    </div>
</div>
</body>
</html>
