<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/db.php';

session_name(SESSION_NAME);
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

// ✅ If already logged in, go to the correct dashboard
if (!empty($_SESSION['user'])) {
  $role = $_SESSION['user']['role'] ?? '';
  if ($role === 'staff') {
    header('Location: ' . BASE_URL . '/staff_dashboard.php');
  } else {
    header('Location: ' . BASE_URL . '/dashboard.php');
  }
  exit;
}

$error = '';
// default next: go to correct dashboard after login
$defaultNext = '/dashboard.php';
$next = $_GET['next'] ?? ($_POST['next'] ?? $defaultNext);

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

  if ($email && $password) {
    $stmt = db()->prepare(
      "SELECT id, full_name, email, password_hash, role, is_active
       FROM users WHERE email = ? LIMIT 1"
    );
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && (int)$user['is_active'] === 1 && password_verify($password, $user['password_hash'])) {

      $_SESSION['user'] = [
        'id'        => (int)$user['id'],
        'full_name' => $user['full_name'],
        'email'     => $user['email'],
        'role'      => $user['role'],
      ];

      session_regenerate_id(true);

      // ✅ If next is blank or points to dashboard, choose by role
      if (!$next || $next === '/dashboard.php' || $next === 'dashboard.php') {
        $next = ($user['role'] === 'staff') ? '/staff_dashboard.php' : '/dashboard.php';
      }

      // Normalize redirect (prevent weird paths)
      if (str_starts_with($next, 'http')) {
        $redirect = $next;
      } else {
        $redirect = BASE_URL . '/' . ltrim($next, '/');
      }

      header('Location: ' . $redirect);
      exit;
    }
  }

  $error = 'Invalid email or password.';
}

// Standalone Login Page (no header.php/navbar)
$pageTitle = 'Login';
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?= htmlspecialchars(APP_NAME) ?> - <?= htmlspecialchars($pageTitle) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="icon" type="image/svg+xml" href="<?= BASE_URL ?>/assets/favicon/logo.svg">

  
  <link href="<?= BASE_URL ?>/assets/css/theme.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container vh-100 d-flex align-items-center justify-content-center">
  <div class="card p-4 shadow-sm" style="max-width: 460px; width:100%;">
    <h4 class="page-title text-center mb-1">Sign in</h4>
    <div class="text-muted text-center mb-3"><?= htmlspecialchars(APP_NAME) ?></div>

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

    <form method="post">
      <input type="hidden" name="next" value="<?= htmlspecialchars($next) ?>">

      <div class="mb-3">
        <label class="form-label">Email</label>
        <input type="email" name="email" 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 class="btn btn-primary w-100">Login</button>

      <a href="<?= BASE_URL ?>/index.php" class="btn btn-outline-secondary w-100 mt-2">
        ← Back to Welcome
      </a>
    </form>

    <div class="text-muted small mt-3">
      Tip: Use your staff/admin credentials provided by the system admin.
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
