<?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 | EDEN ELMS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <base href="<?= esc($BASE_PATH) ?>/">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

  <style>
    *{box-sizing:border-box}
    body{
      min-height:100vh;
      margin:0;
      background:#f4f6f9;
      font-family:Arial,sans-serif;
      color:#111827;
    }
    .login-page{
      min-height:100vh;
      display:flex;
      align-items:center;
      justify-content:center;
      padding:28px;
    }
    .login-box{
      width:100%;
      max-width:860px;
      min-height:460px;
      background:#fff;
      border:1px solid #e5e7eb;
      border-radius:30px;
      overflow:hidden;
      display:grid;
      grid-template-columns:1fr 1fr;
      box-shadow:0 30px 90px rgba(15,23,42,.10);
    }
    .login-brand-side{
      background:#0D0B61;
      color:#fff;
      padding:48px 42px;
      display:flex;
      flex-direction:column;
      justify-content:center;
      align-items:center;
      text-align:center;
    }
    .login-brand-side img{
      width:150px;
      background:#fff;
      border-radius:18px;
      padding:12px;
      margin-bottom:32px;
    }
    .login-brand-side h1{
      font-size:42px;
      font-weight:900;
      letter-spacing:2px;
      margin:0 0 14px;
      color:#fff;
    }
    .login-brand-side p{
      font-size:16px;
      color:#f3f4f6;
      margin:0;
      line-height:1.7;
    }
    .login-form-side{
      padding:48px 42px;
      display:flex;
      flex-direction:column;
      justify-content:center;
    }
    .login-head span{
      display:inline-block;
      font-size:11px;
      font-weight:900;
      letter-spacing:1px;
      text-transform:uppercase;
      color:#6b7280;
      margin-bottom:10px;
    }
    .login-head h2{
      font-size:28px;
      font-weight:900;
      margin:0;
      color:#111827;
    }
    .login-head p{
      font-size:13px;
      color:#6b7280;
      margin:8px 0 26px;
    }
    .form-label{
      font-size:13px;
      font-weight:800;
      color:#111827;
      margin-bottom:8px;
    }
    .form-control{
      height:48px;
      border-radius:14px;
      border:1px solid #d9dee7;
      background:#fff;
      padding:10px 14px;
      font-size:14px;
      box-shadow:none!important;
    }
    .form-control:focus{
      border-color:#111827;
    }
    .login-btn{
      width:100%;
      height:48px;
      border:0;
      border-radius:14px;
      background:#0D0B61;
      color:#fff;
      font-size:14px;
      font-weight:900;
      margin-top:8px;
    }
    .login-btn:hover{background:#000}
    .alert{
      border-radius:14px;
      font-size:13px;
      margin-bottom:16px;
    }
    .login-footer{
      margin-top:24px;
      text-align:center;
      font-size:12px;
      color:#6b7280;
    }
    @media(max-width:768px){
      .login-box{
        grid-template-columns:1fr;
        max-width:430px;
      }
      .login-brand-side{
        padding:38px 28px;
      }
      .login-brand-side img{
        width:125px;
        margin-bottom:22px;
      }
      .login-brand-side h1{
        font-size:30px;
      }
      .login-form-side{
        padding:34px 28px;
      }
    }
  </style>
</head>
<body>

<div class="login-page">
  <div class="login-box">

    <div class="login-brand-side">
      <img src="/elms/includes/logo/edden_logo.jpg" alt="Eden Campus">
      <h1>EDEN ELMS</h1>
      <p>Lecturer Learning Management Portal</p>
    </div>

    <div class="login-form-side">
      <div class="login-head">
        <span>Lecturer Login</span>
        <h2>Welcome Back</h2>
        <p>Sign in to continue your session</p>
      </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; ?>

      <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="login-btn">Sign in</button>
      </form>

      <div class="login-footer">
        &copy; <?= date('Y') ?> Eden Campus ELMS
      </div>
    </div>

  </div>
</div>

</body>
</html>