<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/middleware.php';
require_once __DIR__ . '/includes/auth.php';

if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/config/database.php';
}

require_guest();
$errors = [];
if (is_post()) {
    ensure_csrf();
    $email = sanitize_str($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    if (!attempt_login($pdo, $email, $password)) {
        $errors[] = 'Invalid credentials';
    } else {
        $role = $_SESSION['user']['role'] ?? 'customer';
        if ($role === 'admin') {
            redirect(url('admin/dashboard.php'));
        } else {
            $redirect = $_POST['redirect'] ?? $_GET['redirect'] ?? 'customer/dashboard.php';
            redirect(url($redirect));
        }
    }
}
include __DIR__ . '/includes/header.php';
?>
<section class="section" style="padding-top:24px">
  <div class="grid grid-2">
    <div class="card reveal">
      <h2 style="margin:0 0 6px">Welcome Back</h2>
      <p class="lead" style="margin:0 0 12px">Log in to track your applications, manage your documents, and stay ahead of your compliance.</p>
      <?php foreach ($errors as $e): ?><div class="flash error"><?=e($e)?></div><?php endforeach; ?>
      <form method="post" action="<?=url('login.php') . (isset($_GET['redirect']) ? '?redirect=' . urlencode($_GET['redirect']) : '')?>">
        <?=csrf_field()?>
        <?php if (isset($_GET['redirect'])): ?>
          <input type="hidden" name="redirect" value="<?=e($_GET['redirect'])?>">
        <?php endif; ?>
        <label>Email</label>
        <input type="email" name="email" required>
        <label>Password</label>
        <input type="password" name="password" required>
        <button class="btn primary" type="submit" style="margin-top:12px;width:100%">Login</button>
      </form>
      <div style="margin-top: 16px; text-align: center;">
        <a href="<?=url('forgot_password.php')?>" style="color: var(--primary); text-decoration: none; font-size: 14px; font-weight: 500;">Forgot Password?</a>
      </div>
      <p class="muted" style="margin-top:10px">New here? <a href="<?=url('register.php') . (isset($_GET['redirect']) ? '?redirect=' . urlencode($_GET['redirect']) : '')?>">Create an account</a></p>

    </div>
    <div class="card reveal" style="border:none;padding:0;display:flex;align-items:center;justify-content:center">
      <img src="<?=url('assets/hero-abstract.svg')?>" alt="Login visual" style="width:100%;max-width:520px;border-radius:12px">
    </div>
  </div>
</section>
<?php include __DIR__ . '/includes/footer.php'; ?>
