<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode([]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode([]); exit; }

$subjectId = (int) ($_POST['subject_id'] ?? 0);
$className = trim((string) ($_POST['class_name'] ?? ''));
$difficulty = trim((string) ($_POST['difficulty'] ?? ''));
$questionType = trim((string) ($_POST['question_type'] ?? ''));
$search = trim((string) ($_POST['search'] ?? ''));
$source = trim((string) ($_POST['source'] ?? ''));
$jobId = (int) ($_POST['job_id'] ?? $_GET['job_id'] ?? 0);

$sql = "SELECT eq.*, s.subject_name
        FROM exam_questions eq
        LEFT JOIN subjects s ON eq.subject_id = s.id
        WHERE 1=1";
$types = '';
$params = [];

foreach ([['eq.subject_id', $subjectId, 'i'], ['eq.class_name', $className, 's'], ['eq.difficulty', $difficulty, 's'], ['eq.question_type', $questionType, 's'], ['eq.generation_job_id', $jobId, 'i']] as [$field, $value, $type]) {
    if (($type === 'i' && (int) $value > 0) || ($type === 's' && $value !== '')) {
        $sql .= " AND {$field} = ?";
        $types .= $type;
        $params[] = $value;
    }
}

if ($search !== '') {
    $sql .= " AND eq.question LIKE ?";
    $types .= 's';
    $params[] = '%' . $search . '%';
}

if ($source === 'ai') {
    $sql .= " AND eq.ai_generated = 1";
} elseif ($source === 'manual') {
    $sql .= " AND eq.ai_generated = 0 AND eq.created_by IS NOT NULL";
} elseif ($source === 'imported') {
    $sql .= " AND eq.ai_generated = 0 AND eq.created_by IS NULL";
}

$sql .= " ORDER BY eq.created_at DESC";
$stmt = $conn->prepare($sql);
if ($types !== '') {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
while ($row = $result->fetch_assoc()) {
    $row['source'] = ((int) ($row['ai_generated'] ?? 0) === 1) ? 'AI' : (((int) ($row['created_by'] ?? 0) > 0) ? 'Manual' : 'Imported');
    $rows[] = $row;
}
$stmt->close();
echo json_encode($rows);
