<?php

require_once __DIR__ . '/../config/database.php';

$workspace_id = $_GET['workspace_id'] ?? '';

if (empty($workspace_id)) {
    header('Content-Type: text/plain');
    echo 'Missing workspace_id.';
    exit;
}

$sql = "SELECT
            id,
            source_question_id,
            title,
            status,
            source_type,
            specialty,
            condition_name,
            presentation,
            skill,
            summative_formative,
            year_level,
            created_at,
            tutor_comments
        FROM questions
        WHERE workspace_id = :workspace_id
          AND source_type = 'variant'
        ORDER BY id ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    'workspace_id' => $workspace_id
]);

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=moderation_summary.csv');

$output = fopen('php://output', 'w');

fputcsv($output, [
    'generated_question_id',
    'source_row_number',
    'title',
    'status',
    'source_type',
    'specialty',
    'condition_name',
    'presentation',
    'skill',
    'summative_formative',
    'year_level',
    'created_at',
    'tutor_comments'
]);

foreach ($rows as $row) {
    fputcsv($output, [
        $row['id'] ?? '',
        $row['source_question_id'] ?? '',
        $row['title'] ?? '',
        $row['status'] ?? '',
        $row['source_type'] ?? '',
        $row['specialty'] ?? '',
        $row['condition_name'] ?? '',
        $row['presentation'] ?? '',
        $row['skill'] ?? '',
        $row['summative_formative'] ?? '',
        $row['year_level'] ?? '',
        $row['created_at'] ?? '',
        $row['tutor_comments'] ?? ''
    ]);
}

fclose($output);
exit;
