<?php
// public/login.php
require_once __DIR__ . '/../helpers/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)) {

    // Role-based redirect
    $u = current_user(); // comes from auth.php

    if (($u['role'] ?? '') === 'admin') {
        header('Location: dashboard.php');
        exit;
    }

    if (($u['role'] ?? '') === 'staff') {
        header('Location: staff_dashboard.php');
        exit;
    }

    if (($u['role'] ?? '') === 'driver') {
        header('Location: driver_app.php');
        exit;
    }

    // fallback
    header('Location: dashboard.php');
    exit;
}

}


?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Login - IMS Delivery Tracker</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container">
  <div class="row justify-content-center align-items-center" style="min-height:100vh;">
    <div class="col-12 col-md-5 col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body p-4">
          <h4 class="mb-3">Login</h4>

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

          <form method="POST" autocomplete="off">
            <div class="mb-3">
              <label class="form-label">Username</label>
              <input class="form-control" name="username" type="text" value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" required>
            </div>

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

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

        
        </div>
      </div>
    </div>
  </div>
</div>

</body>
</html>
