<?php
session_start();
require_once '../includes/config.php';

$err = "";

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

  $stmt = $pdo->prepare("SELECT * FROM employees WHERE email = ?");
  $stmt->execute([$email]);
  $user = $stmt->fetch();

  if ($user && password_verify($password, $user['password'])) {
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['name'];
    $_SESSION['role'] = $user['role'];

    if (!empty($_POST['remember'])) {
      setcookie("email", $email, time() + 86400 * 30);
    }

    $redirect = ($user['role'] === 'admin') ? '/admin/dashboard.php' : '/officers/dashboard.php';
    header("Location: $redirect");
    exit;
  } else {
    $err = "Invalid email or password.";
  }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Login | CFS System OS</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
  <style>
    body {
      background: linear-gradient(135deg, #1a4d80, #0e2c4d);
      color: #fff;
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: 'Segoe UI', sans-serif;
    }
    .card {
      border: none;
      border-radius: 20px;
      box-shadow: 0 0 40px rgba(0,0,0,0.2);
    }
    .form-control {
      border-radius: 12px;
    }
    .btn-primary {
      background-color: #007bff;
      border: none;
      border-radius: 12px;
    }
    .btn-primary:hover {
      background-color: #0056b3;
    }
    .logo {
      width: 60px;
      height: auto;
    }
    .brand-title {
      font-size: 24px;
      font-weight: 600;
    }
    a {
      color: #e0e0e0;
    }
    a:hover {
      color: #ffffff;
      text-decoration: underline;
    }
  </style>
</head>
<body>

<div class="card p-4" style="width: 400px;">
  <div class="text-center mb-3">
    <img src="../assets/logo.png" alt="CFS Logo" class="logo mb-2">
    <div class="brand-title">CFS System OS</div>
  </div>

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

  <form method="post">
    <div class="mb-3">
      <label>Email</label>
      <input type="email" name="email" value="<?= $_COOKIE['email'] ?? '' ?>" class="form-control" required>
    </div>
    <div class="mb-3">
      <label>Password</label>
      <input type="password" name="password" class="form-control" required>
    </div>
    <div class="form-check mb-3">
      <input type="checkbox" class="form-check-input" name="remember" id="remember">
      <label class="form-check-label" for="remember">Remember Me</label>
    </div>
    <button type="submit" class="btn btn-primary w-100">Login</button>

    <div class="text-center mt-3">
      <a href="forgot_password.php">Forgot Password?</a><br>
      <a href="register.php">Don't have an account? Register</a>
    </div>
  </form>
</div>

</body>
</html>
