<?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();

ini_set('display_errors','0');
ini_set('log_errors','1');
error_reporting(E_ALL);

require_once __DIR__ . '/../../includes/db.php';

$db = null;

if (isset($conn) && $conn instanceof mysqli) {
  $db = $conn;
} elseif (isset($mysqli) && $mysqli instanceof mysqli) {
  $db = $mysqli;
}

if (!$db || $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>';
  exit;
}

$db->set_charset('utf8mb4');

/* ---------- Helper Functions ---------- */
if (!function_exists('h')) {
  function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
  }
}

if (!function_exists('pass_ok')) {
  function pass_ok(string $plain, string $stored): bool {
    $stored = trim($stored);

    if ($stored === '') {
      return false;
    }

    $info = password_get_info($stored);

    // bcrypt / argon hash support
    if (($info['algoName'] ?? 'unknown') !== 'unknown') {
      return password_verify($plain, $stored);
    }

    // plaintext password support
    return hash_equals($stored, $plain);
  }
}

/* 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/admin/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, role_code, branch_id, branch_ids, password_hash, plain_password, 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']) &&
  !hash_equals((string)($row['plain_password'] ?? ''), $pass)
) {
  $msg = 'Invalid password.';
    } else {
      // normalize role from your columns
      $role = strtolower((string)($row['role_slug'] ?: $row['role'] ?: 'coordinator'));
      if ($role === 'coordinator') $role = 'course_coordinator';

      /* branch scope */
$branch_ids = [];

if (!empty($row['branch_ids'])) {
  $decoded = json_decode((string)$row['branch_ids'], true);

  if (is_array($decoded)) {
    $branch_ids = array_values(array_filter(array_map('intval', $decoded)));
  } else {
    $branch_ids = array_values(array_filter(array_map('intval', explode(',', (string)$row['branch_ids']))));
  }
}

if (!$branch_ids && !empty($row['branch_id'])) {
  $branch_ids[] = (int)$row['branch_id'];
}

$_SESSION['role'] = $role;
$_SESSION['branch_ids'] = $branch_ids;

$_SESSION['user'] = [
  'id'         => (int)$row['id'],
  'username'   => $row['username'] ?? '',
  'name'       => $row['full_name'] ?: ($row['username'] ?? 'Coordinator'),
  'email'      => $row['email'] ?? '',
  'role'       => $role,
  'branch_id'  => $row['branch_id'] ?? null,
  'branch_ids' => implode(',', $branch_ids),
];
      session_regenerate_id(true);
      session_write_close();

      header('Location: /elms/admin/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/eden-student-wide.png" alt="Eden Campus">
        <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>
