<?php
header('Content-Type: application/json'); // Indicate JSON response

$baseDir = __DIR__;
$templateDir = $baseDir . '/templates/';
$response = ['success' => false, 'message' => 'An unknown error occurred.'];

// Ensure the templates directory exists
if (!is_dir($templateDir)) {
    // Attempt to create it (adjust permissions as needed)
    if (!mkdir($templateDir, 0755, true)) { // 0755 might need adjustment based on server config
         $response['message'] = 'Error: Templates directory does not exist and could not be created.';
         echo json_encode($response);
         exit;
    }
}

// Check if data is received via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    if (isset($input['filename']) && isset($input['data'])) {
        $filename = $input['filename'];
        $jsonData = $input['data']; // This should be the JSON *string* from Fabric.js

        // --- Security: Sanitize filename ---
        // 1. Remove directory separators
        $filename = preg_replace('/[^A-Za-z0-9 _\-\.]/', '', basename(str_replace(['/', '\\'], '', $filename)));
        // 3. Ensure it ends with .json (or add it)
        if (strtolower(substr($filename, -5)) !== '.json') {
            $filename .= '.json';
        }
        // 4. Basic check for invalid/empty filename
        if (empty($filename) || $filename === '.json') {
             $response['message'] = 'Invalid filename provided.';
             echo json_encode($response);
             exit;
        }
        // --- End Security ---

        $filePath = $templateDir . $filename;

        if (!is_string($jsonData) || strlen($jsonData) > 2 * 1024 * 1024 || json_decode($jsonData) === null && json_last_error() !== JSON_ERROR_NONE) {
            $response['message'] = 'Invalid or oversized template data.';
            http_response_code(400);
            echo json_encode($response);
            exit;
        }

        // Check if data is valid JSON (optional but good)
        // Note: FabricJS data is already JSON, but we receive it as a string usually
        // json_decode($jsonData); if (json_last_error() !== JSON_ERROR_NONE) { ... }

        // Attempt to save the file
        if (file_put_contents($filePath, $jsonData) !== false) {
            $response['success'] = true;
            $response['message'] = 'Template "' . htmlspecialchars($filename) . '" saved successfully.';
        } else {
            $response['message'] = 'Error: Could not write template file. Check server permissions.';
            // Log detailed error internally if possible: error_log("Failed to write to $filePath");
        }

    } else {
        $response['message'] = 'Error: Missing filename or data.';
    }
} else {
     $response['message'] = 'Error: Invalid request method.';
}

echo json_encode($response);
?>
