<?php
require_once __DIR__ . '/core/auth.php';
$pdo = pdo();
if (current_user()) {
    redirect('dashboard.php');
}

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

    if (attempt_login($pdo, $username, $password)) {
        redirect('dashboard.php');
    }

    flash_set('error', 'Invalid username or password.');
    redirect('index.php');
}
$error = flash_get('error');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e(app_name()) ?> - Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/app.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container">
    <div class="row min-vh-100 align-items-center justify-content-center">
        <div class="col-12 col-md-6 col-lg-4">
            <div class="card shadow-sm border-0">
                <div class="card-body p-4">
                    <h1 class="h3 text-center mb-3"><?= e(app_name()) ?></h1>
                    <p class="text-muted text-center mb-4">Mobile-friendly distributor reporting portal</p>
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?= e($error) ?></div>
                    <?php endif; ?>
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" name="username" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Password</label>
                            <input type="password" name="password" class="form-control" required>
                        </div>
                        <button class="btn btn-primary w-100">Login</button>
                    </form>
                    <div class="small text-muted mt-3">
                        Demo users are included in <code>database/schema.sql</code>.<br>
                        Demo agent / report data for the RSM account is included in <code>database/demo_data.sql</code>.<br>
                        Admin: <strong>admin</strong> / <strong>3</strong><br>
                        RSM: <strong>rsm1</strong> / <strong>Rsm@123</strong>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
