<?php
require_once __DIR__ . '/inc/layout.php';
require_once __DIR__ . '/inc/auth.php';

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

$error = '';

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

    if (login_attempt($username, $password)) {
        header('Location: dashboard.php');
        exit;
    } else {
        $error = 'Invalid username or password.';
    }
}

page_header('Login');
?>

<div class="row justify-content-center">
    <div class="col-md-5 col-lg-4">
        <div class="card soft-card mt-5">
            <div class="card-body p-4">
                <h3 class="mb-4 text-center">Sign in</h3>

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

                <form method="post">
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" name="username" class="form-control" required autofocus>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>

                    <button type="submit" class="btn btn-primary w-100">Login</button>
                </form>

                <div class="text-center text-muted small mt-3">Restricted access</div>
            </div>
        </div>
    </div>
</div>

<?php page_footer(); ?>