<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
    exit;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if ($data === null) {echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);exit;}

/*
// disable file upload in demo
$dir = __DIR__.'/storage/templates';
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}

$id = isset($data['id']) && $data['id'] ? preg_replace('/[^A-Za-z0-9\-_.]/', '_', $data['id']) : ('tpl-'.time());
$path = $dir.'/'.$id.'.json';
file_put_contents($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
 */
echo json_encode(['ok' => true, 'id' => $id, 'path' => 'api/storage/templates/'.basename($path)]);
