<?php
require_once __DIR__ . '/../../app/helpers/functions.php';

session_boot();

$conn = require __DIR__ . '/../../app/config/database.php';

$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $email = trim($_POST['email'] ?? '');
  $password = $_POST['password'] ?? '';

  if (!$email || !$password) {
    $error = "Email and password required";
  } else {

    /* FETCH ADMIN (MYSQLI) */
    $sql = "
      SELECT u.id, u.password_hash, u.status
      FROM users u
      INNER JOIN user_roles ur ON ur.user_id = u.id
      INNER JOIN roles r ON r.id = ur.role_id
      WHERE u.email = ?
        AND r.name IN ('admin','super_admin')
      LIMIT 1
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $admin = $stmt->get_result()->fetch_assoc();

    if (!$admin) {
      $error = "Admin account not found or role not assigned";

    } elseif (($admin['status'] ?? 'active') !== 'active') {
      $error = "Admin account is disabled";

    } else {

      $stored = $admin['password_hash'];
      $passwordOk = false;

      /* 1️⃣ HASHED PASSWORD */
      if (password_verify($password, $stored)) {
        $passwordOk = true;
      }

      /* 2️⃣ LEGACY RAW PASSWORD (AUTO-UPGRADE) */
      elseif (hash_equals($stored, $password)) {
        $passwordOk = true;

        // Upgrade to hashed password
        $newHash = password_hash($password, PASSWORD_DEFAULT);
        $uid = (int)$admin['id'];

        $up = $conn->prepare(
          "UPDATE users SET password_hash=? WHERE id=?"
        );
        $up->bind_param("si", $newHash, $uid);
        $up->execute();
      }

      if (!$passwordOk) {
        $error = "Incorrect password";
      } else {
        session_regenerate_id(true);
        session_boot();

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

$_SESSION['admin_id'] = (int)$admin['id'];

header("Location: dashboard.php");
exit;

      }
    }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Eliteguarantytrust Inc | Admin Login</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">

<style>
:root{
  --gold:#D4AF37;
  --panel:#111;
  --border:#222;
}
body{
  background:linear-gradient(135deg,#050505,#0e0e0e);
  min-height:100vh;
  display:flex;
  align-items:center;
  justify-content:center;
}
.login-container{max-width:420px;width:100%}
.login-card{
  background:var(--panel);
  border:1px solid var(--border);
  border-radius:14px;
  padding:36px;
}
.brand{text-align:center;margin-bottom:28px}
.brand h1{color:var(--gold);font-weight:700;letter-spacing:.6px}
.brand small{color:#9ca3af}
.form-label{color:#cbd5e1;font-size:13px}
.form-control{background:#0c0c0c;border:1px solid var(--border);color:#fff}
.form-control:focus{border-color:var(--gold);box-shadow:none}
.btn-gold{background:var(--gold);color:#000;font-weight:600}
.btn-gold:hover{background:#c5a634}
.footer-note{text-align:center;color:#6b7280;font-size:11px;margin-top:20px}
</style>
</head>

<body>

<div class="login-container">
  <div class="login-card">

    <div class="brand">
      <h1>Eliteguarantytrust Inc</h1>
      <small>Administrative Control Panel</small>
    </div>

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

    <form method="post" autocomplete="off">

      <div class="mb-3">
        <label class="form-label">Admin Email</label>
        <input type="email" name="email" class="form-control" required>
      </div>

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

      <button class="btn btn-gold w-100">
        <i class="bi bi-shield-lock me-2"></i>Sign In Securely
      </button>

    </form>

    <div class="footer-note">
      Restricted access • All activities are logged
    </div>

  </div>
</div>

</body>
</html>
