<?php

declare(strict_types=1);

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

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

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

$sql = "SELECT
            id,
            title,
            stem,
            lead_in,
            option_a,
            option_b,
            option_c,
            option_d,
            option_e,
            correct_answer_letter,
            correct_answer,
            justification,
            status,
            condition_name,
            presentation,
            skill,
            specialty,
            summative_formative,
            year_level,
            tutor_comments
        FROM questions
        WHERE workspace_id = :workspace_id
          AND status = 'Done'
          AND source_type = 'variant'
        ORDER BY id ASC";

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

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

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

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

fputcsv($output, [
    'Item ID',
    'Item type',
    'Item number',
    'Question title',
    'Version',
    'Status',
    'Question text',
    'Comments',
    'Examiner notes',
    'Item max score (export only)',
    'Resources (file names)',
    'Core condition',
    'Presentation',
    'Skill',
    'Specialty',
    'Summative/Formative',
    'Year',
    'Year of Writing',
    '<-->',
    'Stem',
    'Stem comments',
    'Role visibility',
    'Marker notes',
    'Type',
    'Answer ordering',
    'Scoring method',
    'Max responses',
    'Weight',
    'Mandatory criterion',
    'Levenshtein threshold',
    'Number of lines',
    'Indentation level',
    'Maximum mark',
    'Angoff',
    'Difficulty',
    'Relevance',
    'Feedback visible to candidate?',
    'Available answers',
    'Available answers',
    'Available answers',
    'Available answers',
    'Available answers',
    'Correct answer',
    'Correct answer letter',
]);

foreach ($questions as $q) {
    $stem = trim($q['stem'] ?? '');
    $leadIn = trim($q['lead_in'] ?? '');

    $paragraphs = [];

    if ($stem !== '') {
        $stemParts = preg_split('/\n\s*\n/', $stem);

        foreach ($stemParts as $part) {
            $part = trim($part);
            if ($part !== '') {
                $paragraphs[] = '<p>' . htmlspecialchars($part) . '</p>';
            }
        }
    }

    if ($leadIn !== '') {
        $paragraphs[] = '<p><strong>' . htmlspecialchars($leadIn) . '</strong></p>';
    }

    $questionText = implode("\n", $paragraphs);

    $optionA = ($q['option_a'] ?? '') . ($q['correct_answer_letter'] === 'A' ? ';1.00' : ';0.00');
    $optionB = ($q['option_b'] ?? '') . ($q['correct_answer_letter'] === 'B' ? ';1.00' : ';0.00');
    $optionC = ($q['option_c'] ?? '') . ($q['correct_answer_letter'] === 'C' ? ';1.00' : ';0.00');
    $optionD = ($q['option_d'] ?? '') . ($q['correct_answer_letter'] === 'D' ? ';1.00' : ';0.00');
    $optionE = ($q['option_e'] ?? '') . ($q['correct_answer_letter'] === 'E' ? ';1.00' : ';0.00');
    $derivedCorrectAnswer = '';

    switch ($q['correct_answer_letter'] ?? '') {
        case 'A':
            $derivedCorrectAnswer = $q['option_a'] ?? '';
            break;
        case 'B':
            $derivedCorrectAnswer = $q['option_b'] ?? '';
            break;
        case 'C':
            $derivedCorrectAnswer = $q['option_c'] ?? '';
            break;
        case 'D':
            $derivedCorrectAnswer = $q['option_d'] ?? '';
            break;
        case 'E':
            $derivedCorrectAnswer = $q['option_e'] ?? '';
            break;
    }

    fputcsv($output, [
        '',
        'SBA',
        '',
        $q['title'] ?? '',
        '1',
        'Approved',
        $questionText,
        $q['tutor_comments'] ?? '',
        '',
        '1',
        '---',
        $q['condition_name'] ?? '',
        $q['presentation'] ?? '',
        $q['skill'] ?? '',
        $q['specialty'] ?? '',
        $q['summative_formative'] ?? '',
        $q['year_level'] ?? '',
        date('Y'),
        '',
        '',
        '',
        '',
        '',
        'sba',
        'default',
        '',
        '',
        '1',
        'False',
        '0',
        '',
        '0',
        '1',
        '60',
        '',
        '',
        'False',
        $optionA,
        $optionB,
        $optionC,
        $optionD,
        $optionE,
        $derivedCorrectAnswer,
        $q['correct_answer_letter'] ?? '',
    ]);
}

fclose($output);
exit;
