<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';

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

try {
    $user = require_auth($pdo);

    if (!in_array($user['role_key'] ?? '', ['super_admin', 'platform_admin'], true)) {
        throw new Exception('Access denied');
    }

    if (!isset($_FILES['questions'], $_FILES['signatures'])) {
        throw new Exception('Both questions and signatures CSV files are required');
    }

    $baseDir = __DIR__ . '/../md/templates';

    if (!move_uploaded_file($_FILES['questions']['tmp_name'], $baseDir . '/MD_Template_Questions.csv')) {
        throw new Exception('Failed to save questions CSV');
    }

    if (!move_uploaded_file($_FILES['signatures']['tmp_name'], $baseDir . '/MD_Template_Signatures.csv')) {
        throw new Exception('Failed to save signatures CSV');
    }

    // Import MUST return array or throw
    $result = require $baseDir . '/import_md_template.php';

    echo json_encode([
        'success' => true,
        'message' => 'Template imported and activated successfully',
        'version' => $result['version'],
    ]);

} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
    ]);
}
