<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
header('X-Content-Type-Options: nosniff');
if (!isset($_SESSION['user_id'])) { http_response_code(401); exit('Unauthorized'); }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('DB failed'); }
$jobId = (int) ($_GET['job_id'] ?? 0);
$stmt = $conn->prepare(
    "SELECT eq.*, s.subject_code
     FROM exam_questions eq
     LEFT JOIN subjects s ON s.id = eq.subject_id
     WHERE eq.generation_job_id = ? AND eq.created_by = ?
     ORDER BY eq.id ASC"
);
$stmt->bind_param('ii', $jobId, $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=\"questions_job' . $jobId . '.csv\"');
$out = fopen('php://output', 'wb');
fputcsv($out, ['subject_code','class_name','question_type','question','option_a','option_b','option_c','option_d','correct_answer','marks','difficulty','diagram_required','diagram_spec']);
while ($row = $result->fetch_assoc()) {
    fputcsv($out, [
        $row['subject_code'] ?? '',
        $row['class_name'] ?? '',
        $row['question_type'] ?? '',
        $row['question'] ?? '',
        $row['option_a'] ?? '',
        $row['option_b'] ?? '',
        $row['option_c'] ?? '',
        $row['option_d'] ?? '',
        $row['correct_answer'] ?? '',
        $row['marks'] ?? '',
        $row['difficulty'] ?? '',
        $row['diagram_required'] ?? 0,
        $row['diagram_spec'] ?? '',
    ]);
}
fclose($out);
$stmt->close();
