<?php
/* EdenCampus — Coordinator Login (matches your SQL dump)
   - Uses table elms_users (username/email + password_hash)
   - Accepts plaintext (your current rows) or bcrypt/argon
   - On success -> /elms/coordinator/index.php
*/
declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

/* ===== 1) EDIT THESE 4 LINES TO YOUR HOSTING DB CREDENTIALS ===== */
$DB_HOST = 'localhost';                 // usually 'localhost'
$DB_USER = 'cpanelprefix_dbuser';       // <-- change
$DB_PASS = 'strong-password';           // <-- change
$DB_NAME = 'cpanelprefix_edencampus';   // <-- change (your DB name)
/* ================================================================= */

ini_set('display_errors','0'); ini_set('log_errors','1'); error_reporting(E_ALL);
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }

/* password check: plaintext or hash */
function pass_ok(string $input, string $stored): bool {
  if ($stored === '') return false;
  if ($stored === $input) return true;                          // plaintext (coord1 has this)
  $info = @password_get_info($stored);
  if (!empty($info['algo'])) return password_verify($input,$stored); // bcrypt/argon
  if (preg_match('/^[a-f0-9]{32}$/i',$stored)) return hash_equals(strtolower($stored), md5($input));
  return false;
}

/* connect (show real error if it fails) */
mysqli_report(MYSQLI_REPORT_OFF);
$db = @new mysqli($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
if ($db->connect_errno) {
  http_response_code(500);
  echo '<!doctype html><meta charset="utf-8"><style>body{font:14px system-ui;padding:20px}</style>';
  echo '<h3>Database connection failed</h3>';
  echo '<p><b>Error:</b> '.h($db->connect_error).'</p>';
  echo '<p>Fix the 4 credentials at the top of <code>login.php</code> to your cPanel MySQL user & DB.</p>';
  exit;
}
$db->set_charset('utf8mb4');

/* already logged in? */
$role_now = strtolower((string)($_SESSION['user']['role'] ?? $_SESSION['role'] ?? ''));
if (in_array($role_now, ['course_coordinator','coordinator','branch_admin','super_admin'], true)) {
  header('Location: /elms/coordinator/index.php'); exit;
}

/* handle submit */
$msg = '';
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $login = trim((string)($_POST['username'] ?? ''));
  $pass  = (string)($_POST['password'] ?? '');
  if ($login === '' || $pass === '') {
    $msg = 'Enter username/email and password.';
  } else {
    $sql = "SELECT id, username, email, full_name, role_slug, role, password_hash, is_active
            FROM elms_users
            WHERE is_active=1 AND (username=? OR email=?) LIMIT 1";
    if ($st = $db->prepare($sql)) {
      $st->bind_param('ss', $login, $login);
      $st->execute();
      $row = $st->get_result()->fetch_assoc();
      $st->close();
    } else { $row = null; }

    if (!$row) {
      $msg = 'User not found or inactive.';
    } elseif (!pass_ok($pass, (string)$row['password_hash'])) {
      $msg = 'Invalid password.';
    } else {
      // normalize role from your columns
      $role = strtolower((string)($row['role_slug'] ?: $row['role'] ?: 'coordinator'));
      if ($role === 'coordinator') $role = 'course_coordinator';

      $_SESSION['role'] = $role; // some pages read this directly
      $_SESSION['user'] = [
        'id'       => (int)$row['id'],
        'username' => $row['username'] ?? '',
        'name'     => $row['full_name'] ?: ($row['username'] ?? 'Coordinator'),
        'email'    => $row['email'] ?? '',
        'role'     => $role,
      ];
      session_regenerate_id(true);
      session_write_close();

      header('Location: /elms/coordinator/index.php'); exit;
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Eden Campus | Coordinator Login</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">
  <style>
    body{min-height:100vh;background:linear-gradient(135deg,#0E1B2A 0%,#13293D 55%,#1D3557 100%);}
    .auth-wrap{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:24px;}
    .card-auth{width:100%;max-width:440px;border:0;border-radius:18px;box-shadow:0 8px 30px rgba(0,0,0,.25);}
    .brand{display:flex;align-items:center;gap:12px;margin-bottom:18px;}
    .brand img{width:44px;height:44px;object-fit:contain;}
    .brand .t1{color:#0E1B2A;font-weight:800;letter-spacing:.3px;}
    .small-note{font-size:.9rem;color:#6c7a95;}
    .btn-brand{background:#1D9D84;border-color:#1D9D84;}
    .btn-brand:hover{background:#188a73;border-color:#188a73;}
    .link-light-muted{color:#bcd0ff;text-decoration:none;}
    .link-light-muted:hover{color:#fff;}
  </style>
</head>
<body>
<div class="auth-wrap">
  <div class="card card-auth">
    <div class="card-body p-4 p-md-5">
      <div class="brand">
        <img src="/elms/assets/brand/logo.png" alt="Eden">
        <div>
          <div class="t1">EDEN CAMPUS</div>
          <div class="small-note">Coordinator Portal</div>
        </div>
      </div>

      <?php if ($msg): ?><div class="alert alert-danger py-2"><?= h($msg) ?></div><?php endif; ?>

      <form method="post" action="">
        <div class="mb-3">
          <label class="form-label">Username / Email</label>
          <input type="text" name="username" class="form-control form-control-lg" required autofocus
                 value="<?= h($_POST['username'] ?? '') ?>">
        </div>
        <div class="mb-3">
          <label class="form-label">Password</label>
          <input type="password" name="password" class="form-control form-control-lg" required>
        </div>
        <div class="d-grid">
          <button type="submit" class="btn btn-brand btn-lg">Sign in</button>
        </div>
      </form>

      <div class="text-center mt-3">
        <a class="link-light-muted" href="/elms/admin/forgot.php">Forgot password?</a>
      </div>
    </div>
    <div class="card-footer text-center small text-muted py-3">
      © <?= date('Y') ?> Eden Campus — Coordinator Access Only
    </div>
  </div>
</div>
</body>
</html>
