<?php

declare(strict_types=1);

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

$workspace_id = trim((string) ($_GET['workspace_id'] ?? ''));
$source = strtolower(trim((string) ($_GET['source'] ?? 'main')));

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

$isVariantExport = $source === 'variant';

$sql = "SELECT
            stem,
            lead_in,
            option_a,
            option_b,
            option_c,
            option_d,
            option_e,
            correct_answer_letter
        FROM questions
        WHERE workspace_id = :workspace_id
          AND status = 'Done'";

if ($isVariantExport) {
    $sql .= " AND source_type = 'variant'";
    $documentTitle = 'MLA SBA Variants';
    $filename = 'mla-question-variants-forms.docx';
} else {
    $sql .= " AND (source_type IS NULL OR source_type = '' OR source_type = 'generated')";
    $documentTitle = 'MLA SBA Questions';
    $filename = 'microsoft_forms_import_template.docx';
}

$sql .= ' ORDER BY id ASC';

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

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

if ($questions === []) {
    header('Content-Type: text/plain; charset=utf-8');
    http_response_code(404);
    echo 'No approved questions available for export.';
    exit;
}

try {
    $docxBytes = docx_build_microsoft_forms_document($questions, $documentTitle);
} catch (Throwable $exception) {
    header('Content-Type: text/plain; charset=utf-8');
    http_response_code(500);
    echo 'DOCX export failed.';
    exit;
}

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . (string) strlen($docxBytes));
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');

echo $docxBytes;
