<?php
require 'config.php';
session_start();

$teacher_id = $_SESSION['teacher_id'] ?? null;
if (!$teacher_id) {
    echo "Unauthorized.";
    exit;
}

// Get filters
$session_id = $_GET['session_id'] ?? null;
$term_id    = $_GET['term_id'] ?? null;
$class_id   = $_GET['class_id'] ?? null;
$subject_id = $_GET['subject_id'] ?? null;
$type       = $_GET['type'] ?? null;

// Pagination params
$limit = 100; // questions per page
$page  = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

if (!$session_id || !$term_id || !$class_id || !$subject_id || !$type) {
    echo "<p class='text-gray-500'>Please select all filters to view questions.</p>";
    exit;
}

// Count total
$countStmt = $dbh->prepare("SELECT COUNT(*) FROM questions 
    WHERE teacher_id=:t AND session_id=:s AND term_id=:tm 
      AND student_class=:c AND subject_id=:sub AND type=:ty");
$countStmt->execute([
    ':t'=>$teacher_id, ':s'=>$session_id, ':tm'=>$term_id,
    ':c'=>$class_id, ':sub'=>$subject_id, ':ty'=>$type
]);
$total = $countStmt->fetchColumn();
$totalPages = ceil($total / $limit);

// Fetch limited set
$stmt = $dbh->prepare("SELECT * FROM questions 
    WHERE teacher_id=:t AND session_id=:s AND term_id=:tm 
      AND student_class=:c AND subject_id=:sub AND type=:ty
    ORDER BY id DESC LIMIT :lim OFFSET :off");
$stmt->bindValue(':t',$teacher_id);
$stmt->bindValue(':s',$session_id);
$stmt->bindValue(':tm',$term_id);
$stmt->bindValue(':c',$class_id);
$stmt->bindValue(':sub',$subject_id);
$stmt->bindValue(':ty',$type);
$stmt->bindValue(':lim',$limit,PDO::PARAM_INT);
$stmt->bindValue(':off',$offset,PDO::PARAM_INT);
$stmt->execute();
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$questions) {
    echo "<p class='text-gray-500'>No questions found.</p>";
    exit;
}
?>

<!-- Search & Filter -->
<div class="flex justify-between items-center mb-3">
  <input type="text" id="searchInput" placeholder="Search questions..." class="border p-2 rounded w-1/3">
  <select id="filterAnswer" class="border p-2 rounded">
    <option value="">Filter by Answer</option>
    <?php 
    $answers = array_unique(array_column($questions, 'correct_answer'));
    foreach($answers as $ans): if(!$ans) continue; ?>
      <option value="<?=htmlspecialchars($ans)?>"><?=htmlspecialchars($ans)?></option>
    <?php endforeach; ?>
  </select>
</div>

<table class="min-w-full border border-gray-200 text-sm" id="questionsTable">
  <thead class="bg-gray-100">
    <tr>
      <th class="border px-2 py-1">#</th>
      <th class="border px-2 py-1">Question</th>
      <?php if($type === 'objective'): ?>
        <th class="border px-2 py-1">Options</th>
      <?php endif; ?>
      <th class="border px-2 py-1">Answer</th>
      <th class="border px-2 py-1">Actions</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach($questions as $i=>$q): ?>
      <tr id="qrow<?=$q['id']?>" class="questionRow">
        <td class="border px-2 py-1"><?=($offset+$i+1)?></td>
        <td class="border px-2 py-1 questionText"><?=htmlspecialchars($q['question_text'])?></td>
        <?php if($type === 'objective'): ?>
          <td class="border px-2 py-1 optionsText"><?=htmlspecialchars($q['options'])?></td>
        <?php endif; ?>
        <td class="border px-2 py-1 answerText"><?=htmlspecialchars($q['correct_answer'])?></td>
        <td class="border px-2 py-1">
          <button class="bg-yellow-500 text-white px-2 py-1 rounded text-xs editBtn" 
                  data-id="<?=$q['id']?>" 
                  data-question="<?=htmlspecialchars($q['question_text'])?>"
                  data-answer="<?=htmlspecialchars($q['correct_answer'])?>"
                  data-options="<?=htmlspecialchars($q['options'])?>">Edit</button>
          <button class="bg-red-600 text-white px-2 py-1 rounded text-xs deleteBtn" data-id="<?=$q['id']?>">Delete</button>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<!-- Pagination -->
<div class="flex justify-between items-center mt-4">
  <button class="px-3 py-1 rounded bg-gray-200" id="prevPage" <?=($page<=1?"disabled":"")?>>Prev</button>
  <span>Page <?=$page?> of <?=$totalPages?></span>
  <button class="px-3 py-1 rounded bg-gray-200" id="nextPage" <?=($page>=$totalPages?"disabled":"")?>>Next</button>
</div>

<!-- Edit Modal same as before -->
<div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
  <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-lg">
    <h2 class="text-xl font-semibold mb-4">Edit Question</h2>
    <form id="editForm">
      <input type="hidden" id="edit_id" name="id">
      <div class="mb-3">
        <label class="block text-sm font-medium mb-1">Question</label>
        <textarea id="edit_question" name="question_text" class="w-full border rounded p-2"></textarea>
      </div>
      <div id="optionsGroup" class="mb-3 hidden">
        <label class="block text-sm font-medium mb-1">Options (comma separated)</label>
        <input type="text" id="edit_options" name="options" class="w-full border rounded p-2">
      </div>
      <div class="mb-3">
        <label class="block text-sm font-medium mb-1">Correct Answer</label>
        <input type="text" id="edit_answer" name="correct_answer" class="w-full border rounded p-2">
      </div>
      <div class="flex justify-end space-x-2">
        <button type="button" id="closeModal" class="px-4 py-2 rounded bg-gray-500 text-white">Cancel</button>
        <button type="submit" class="px-4 py-2 rounded bg-green-600 text-white">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
let qType = "<?=$type?>";
let currentPage = <?=$page?>;
let totalPages = <?=$totalPages?>;

// 🔍 Search + Filter
$("#searchInput, #filterAnswer").on("input change", function(){
  let keyword = $("#searchInput").val().toLowerCase();
  let filterAns = $("#filterAnswer").val().toLowerCase();

  $("#questionsTable tbody tr").each(function(){
    let qText = $(this).find(".questionText").text().toLowerCase();
    let ans = $(this).find(".answerText").text().toLowerCase();
    let matchSearch = !keyword || qText.includes(keyword);
    let matchFilter = !filterAns || ans === filterAns;
    $(this).toggle(matchSearch && matchFilter);
  });
});

// Pagination buttons
$("#prevPage").click(function(){
  if(currentPage>1) loadPage(currentPage-1);
});
$("#nextPage").click(function(){
  if(currentPage<totalPages) loadPage(currentPage+1);
});
function loadPage(p){
  let params = new URLSearchParams(window.location.search);
  params.set("page", p);
  $("#questionsTable").closest("div").load("view_questions.php?"+params.toString());
}

// Delete
$(".deleteBtn").click(function(){
  if(!confirm("Delete this question?")) return;
  let id = $(this).data("id");
  $.post("delete_question.php",{id:id},function(res){
    alert(res);
    if(res.includes("deleted")) $("#qrow"+id).fadeOut();
  });
});

// Edit modal open
$(".editBtn").click(function(){
  let id=$(this).data("id");
  let q=$(this).data("question");
  let ans=$(this).data("answer");
  let opts=$(this).data("options");
  $("#edit_id").val(id);
  $("#edit_question").val(q);
  $("#edit_answer").val(ans);
  if(qType==="objective"){
    $("#optionsGroup").show();
    $("#edit_options").val(opts);
  } else {
    $("#optionsGroup").hide();
    $("#edit_options").val("");
  }
  $("#editModal").removeClass("hidden").addClass("flex");
});

// Close modal
$("#closeModal").click(function(){
  $("#editModal").addClass("hidden").removeClass("flex");
});

// Save edit
$("#editForm").submit(function(e){
  e.preventDefault();
  $.post("update_question.php",$(this).serialize(),function(res){
    alert(res);
    if(res.includes("updated")){
      let id=$("#edit_id").val();
      $("#qrow"+id+" td:eq(1)").text($("#edit_question").val());
      if(qType==="objective"){
        $("#qrow"+id+" td:eq(2)").text($("#edit_options").val());
        $("#qrow"+id+" td:eq(3)").text($("#edit_answer").val());
      } else {
        $("#qrow"+id+" td:eq(2)").text($("#edit_answer").val());
      }
      $("#editModal").addClass("hidden").removeClass("flex");
    }
  });
});
</script>
