<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;

if (Auth::check()) {
    redirect(role_dashboard_url());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) {
        set_flash('error', 'Invalid security token. Refresh the page and try again.');
    } elseif (Auth::attempt((string)($_POST['email'] ?? ''), (string)($_POST['password'] ?? ''))) {
        if (!in_array((string)Auth::role(), ['admin', 'staff'], true)) {
            Auth::logout(false);
            set_flash('error', 'This account does not have administration access.');
        } else {
            redirect(role_dashboard_url());
        }
    } else {
        set_flash('error', 'Invalid credentials, inactive account, or too many attempts.');
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin Login | <?= e(APP_NAME) ?></title>
<link rel="stylesheet" href="<?= admin_asset('css/bootstrap.min.css') ?>">
<link rel="stylesheet" href="<?= asset('css/purchase-haat.css') ?>">
</head>
<body class="panel-bg">
<div class="container py-5"><div class="row justify-content-center"><div class="col-md-5">
<div class="card border-0 shadow-lg"><div class="card-body p-4">
<div class="text-center mb-3"><img src="<?= asset('brand/logo.png') ?>" height="62" alt="<?= e(BRAND_NAME) ?>"></div>
<h4 class="text-center">Administration Login</h4>
<?php if ($msg = flash('error')): ?><div class="alert alert-danger"><?= e($msg) ?></div><?php endif; ?>
<form method="post" autocomplete="on">
<?= csrf_field() ?>
<label class="form-label">Email</label>
<input type="email" name="email" class="form-control mb-3" value="<?= e($_POST['email'] ?? '') ?>" autocomplete="username" required autofocus>
<label class="form-label">Password</label>
<input type="password" name="password" class="form-control mb-3" autocomplete="current-password" required>
<button class="btn btn-primary w-100">Login</button>
</form>
<div class="text-center mt-3"><a href="<?= url('public/forgot-password.php') ?>">Forgot password?</a></div>
</div></div>
</div></div></div>
</body>
</html>
