<?php
declare(strict_types=1);

/**
 * IMPORTER LIBRARY
 * - MUST NOT echo
 * - MUST NOT exit
 * - MUST NOT set headers
 * - MUST throw on failure
 */


/* =========================================================
   HELPERS (GUARDED)
   ========================================================= */

if (!function_exists('toUtf8')) {
    function toUtf8($value): string {
        $value = (string)$value;

        // If already valid UTF-8, return as-is
        if (mb_check_encoding($value, 'UTF-8')) {
            return $value;
        }

        // Attempt conversion from Windows-1252 / ISO-8859-1
        return mb_convert_encoding(
            $value,
            'UTF-8',
            'Windows-1252,ISO-8859-1,UTF-8'
        );
    }
}

if (!function_exists('fail')) {
    function fail(string $msg): never {
        throw new Exception($msg);
    }
}

if (!function_exists('boolVal')) {
    function boolVal($v): bool {
        return in_array(
            strtolower(trim((string)$v)),
            ['1', 'yes', 'true'],
            true
        );
    }
}

if (!function_exists('snake')) {
    function snake(string $text): string {
        $text = strtolower(trim($text));
        $text = preg_replace('/[^a-z0-9]+/', '_', $text);
        return trim($text, '_');
    }
}

/* =========================================================
   CONFIG
   ========================================================= */

$delimiter = ';'; // FIXED — no UI guessing

$baseDir = __DIR__;
$questionsPath  = $baseDir . '/MD_Template_Questions.csv';
$signaturesPath = $baseDir . '/MD_Template_Signatures.csv';

if (!file_exists($questionsPath)) {
    fail('MD_Template_Questions.csv not found');
}
if (!file_exists($signaturesPath)) {
    fail('MD_Template_Signatures.csv not found');
}

/* =========================================================
   PARSE QUESTIONS CSV
   ========================================================= */

$fh = fopen($questionsPath, 'r');
if (!$fh) {
    fail('Unable to open questions CSV');
}

/* --- headers --- */
$rawHeaders = fgetcsv($fh, 0, $delimiter);
if (!$rawHeaders) {
    fail('Questions CSV is empty');
}

$headers = array_map(function ($h) {
    return strtolower(trim(preg_replace('/\x{FEFF}/u', '', $h)));
}, $rawHeaders);


$sectionsMap = [];

/* --- rows --- */
while (($row = fgetcsv($fh, 0, $delimiter)) !== false) {
    if (count($row) !== count($headers)) {
        continue;
    }

    $data = array_combine($headers, array_map('toUtf8', $row));

    $section     = trim($data['section'] ?? '');
    $questionKey = trim($data['question_key'] ?? '');
    $label       = trim($data['label'] ?? '');
    $type        = trim($data['type'] ?? '');

    if ($section === '' || $questionKey === '' || $type === '') {
        continue;
    }

    if (!isset($sectionsMap[$section])) {
        $sectionsMap[$section] = [
            'id' => snake($section),
            'title' => $section,
            'questions' => []
        ];
    }

    $q = [
        'key' => $questionKey,
        'label' => $label,
        'type' => $type,
        'required' => boolVal($data['required'] ?? '0')
    ];

    if ($type === 'choice' || $type === 'yes_no') {
        $options = array_values(array_filter(
            array_map('trim', explode('|', $data['options'] ?? ''))
        ));

        if (!$options) {
            fail("Choice question missing options: {$questionKey}");
        }

        $q['options'] = $options;

        if (!empty($data['compliant_options'])) {
            $compliant = array_values(array_filter(
                array_map('trim', explode('|', $data['compliant_options']))
            ));

            foreach ($compliant as $c) {
                if (!in_array($c, $options, true)) {
                    fail("Compliant option '{$c}' not in options for '{$questionKey}'");
                }
            }

            $q['compliantOptions'] = $compliant;
            $q['requiresCommentOnDeviation'] =
                boolVal($data['deviation_requires_comment'] ?? '0');
            $q['requiresPhotoOnDeviation'] =
                boolVal($data['deviation_requires_photo'] ?? '0');
        }
    }

    $sectionsMap[$section]['questions'][] = $q;
}

fclose($fh);

/* --- VALIDATION (AFTER LOOP) --- */
if (empty($sectionsMap)) {
    fail('Template import failed: no sections parsed from CSV');
}

$sections = array_values($sectionsMap);

/* =========================================================
   PARSE SIGNATURES CSV
   ========================================================= */

$signatureRules = [
    'miner' => ['phase' => 'draft',  'required' => true,  'repeatable' => false],
    'assistant' => ['phase' => 'draft',  'required' => true,  'repeatable' => false],
    'team' => ['phase' => 'draft',  'required' => false, 'repeatable' => true],
    'shiftboss' => ['phase' => 'review', 'required' => true,  'repeatable' => false],
];

$fh = fopen($signaturesPath, 'r');
if (!$fh) {
    fail('Unable to open signatures CSV');
}

$rawHeaders = fgetcsv($fh, 0, $delimiter);
if (!$rawHeaders) {
    fail('Signatures CSV is empty');
}

$sigHeaders = array_map(function ($h) {
    return strtolower(trim(preg_replace('/\x{FEFF}/u', '', $h)));
    }, $rawHeaders
);

$signatures = [];
$seenRoles = [];

while (($row = fgetcsv($fh, 0, $delimiter)) !== false) {
    if (count($row) !== count($sigHeaders)) {
        continue;
    }

    $data = array_combine($sigHeaders, array_map('toUtf8', $row));

    $order = (int)($data['order'] ?? 0);
    $role  = trim($data['role'] ?? '');
    $label = trim($data['label'] ?? '');
    $phase = trim($data['phase'] ?? '');

    if ($order <= 0 || $role === '' || $label === '') {
        continue;
    }

    if (!isset($signatureRules[$role])) {
        fail("Unknown signature role: {$role}");
    }

    $rule = $signatureRules[$role];

    if ($phase !== $rule['phase']) {
        fail("Signature role '{$role}' must be in phase '{$rule['phase']}'");
    }

    if (!$rule['repeatable']) {
        if (isset($seenRoles[$role])) {
            fail("Signature role '{$role}' may not be repeated");
        }
        $seenRoles[$role] = true;
    }

    $signatures[] = [
        'order' => $order,
        'role' => $role,
        'label' => $label,
        'required' => $rule['required'],
        'repeatable' => $rule['repeatable'],
        'phase' => $phase
    ];
}

fclose($fh);

/* --- ensure required roles exist --- */
foreach ($signatureRules as $role => $rule) {
    if ($rule['required']) {
        $found = false;
        foreach ($signatures as $sig) {
            if ($sig['role'] === $role) {
                $found = true;
                break;
            }
        }
        if (!$found) {
            fail("Required signature missing: {$role}");
        }
    }
}

/* =========================================================
   FINAL TEMPLATE JSON
   ========================================================= */

$template = [
    'version' => '1.0',
    'sections' => $sections,
    'signatures' => [
        'minimumRequired' => 3,
        'items' => $signatures
    ]
];

$json = json_encode($template, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);

/* =========================================================
   STORE IN DATABASE
   ========================================================= */

require_once $baseDir . '/../../system/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

    $pdo->beginTransaction();

    $pdo->exec("UPDATE md_templates SET active = 0");

    $stmt = $pdo->query("
        SELECT MAX(CAST(version AS DECIMAL(10,2))) FROM md_templates
    ");
    $maxVersion = $stmt->fetchColumn();
    $newVersion = $maxVersion
        ? number_format(((float)$maxVersion + 0.1), 1)
        : '1.0';

    $stmt = $pdo->prepare("
        INSERT INTO md_templates (version, json_schema, active, created_at)
        VALUES (:version, :schema, 1, NOW())
    ");
    $stmt->execute([
        'version' => $newVersion,
        'schema' => $json
    ]);

    $pdo->commit();

    return [
        'version' => $newVersion,
        'sections' => count($sections),
        'signatures' => count($signatures)
    ];


/* =========================================================
   DONE
   ========================================================= */
   
