<?php

use PhpOffice\PhpSpreadsheet\IOFactory;

require_once __DIR__ . '/../vendor/autoload.php';

$inputFile = __DIR__ . '/md_template.xlsx';

$spreadsheet = IOFactory::load($inputFile);
$sheet = $spreadsheet->getSheetByName('Questions');

if (!$sheet) {
    throw new Exception("Sheet 'Questions' not found");
}

$rows = $sheet->toArray(null, true, true, true);

$questions = [];
$rowNum = 1;

foreach ($rows as $row) {
    // Skip header
    if ($rowNum++ === 1) {
        continue;
    }

    $key = trim($row['A'] ?? '');
    $label = trim($row['B'] ?? '');
    $optionsRaw = trim($row['C'] ?? '');
    $allowsDeviationRaw = trim($row['D'] ?? '');

    if ($key === '' || $label === '' || $optionsRaw === '') {
        continue; // skip incomplete rows
    }

    $options = array_map(
        fn($v) => trim($v),
        explode(',', $optionsRaw)
    );

    if (count($options) < 2) {
        throw new Exception("Question '$key' has fewer than 2 options");
    }

    $questions[] = [
        'key' => $key,
        'label' => $label,
        'options' => $options,
        'allowsDeviation' =>
            strtolower($allowsDeviationRaw) === 'true'
    ];
}

$template = [
    'version' => '1.0',
    'questions' => $questions
];

$json = json_encode($template, JSON_PRETTY_PRINT);

// === STORE IN DB ===
$stmt = $pdo->prepare("
    INSERT INTO md_templates (version, schema_json, is_active, created_at)
    VALUES (:version, :schema, 1, NOW())
");

$stmt->execute([
    'version' => '1.0',
    'schema' => $json
]);

echo "MD template imported successfully\n";
