<?php
require_once __DIR__ . "/auth.php";
require_role(['super','admin','staff']);
require_once __DIR__ . "/../includes/db.php";

$message = "";
$studentCopy = null;

/* ---------------------------------
   AJAX LOOKUP: studentss -> autofill
--------------------------------- */
if (isset($_GET['action']) && $_GET['action'] === 'lookup_student') {
  header('Content-Type: application/json; charset=utf-8');

  $reg = trim($_GET['course_reg_no'] ?? '');

  if ($reg === '') {
    echo json_encode(['ok' => false, 'error' => 'Missing register number']);
    exit;
  }

  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  $conn->set_charset('utf8mb4');

  $student = null;

  // 1) Direct search in studentss
  $st = $conn->prepare("
    SELECT id, full_name, nic_passport, center_reg_no, reference_no
    FROM studentss
    WHERE center_reg_no = ? OR reference_no = ?
    LIMIT 1
  ");
  $st->bind_param("ss", $reg, $reg);
  $st->execute();
  $student = $st->get_result()->fetch_assoc();
  $st->close();

  // 2) Fallback search via student_numbers
  if (!$student) {
    $st2 = $conn->prepare("
      SELECT s.id, s.full_name, s.nic_passport, sn.center_reg_no, sn.reference_no
      FROM student_numbers sn
      INNER JOIN studentss s ON s.id = sn.student_id
      WHERE sn.center_reg_no = ? OR sn.reference_no = ?
      LIMIT 1
    ");
    $st2->bind_param("ss", $reg, $reg);
    $st2->execute();
    $student = $st2->get_result()->fetch_assoc();
    $st2->close();
  }

  if ($student) {
    echo json_encode([
      'ok' => true,
      'student' => [
        'id'            => (int)$student['id'],
        'full_name'     => (string)($student['full_name'] ?? ''),
        'nic_passport'  => (string)($student['nic_passport'] ?? ''),
        'center_reg_no' => (string)($student['center_reg_no'] ?? ''),
        'reference_no'  => (string)($student['reference_no'] ?? '')
      ]
    ]);
  } else {
    echo json_encode(['ok' => false, 'error' => 'Student not found']);
  }
  exit;
}

function make_password(int $len = 10): string {
  $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789@#$%&*!?';
  $out = '';
  for ($i = 0; $i < $len; $i++) {
    $out .= $alphabet[random_int(0, strlen($alphabet) - 1)];
  }
  return $out;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $course_reg_no = trim($_POST['course_reg_no'] ?? '');
  $name          = trim($_POST['name'] ?? '');
  $nic           = trim($_POST['nic_number'] ?? '');
  $password      = trim($_POST['password'] ?? '');
  $course        = trim($_POST['course_name'] ?? '');
  $unit          = trim($_POST['unit_exam'] ?? '');
  $valid_date    = trim($_POST['password_valid_date'] ?? date('Y-m-d'));

  if ($password === '') {
    $password = make_password(10);
  }
  $hash = password_hash($password, PASSWORD_DEFAULT);

  if ($course_reg_no && $name && $nic && $course && $unit) {
    try {
      mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
      $conn->set_charset('utf8mb4');
      $conn->begin_transaction();

      $exam_id = 0;

      $stExam = $conn->prepare("
        SELECT id
        FROM exams
        WHERE course_name = ?
          AND unit_exam   = ?
        ORDER BY id DESC
        LIMIT 1
      ");
      $stExam->bind_param("ss", $course, $unit);
      $stExam->execute();
      $examRow = $stExam->get_result()->fetch_assoc();
      $stExam->close();

      if (!$examRow) {
        $stExam2 = $conn->prepare("
          SELECT id
          FROM exams
          WHERE course_name = ?
            AND title       = ?
          ORDER BY id DESC
          LIMIT 1
        ");
        $stExam2->bind_param("ss", $course, $unit);
        $stExam2->execute();
        $examRow = $stExam2->get_result()->fetch_assoc();
        $stExam2->close();
      }

      if ($examRow) {
        $exam_id = (int)$examRow['id'];
      }

      if ($exam_id <= 0) {
        throw new Exception("Matching exam not found for selected course and unit.");
      }

      $stmt = $conn->prepare("
        INSERT INTO students
        (course_reg_no, name, nic_number, password, password_plain, password_valid_date, course_name, unit_exam, created_at)
        VALUES (?,?,?,?,?,?,?,?,NOW())
      ");
      $stmt->bind_param("ssssssss", $course_reg_no, $name, $nic, $hash, $password, $valid_date, $course, $unit);
      $stmt->execute();
      $stmt->close();

      $examStudentId = (int)$conn->insert_id;

      $attempt_no = 1;
      $stAttempt = $conn->prepare("
        SELECT COALESCE(MAX(attempt_no), 0) + 1 AS next_attempt
        FROM student_exams
        WHERE student_id=? AND exam_id=?
      ");
      $stAttempt->bind_param("ii", $examStudentId, $exam_id);
      $stAttempt->execute();
      $attemptRow = $stAttempt->get_result()->fetch_assoc();
      $stAttempt->close();

      if ($attemptRow) {
        $attempt_no = (int)($attemptRow['next_attempt'] ?? 1);
        if ($attempt_no <= 0) $attempt_no = 1;
      }

      $created_at = $valid_date . ' ' . date('H:i:s');
      $stSE = $conn->prepare("
        INSERT INTO student_exams
        (student_id, exam_id, attempt_no, created_at)
        VALUES (?,?,?,?)
      ");
      $stSE->bind_param("iiis", $examStudentId, $exam_id, $attempt_no, $created_at);
      $stSE->execute();
      $stSE->close();

      $conn->commit();

      $message = "<div class='alert alert-success mb-3 animate__animated animate__fadeInDown'>Student created and exam sitting assigned successfully.</div>";
      $studentCopy = compact('course_reg_no','name','nic','password','valid_date','course','unit');

    } catch (Throwable $e) {
      @ $conn->rollback();
      $message = "<div class='alert alert-danger mb-3 animate__animated animate__shakeX'>Error: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "</div>";
    }
  } else {
    $message = "<div class='alert alert-danger mb-3 animate__animated animate__shakeX'>All fields are required.</div>";
  }
}

$courses_rs = $conn->query("SELECT DISTINCT course_name AS name FROM exams ORDER BY name ASC");
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Exam Student Registration • Eden Campus</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">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet"/>
  <style>
    body{
      background: linear-gradient(135deg,#0b2c61,#5a2bb5);
      min-height:100vh; display:flex; flex-direction:column;
    }
    .header-bar{
      background: linear-gradient(90deg,#0b2c61,#5a2bb5);
      color:#fff; padding:14px 20px;
      display:flex; align-items:center; justify-content:center;
      box-shadow:0 4px 12px rgba(0,0,0,.3);
    }
    .header-bar img{ height:50px; margin-right:12px; }
    .header-bar h3{ margin:0; font-weight:700; }

    .card-custom{
      max-width:950px; margin:40px auto; border-radius:16px;
      background: rgba(255,255,255,0.15);
      backdrop-filter: blur(12px);
      color:#fff;
      box-shadow:0 8px 25px rgba(0,0,0,.3);
      padding:25px;
      animation: fadeInUp 1s ease;
    }

    .form-label{ font-weight:600; }
    .form-control, .form-select{
      background: rgba(255,255,255,0.9);
      border-radius:8px;
    }

    .btn-theme{
      background:linear-gradient(45deg,#e42424,#f85f0f);
      border:0; color:#fff; font-weight:600;
      border-radius:25px; padding:12px 30px;
      box-shadow:0 5px 15px rgba(0,0,0,.3);
      transition:.3s;
    }
    .btn-theme:hover{ transform:scale(1.05); }

    #printArea{ font-size:15px; }
    #printArea h5{ font-weight:700; text-align:center; margin-bottom:20px; }
    #printArea table th{ background:#f5f5f5; width:40%; }
    #printArea table td{ background:#fff; }

    @media print {
      body * { visibility:hidden; }
      #printArea, #printArea * { visibility:visible; }
      #printArea{ position:absolute; left:0; top:0; width:100%; }
    }
  </style>
</head>
<body>

<div class="header-bar">
  <img src="../assets/img/edencampus.png" alt="Eden Campus">
  <h3>Eden Campus Online Examination - Exam Student Registration</h3>
</div>

<div class="container">
  <div class="card card-custom animate__animated animate__fadeIn">
    <?= $message ?>
    <form method="post" class="row g-3" id="studentForm">
      <div class="col-md-6">
        <label class="form-label">Course Register Number</label>
        <input name="course_reg_no" id="course_reg_no" class="form-control" autocomplete="off" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">Full Name</label>
        <input name="name" id="name" class="form-control" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">NIC / Passport</label>
        <input name="nic_number" id="nic_number" class="form-control" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">Password</label>
        <input name="password" type="text" class="form-control" placeholder="Leave blank for auto-generate">
      </div>
      <div class="col-md-6">
        <label class="form-label">Password Valid Date</label>
        <input type="date" name="password_valid_date" class="form-control" value="<?= date('Y-m-d') ?>">
      </div>
      <div class="col-md-6">
        <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_rs) while($cr=$courses_rs->fetch_assoc()): ?>
            <option value="<?= htmlspecialchars($cr['name']) ?>"><?= htmlspecialchars($cr['name']) ?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col-md-6">
        <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>
      <div class="col-12 text-center">
        <button class="btn btn-theme">Create Student</button>
      </div>
    </form>
  </div>
</div>

<div class="modal fade" id="studentCopyModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content" id="printArea">
      <div class="modal-header">
        <img src="../assets/img/edencampus.png" style="height:50px" class="me-2">
        <h5 class="modal-title">Eden Campus Online Examination - Exam Student Registration</h5>
      </div>
      <div class="modal-body">
        <table class="table table-bordered">
          <tr><th>Course Reg. No</th><td id="copy_reg"></td></tr>
          <tr><th>Full Name</th><td id="copy_name"></td></tr>
          <tr><th>NIC / Passport</th><td id="copy_nic"></td></tr>
          <tr><th>Password</th><td id="copy_pw"></td></tr>
          <tr><th>Password Valid Date</th><td id="copy_valid"></td></tr>
          <tr><th>Course Name</th><td id="copy_course"></td></tr>
          <tr><th>Unit Exam</th><td id="copy_unit"></td></tr>
        </table>
        <div class="mt-4 text-end">
          <p><strong>Authorized Signature: ____________________</strong></p>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button class="btn btn-info text-white" onclick="copySlip()">Copy</button>
        <button class="btn btn-success" onclick="window.print()">Print Slip</button>
      </div>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
let lookupTimer = null;
let activeLookupRequest = null;

function clearStudentFields() {
  $('#name').val('');
  $('#nic_number').val('');
}

function lookupStudent(reg) {
  if (activeLookupRequest && activeLookupRequest.readyState !== 4) {
    activeLookupRequest.abort();
  }

  activeLookupRequest = $.ajax({
    url: window.location.pathname,
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: {
      action: 'lookup_student',
      course_reg_no: reg,
      _t: Date.now()
    },
    success: function(res) {
      const currentReg = $('#course_reg_no').val().trim();

      if (currentReg !== reg) return;

      if (res && res.ok && res.student) {
        $('#name').val(res.student.full_name || '');
        $('#nic_number').val(res.student.nic_passport || '');
      } else {
        clearStudentFields();
      }
    },
    error: function(xhr, status) {
      if (status !== 'abort') {
        clearStudentFields();
      }
    }
  });
}

$('#course_reg_no').on('input keyup change paste', function() {
  const reg = $(this).val().trim();

  clearTimeout(lookupTimer);

  if (reg === '') {
    if (activeLookupRequest && activeLookupRequest.readyState !== 4) {
      activeLookupRequest.abort();
    }
    clearStudentFields();
    return;
  }

  lookupTimer = setTimeout(function() {
    lookupStudent(reg);
  }, 200);
});

$('#course_name').on('change', function(){
  $.get('get_units.php', { course_name: $(this).val() }, function(html){
    $('#unit_exam').html(html);
  });
});

function copySlip(){
  const details =
    `*Eden Campus - Examination Login Credentials*\n\n` +
    `*Course Reg. No:* ${document.getElementById('copy_reg').textContent}\n` +
    `*Full Name:* ${document.getElementById('copy_name').textContent}\n` +
    `*NIC / Passport:* ${document.getElementById('copy_nic').textContent}\n` +
    `*Password:* ${document.getElementById('copy_pw').textContent}\n` +
    `*Valid Until:* ${document.getElementById('copy_valid').textContent}\n` +
    `*Course Name:* ${document.getElementById('copy_course').textContent}\n` +
    `*Unit Exam:* ${document.getElementById('copy_unit').textContent}\n\n` +
    `All the best for your examination`;

  navigator.clipboard.writeText(details).then(() => {
    alert("Slip details copied (ready to paste in WhatsApp).");
  });
}
</script>

<?php if ($studentCopy): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  document.getElementById('copy_reg').textContent = <?= json_encode($studentCopy['course_reg_no']) ?>;
  document.getElementById('copy_name').textContent = <?= json_encode($studentCopy['name']) ?>;
  document.getElementById('copy_nic').textContent = <?= json_encode($studentCopy['nic']) ?>;
  document.getElementById('copy_pw').textContent = <?= json_encode($studentCopy['password']) ?>;
  document.getElementById('copy_valid').textContent = <?= json_encode($studentCopy['valid_date']) ?>;
  document.getElementById('copy_course').textContent = <?= json_encode($studentCopy['course']) ?>;
  document.getElementById('copy_unit').textContent = <?= json_encode($studentCopy['unit']) ?>;
  var myModal = new bootstrap.Modal(document.getElementById('studentCopyModal'));
  myModal.show();
});
</script>
<?php endif; ?>

</body>
</html>