<?php
// teacher_load_questions_ajax.php
require 'config.php';
session_start();
if (!isset($_SESSION['teacher_id'])) { echo "Unauthorized"; exit; }

$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;
$qsearch = $_GET['qsearch'] ?? '';

$where = [];
$params = [];
if ($session_id) { $where[] = 'session_id = :s'; $params[':s']=$session_id; }
if ($term_id) { $where[] = 'term_id = :t'; $params[':t']=$term_id; }
if ($class_id) { $where[] = 'student_class = :c'; $params[':c']=$class_id; } // note: student_class stores class id or name depending on your schema
if ($subject_id) { $where[] = 'subject_id = :sub'; $params[':sub']=$subject_id; }
if ($type) { $where[] = '`type` = :type'; $params[':type']=$type; }
if ($qsearch) { $where[] = 'question_text LIKE :q'; $params[':q'] = '%'.$qsearch.'%'; }

$where_sql = $where ? 'WHERE '.implode(' AND ', $where) : '';

$sql = "SELECT id, question_text, `type`, options FROM questions $where_sql ORDER BY id DESC LIMIT 200";
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

echo "<div class='grid gap-2'>";
foreach($rows as $r){
    echo "<label class='inline-flex items-start p-2 border rounded bg-white'>
            <input type='checkbox' name='questions[]' value='".htmlspecialchars($r['id'])."' class='mt-1 mr-2'>
            <div><div class='text-sm font-medium'>".htmlspecialchars(substr($r['question_text'],0,150))."</div>
            <div class='text-xs text-gray-500'>Type: ".htmlspecialchars($r['type'])."</div></div>
          </label>";
}
echo "</div>";
