<?php
declare(strict_types=1);
ini_set('display_errors','1'); error_reporting(E_ALL);

if (session_status() !== PHP_SESSION_ACTIVE) session_start();

/* ---------- include auth.php ---------- */
$ROOT = is_dir(__DIR__ . '/includes') ? __DIR__ : dirname(__DIR__);
$authPath = $ROOT . '/includes/auth.php';
if (!is_file($authPath)) {
  die("includes/auth.php not found.");
}
require_once $authPath;

$db = ec_db(); if (!$db) die('DB connection error');

function h($v): string {
  return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

/* ✅ Set your logo path here (upload logo to this location) */
$logoUrl = '/edenrms/assets/img/eden-logo.png.JPG';

/* ---------- handle POST ---------- */
$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $emailOrUser = trim((string)($_POST['username'] ?? ''));
  $pwd         = (string)($_POST['password'] ?? '');

  /* modern users table */
  if ($emailOrUser && $pwd && table_exists($db, 'users')) {

    $hasUserCol = col_exists($db, 'users', 'username');

    $sql = $hasUserCol
      ? "SELECT * FROM users WHERE email=? OR username=? LIMIT 1"
      : "SELECT * FROM users WHERE email=? LIMIT 1";

    if ($st = $db->prepare($sql)) {
      $hasUserCol
        ? $st->bind_param('ss', $emailOrUser, $emailOrUser)
        : $st->bind_param('s',  $emailOrUser);

      $st->execute();
      $u = $st->get_result()->fetch_assoc();
      $st->close();

      if ($u && (int)$u['active'] === 1 && password_verify($pwd, $u['password_hash'])) {

        ec_set_session_user([
          'id'       => (int)$u['id'],
          'name'     => $u['name'],
          'email'    => $u['email'],
          'username' => $u['username'] ?? $u['email'],
          'role'     => $u['role_slug'] ?: 'staff',
          'active'   => 1
        ]);

        if (!empty($_POST['remember'])) {
          setcookie('eden_user', $u['email'], time()+86400*30, '/', '', false, true);
        }

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

  /* legacy admin fallback */
  if (table_exists($db, 'admin')) {
    if ($st = $db->prepare("SELECT username,password FROM admin WHERE username=? LIMIT 1")) {
      $st->bind_param('s',$emailOrUser);
      $st->execute();
      $old = $st->get_result()->fetch_assoc();
      $st->close();

      if ($old && md5($pwd) === $old['password']) {
        ec_set_session_user([
          'id' => 0,
          'name' => $old['username'],
          'email' => $old['username'].'@legacy.local',
          'username' => $old['username'],
          'role' => 'super_admin',
          'active' => 1
        ]);
        header('Location: /edenrms/pages/dashboard.php');
        exit;
      }
    }
  }

  $err = 'Invalid username or password.';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login — Eden RMS</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="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
:root{
  --bg:#f6f7fb;
  --card:#ffffff;
  --border:#e5e7eb;
  --text:#0f172a;
  --muted:#64748b;
  --primary:#111827;
}

body{
  min-height:100vh;
  margin:0;
  font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;
  background:var(--bg);
  display:flex;
  align-items:center;
  justify-content:center;
  padding:24px;
  color:var(--text);
}

.login-wrap{
  width:100%;
  max-width:420px;
}

.login-card{
  background:var(--card);
  border:1px solid var(--border);
  border-radius:18px;
  padding:28px 28px 22px;
  box-shadow: 0 18px 45px rgba(15,23,42,.08);
}

/* Header row like screenshot */
.logo-area{
  display:flex;
  flex-direction:row;
  align-items:center;
  gap:12px;
  text-align:left;
  margin-bottom:18px;
  padding-bottom:12px;
  border-bottom:1px solid var(--border);
}

.logo{
  width:46px;
  height:46px;
  object-fit:contain;
  border-radius:12px;
  padding:6px;
  border:1px solid var(--border);
  background:#fff;
}

.brand{
  margin:0;
  font-weight:800;
  letter-spacing:.14em;
  font-size:.85rem;
  line-height:1.1;
}

.tag{
  margin:4px 0 0 0;
  font-size:.78rem;
  color:var(--muted);
  line-height:1.1;
}


h1{
  font-size:1.35rem;
  font-weight:800;
  margin:16px 0 6px;
  text-align:left;
}

.sub{
  font-size:.92rem;
  color:var(--muted);
  margin-bottom:18px;
}

label{
  font-size:.78rem;
  font-weight:700;
  color:#475569;
  margin-bottom:6px;
}

.form-control{
  border-radius:12px;
  border:1px solid var(--border);
  padding:.78rem .9rem;
  font-size:.95rem;
}

.form-control:focus{
  border-color: rgba(17,24,39,.55);
  box-shadow: 0 0 0 .18rem rgba(17,24,39,.10);
}

.input-group .btn-eye{
  border:1px solid var(--border);
  border-left:0;
  border-radius:0 12px 12px 0;
  background:#fff;
  color:#334155;
}

.input-group .btn-eye:focus{
  box-shadow: 0 0 0 .18rem rgba(17,24,39,.10);
}

.caps-warn{
  display:none;
  font-size:.78rem;
  color:#b45309;
  background:#fff7ed;
  border:1px solid #fed7aa;
  padding:8px 10px;
  border-radius:12px;
}

.row-links{
  display:flex;
  justify-content:space-between;
  align-items:center;
  margin:14px 0 18px;
}

.small-link{
  font-size:.80rem;
  color:var(--muted);
  text-decoration:none;
}

.small-link:hover{
  color:var(--text);
  text-decoration:underline;
}

.btn-login{
  width:100%;
  border:none;
  border-radius:999px;
  padding:.95rem 1rem;
  font-weight:800;
  color:#fff;
  background: linear-gradient(180deg, #1f2937, #0b1220);
  box-shadow: 0 16px 30px rgba(15,23,42,.18);
  display:flex;
  align-items:center;
  justify-content:center;
  gap:10px;
}
.btn-login:hover{ filter:brightness(1.03); }


.btn-login:hover{ background:#000; }

.footer{
  margin-top:16px;
  text-align:center;
  font-size:.75rem;
  color:#94a3b8;
}

.alert{ border-radius:14px; }
</style>
</head>

<body>

<?php
  // ✅ Use your existing $logoUrl if you have it; otherwise default path
  $safeLogo = htmlspecialchars(($logoUrl ?? '/edenrms/assets/img/eden-logo.png'), ENT_QUOTES, 'UTF-8');
  $safeCookieUser = htmlspecialchars(($_COOKIE['eden_user'] ?? ''), ENT_QUOTES, 'UTF-8');
?>

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

   <div class="logo-area">
  <img class="logo" src="<?= $safeLogo ?>" alt="Eden Campus Logo"
       onerror="this.style.display='none'">

  <div>
    <div class="brand">EDEN CAMPUS</div>
    <div class="tag">Inspiring Growth • Building Success</div>
  </div>
</div>


    <h1>Sign in</h1>
    <div class="sub">Registration Management System</div>

    <?php if(!empty($err)): ?>
      <div class="alert alert-danger small py-2 mb-3"><?= htmlspecialchars($err, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <form id="loginForm" method="post" autocomplete="on">

      <div class="mb-3">
        <label>Email or Username</label>
        <input class="form-control" name="username" required
               value="<?= $safeCookieUser ?>"
               placeholder="Enter your email or username">
      </div>

      <div class="mb-2">
        <label>Password</label>

        <!-- ✅ password + eye toggle -->
        <div class="input-group">
          <input id="pwd" type="password" class="form-control" name="password" required
                 placeholder="Enter your password" autocomplete="current-password">
          <button id="togglePwd" class="btn btn-eye" type="button" aria-label="Show password" aria-pressed="false">
            <i class="bi bi-eye"></i>
          </button>
        </div>

        <!-- ✅ Caps lock warning -->
        <div id="capsWarn" class="caps-warn mt-2">
          <i class="bi bi-exclamation-triangle me-1"></i> Caps Lock is ON
        </div>
      </div>

      <div class="row-links">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" name="remember" id="rm">
          <label class="form-check-label small-link" for="rm">Remember me</label>
        </div>
        <a href="/edenrms/pages/forgot_password.php" class="small-link">Forgot password?</a>
      </div>

      <!-- ✅ Loading spinner button -->
      <button id="btnLogin" class="btn-login" type="submit">
        <span id="btnSpin" class="spinner-border spinner-border-sm" style="display:none;" aria-hidden="true"></span>
        <span id="btnText">Sign in</span>
      </button>

      <div class="footer">
        © <?= date('Y') ?> Eden Campus
      </div>

    </form>

  </div>
</div>

<script>
(() => {
  const form   = document.getElementById('loginForm');
  const pwd    = document.getElementById('pwd');
  const toggle = document.getElementById('togglePwd');
  const caps   = document.getElementById('capsWarn');

  const btn     = document.getElementById('btnLogin');
  const btnText = document.getElementById('btnText');
  const btnSpin = document.getElementById('btnSpin');

  // Caps Lock warning
  function updateCaps(e){
    const on = e.getModifierState && e.getModifierState('CapsLock');
    caps.style.display = on ? 'block' : 'none';
  }
  ['keydown','keyup'].forEach(ev => pwd.addEventListener(ev, updateCaps));
  pwd.addEventListener('blur', () => { caps.style.display = 'none'; });

  // Show/Hide password
  toggle.addEventListener('click', () => {
    const show = (pwd.type === 'password');
    pwd.type = show ? 'text' : 'password';
    toggle.setAttribute('aria-pressed', String(show));
    toggle.setAttribute('aria-label', show ? 'Hide password' : 'Show password');
    toggle.innerHTML = show ? '<i class="bi bi-eye-slash"></i>' : '<i class="bi bi-eye"></i>';
    pwd.focus();
  });

  // Loading spinner on submit
  form.addEventListener('submit', () => {
    // Browser validation should already block invalid submits
    if (typeof form.checkValidity === 'function' && !form.checkValidity()) return;

    btn.disabled = true;
    btn.setAttribute('aria-busy', 'true');
    btnSpin.style.display = 'inline-block';
    btnText.textContent = 'Signing in...';
  });
})();
</script>

</body>
</html>
