<?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,
            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'
        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=risr_export_done_questions.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 = [];

// split stem into paragraphs (by blank lines)
if (!empty($stem)) {
    $stemParts = preg_split('/\n\s*\n/', $stem);

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

// add lead-in as final bold paragraph
if (!empty($leadIn)) {
    $paragraphs[] = "<p><strong>" . htmlspecialchars($leadIn) . "</strong></p>";
}

// join everything together
$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, [
        '',                         // Item ID
        'SBA',                      // Item type
        '',                         // Item number
        $q['title'] ?? '',          // Question title
        '1',                        // Version
        'Approved',                 // Status
        $questionText,              // Question text
        $q['tutor_comments'] ?? '', // Comments
        '',                         // Examiner notes (left blank for RISR)
        '1',                        // Item max score (export only)
        '---',                      // Resources (file names)
        $q['condition_name'] ?? '', // Core condition
        $q['presentation'] ?? '',   // Presentation
        $q['skill'] ?? '',          // Skill
        $q['specialty'] ?? '',      // Specialty
        $q['summative_formative'] ?? '', // Summative/Formative
	$q['year_level'] ?? '',          // Year
	date('Y'),                       // Year of Writing
        '',                         // <-->
        '',                         // Stem (left blank intentionally)
        '',                         // Stem comments
        '',                         // Role visibility
        '',                         // Marker notes
        'sba',                      // Type
        'default',                  // Answer ordering
        '',                         // Scoring method
        '',                         // Max responses
        '1',                        // Weight
        'False',                    // Mandatory criterion
        '0',                        // Levenshtein threshold
        '',                         // Number of lines
        '0',                        // Indentation level
        '1',                        // Maximum mark
        '60',                       // Angoff
        '',                         // Difficulty
        '',                         // Relevance
        'False',                    // Feedback visible to candidate?
        $optionA,                   // Available answers
        $optionB,                   // Available answers
        $optionC,                   // Available answers
        $optionD,                   // Available answers
        $optionE,                   // Available answers
        $derivedCorrectAnswer,      // Correct answer
        $q['correct_answer_letter'] ?? '' // Correct answer letter
    ]);
}

fclose($output);
exit;