<?php
// /elms/lecturer/login.php — robust lecturer login (no redirect loops)
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

/* ------------ PATH/URL HELPERS (AVOID RELATIVE REDIRECTS) ------------ */
$BASE_PATH = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/elms/lecturer/login.php'), '/'); // e.g. /elms/lecturer
$ABS_LOGIN = $BASE_PATH . '/login.php';
$ABS_DASH  = $BASE_PATH . '/dashboard.php';

// Build absolute URL (path under same host)
function go_abs($path) {
  global $BASE_PATH;
  if ($path === '' || $path[0] !== '/') $path = $BASE_PATH . '/' . ltrim($path, '/');
  header('Location: ' . $path, true, 302);
  exit;
}

// Normalize any bad URLs like /login.php/anything → /login.php
if (preg_match('#/login\.php/.*#', $_SERVER['REQUEST_URI'] ?? '')) {
  go_abs('login.php');
}

/* ------------------------- DATABASE (SOFT) -------------------------- */
$mysqli = null;
// Preferred: your existing connection file
if (@is_file(__DIR__ . '/../includes/db.php')) {
  @include __DIR__ . '/../includes/db.php'; // should define $mysqli
}
if (!($mysqli instanceof mysqli) || $mysqli->connect_errno) {
  // Fallback (won't crash if credentials differ)
  mysqli_report(MYSQLI_REPORT_OFF);
  $mysqli = @new mysqli("localhost","root","","edencamp_edencampus");
  if ($mysqli && !$mysqli->connect_errno) { $mysqli->set_charset('utf8mb4'); }
}

/* ------------------------- UTILITIES -------------------------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }

/* fetch lecturer by username or email (role must be lecturer & active) */
function fetch_lecturer_by_login(mysqli $db, string $login): ?array {
  $sql = "SELECT id, username, email, full_name, password_hash, is_active, role, role_code, role_slug
          FROM elms_users
          WHERE (username = ? OR email = ?)
            AND is_active = 1
            AND (LOWER(role_code)='lecturer' OR LOWER(role)='lecturer' OR LOWER(role_slug)='lecturer')
          LIMIT 1";
  $st = $db->prepare($sql);
  if (!$st) return null;
  $st->bind_param('ss', $login, $login);
  $st->execute();
  $row = $st->get_result()->fetch_assoc();
  $st->close();
  return $row ?: null;
}

/* Accept plain text (legacy), bcrypt, md5, sha1 */
function password_ok(string $input, string $stored): bool {
  $input  = (string)$input;
  $stored = (string)$stored;

  if ($stored === $input) return true; // plain
  if (strlen($stored) >= 20 && password_get_info($stored)['algo'] !== 0) {
    if (password_verify($input, $stored)) return true; // bcrypt/argon
  }
  if (preg_match('/^[a-f0-9]{32}$/i', $stored) && md5($input) === strtolower($stored)) return true;  // md5
  if (preg_match('/^[a-f0-9]{40}$/i', $stored) && sha1($input) === strtolower($stored)) return true; // sha1
  return false;
}

/* ----------------------- ALREADY LOGGED IN? ----------------------- */
if (!empty($_SESSION['lecturer_id']) || (!empty($_SESSION['user_role']) && $_SESSION['user_role']==='lecturer')) {
  go_abs('dashboard.php'); // absolute, no loop
}

/* ----------------------------- POST ----------------------------- */
$msg = '';
$db_warning = '';
if (!($mysqli instanceof mysqli) || $mysqli->connect_errno) {
  $db_warning = 'Database connection not available; login will fail until it is fixed.';
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $login = trim($_POST['login'] ?? '');
  $pass  = (string)($_POST['password'] ?? '');

  if (!($mysqli instanceof mysqli) || $mysqli->connect_errno) {
    $msg = 'Temporary database problem. Please try again later.';
  } else {
    $row = $login !== '' ? fetch_lecturer_by_login($mysqli, $login) : null;

    if (!$row) {
      $msg = 'User not found or not active.';
    } elseif (!password_ok($pass, (string)$row['password_hash'])) {
      $msg = 'Invalid password.';
    } else {
      // set session (cover common auth checks in other pages)
      $_SESSION['lecturer_id']   = (int)$row['id'];
      $_SESSION['lecturer_name'] = $row['full_name'] ?: ($row['username'] ?? 'Lecturer');
      $_SESSION['user_role']     = 'lecturer';
      $_SESSION['role']          = 'lecturer';
      $_SESSION['user'] = [
        'id'   => (int)$row['id'],
        'user' => $row['username'] ?? $row['email'],
        'name' => $row['full_name'] ?: ($row['username'] ?? 'Lecturer'),
        'role' => 'lecturer',
      ];
      session_regenerate_id(true);

      // redirect ABSOLUTELY (prevents /login.php/dashboard.php)
      go_abs('dashboard.php');
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Lecturer Login</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Optional: base so all relative links resolve to /elms/lecturer/ (not /login.php/...) -->
  <base href="<?= esc($BASE_PATH) ?>/">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body{background:#f7f9fc}
    .card{border:1px solid #e8eef6;border-radius:12px;box-shadow:0 10px 30px rgba(18,38,63,.05)}
  </style>
</head>
<body>
  <div class="container py-5">
    <div class="row justify-content-center">
      <div class="col-sm-10 col-md-6 col-lg-4">
        <div class="text-center mb-3">
          <div class="h4 mb-0">Lecturer Login</div>
          <div class="text-muted small">Sign in to continue</div>
        </div>

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

        <div class="card">
          <div class="card-body">
            <form method="post" autocomplete="off">
              <div class="mb-3">
                <label class="form-label">Username or Email</label>
                <input class="form-control" name="login" required autofocus>
              </div>
              <div class="mb-3">
                <label class="form-label">Password</label>
                <input class="form-control" type="password" name="password" required>
              </div>
              <button class="btn btn-primary w-100">Sign in</button>
            </form>
          </div>
        </div>

        <div class="text-center mt-3">
          <small class="text-muted">© <?= date('Y') ?> EdenCampus</small>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
