<?php
session_start();
require_once "../includes/db.php"; // defines $mysqli (and $conn alias)

// use one handle
$db = isset($mysqli) ? $mysqli : (isset($conn) ? $conn : null);
if (!$db) { die("DB connection missing"); }

$error = "";

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nic    = trim($_POST['nic_number'] ?? "");
    $pass   = trim($_POST['password'] ?? "");
    $course = trim($_POST['course_name'] ?? "");
    $unit   = trim($_POST['unit_exam'] ?? "");

    if ($nic === "" || $pass === "" || $course === "" || $unit === "") {
        $error = "Please fill all fields.";
    } else {
        $stmt = $db->prepare("SELECT * FROM students WHERE nic_number=? AND course_name=? AND unit_exam=? LIMIT 1");
        $stmt->bind_param("sss", $nic, $course, $unit);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && $res->num_rows === 1) {
            $stu = $res->fetch_assoc();
            if (password_verify($pass, $stu['password'])) {
                $_SESSION['student_id']  = (int)$stu['id'];
                $_SESSION['student_nic'] = $stu['nic_number'];
                $_SESSION['course_name'] = $stu['course_name'];
                $_SESSION['unit_exam']   = $stu['unit_exam'];
                unset($_SESSION['q_list'], $_SESSION['current_index'], $_SESSION['answers'], $_SESSION['exam_id']);
                header("Location: exam.php"); exit;
            } else {
                $error = "Incorrect password.";
            }
        } else {
            $error = "Student not found for this NIC / Course / Unit.";
        }
        $stmt->close();
    }
}

/* Load course list
   Prefer normalized `courses` table; fallback to `exams` if not present
*/
$hasCourses = $db->query("SHOW TABLES LIKE 'courses'");
if ($hasCourses && $hasCourses->num_rows > 0) {
    $courses = $db->query("SELECT course_name AS course_name FROM courses ORDER BY course_name ASC");
} else {
    $courses = $db->query("SELECT DISTINCT course_name FROM exams ORDER BY course_name ASC");
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Eden Campus Online Examinations Student Login</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    :root{
      --blue:#0b2c61;   /* dark blue */
      --blue2:#071f49;  /* deeper blue */
      --red:#e42424;    /* red accent */
      --ink:#0f172a;
    }
    body{
      min-height:100vh;
      background:
        radial-gradient(1200px 600px at -10% -10%, rgba(228,36,36,.08), transparent 60%),
        radial-gradient(900px 600px at 110% 10%, rgba(11,44,97,.12), transparent 60%),
        linear-gradient(180deg, #f4f6fb 0%, #eef2f9 100%);
      font-family: system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, "Helvetica Neue", Arial;
      display:flex; flex-direction:column;
    }
    .wrap{
      flex:1 0 auto;
      display:grid; place-items:center;
      padding: 24px 16px;
    }
    .brand{
      text-align:center; margin-bottom:18px;
    }
    .brand .logo{
      width:200px; height:auto; object-fit:contain; display:block; margin:0 auto 8px auto;
      filter: drop-shadow(0 4px 10px rgba(0,0,0,.2));
    }
    .brand .title{
      font-weight:800; letter-spacing:.3px; color:var(--blue2);
      font-size: clamp(1.25rem, 2.5vw, 1.8rem);
      text-transform: uppercase;
    }

    .card-neo{
      width:100%; max-width:520px;
      border:0; border-radius:16px; overflow:hidden;
      box-shadow:0 16px 36px rgba(15,23,42,.12);
      background:#fff;
    }
    .card-neo .card-header{
      background: linear-gradient(135deg, var(--blue), var(--blue2));
      color:#fff; text-align:center; font-weight:600;
    }
    .btn-theme{ background:var(--red); border-color:var(--red); color:#fff; }
    .btn-theme:hover{ background:#c71f1f; border-color:#c71f1f; }
    .small-hint{ color:#6b7280; }

    footer{
      flex-shrink:0;
      text-align:center; padding: 10px 12px; color:#475569;
      font-size:.92rem;
    }
  </style>
</head>
<body>

  <div class="wrap">
    <div class="container" style="max-width:560px">
      <!-- Logo + Heading -->
      <div class="brand">
        <img src="../assets/img/edencampus.png" class="logo" alt="Eden Campus">
        <div class="title">Eden Online Examinations</div>
      </div>

      <!-- Login Card -->
      <div class="card card-neo">
        <div class="card-header py-2">Student Login</div>
        <div class="card-body">
          <?php if (!empty($error)): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
          <?php endif; ?>

          <form method="post" autocomplete="off">
            <div class="mb-3">
              <label class="form-label">NIC Number</label>
              <input type="text" name="nic_number" class="form-control" required>
            </div>

            <div class="mb-3">
              <label class="form-label">Password</label>
              <div class="input-group">
                <input type="password" name="password" id="pw" class="form-control" required>
                <button type="button" class="btn btn-outline-secondary" id="togglePw">Show</button>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Course Name</label>
              <select name="course_name" id="course_name" class="form-select" required>
                <option value="">-- Select Course --</option>
                <?php if ($courses) while($row = $courses->fetch_assoc()): ?>
                  <option value="<?= htmlspecialchars($row['course_name']) ?>"><?= htmlspecialchars($row['course_name']) ?></option>
                <?php endwhile; ?>
              </select>
            </div>

            <div class="mb-3">
              <label class="form-label">Unit Exam</label>
              <select name="unit_exam" id="unit_exam" class="form-select" required>
                <option value="">-- Select Unit --</option>
              </select>
              <div class="form-text small-hint">Units will load after you select a course.</div>
            </div>

            <button class="btn btn-theme w-100">Login</button>
          </form>
        </div>
      </div>
    </div>
  </div>

  <footer>© 2025 Powered Eden campus Srilanka</footer>

  <script src="../assets/js/bootstrap.bundle.min.js"></script>
  <script>
    // Show / Hide password
    document.getElementById('togglePw').addEventListener('click', function(){
      const f = document.getElementById('pw');
      f.type = (f.type === 'password') ? 'text' : 'password';
      this.textContent = (f.type === 'password') ? 'Show' : 'Hide';
    });

    // When course changes, load units via get_units.php (same folder)
    $('#course_name').on('change', function(){
      const course = $(this).val();
      if (!course) {
        $('#unit_exam').html('<option value="">-- Select Unit --</option>');
        return;
      }
      $.get('get_units.php', { course_name: course }, function(html){
        $('#unit_exam').html(html);
      }).fail(function(xhr){
        alert('Failed to load units. (' + xhr.status + ')');
      });
    });
  </script>
</body>
</html>
