<?php
header('Content-Type: application/json; charset=UTF-8');
$root = rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/\\');
if ($root === '' || !file_exists($root . '/config.php')) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Tenant configuration could not be loaded.']);
    exit;
}
require_once $root . '/config.php';
$imageEngineUserType = strtolower((string)($_SESSION['usertype'] ?? ''));
$imageEngineAccess = (int)($_SESSION['access'] ?? 0);
$imageEngineCanSaveTemplates = $imageEngineUserType === 'admins'
    || $imageEngineAccess === 999
    || ($imageEngineUserType === 'surveyor' && $imageEngineAccess === 3);
if (!$imageEngineCanSaveTemplates) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'You do not have permission to save Image Engine templates.']);
    exit;
}
$input = json_decode((string)file_get_contents('php://input'), true);
$filename = preg_replace('/[^A-Za-z0-9 _\-.]/', '', basename((string)($input['filename'] ?? '')));
$data = $input['data'] ?? null;
if (!preg_match('/\.json$/i', $filename)) $filename .= '.json';
if ($filename === '.json' || !is_string($data) || strlen($data) > 2 * 1024 * 1024) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid template data.']);
    exit;
}
json_decode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Template data must be valid JSON.']);
    exit;
}
$templateDir = $root . '/images/lev_templates/';
if (!is_dir($templateDir) && !mkdir($templateDir, 0755, true)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Template storage is unavailable.']);
    exit;
}
if (file_put_contents($templateDir . $filename, $data, LOCK_EX) === false) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Template could not be saved.']);
    exit;
}
echo json_encode(['success' => true, 'message' => 'Template saved.', 'templateUrl' => rtrim(TENANT_URL, '/') . '/images/lev_templates/' . rawurlencode($filename)]);
