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

$baseDir = __DIR__;
$imageDir = $baseDir . '/images/';
$response = ['success' => false, 'message' => 'An unknown error occurred saving the image.'];

// Ensure the images directory exists and is writable
if (!is_dir($imageDir)) {
    // Attempt to create it recursively with appropriate permissions (adjust 0755 if needed)
    if (!mkdir($imageDir, 0755, true)) {
         $response['message'] = 'Error: Images directory does not exist and could not be created.';
         http_response_code(500); // Server error
         echo json_encode($response);
         exit;
    }
}
if (!is_writable($imageDir)){
    $response['message'] = 'Error: Images directory is not writable by the server.';
    // You might want to log this error on the server for diagnostics
    // error_log("PHP script cannot write to directory: " . $imageDir);
    http_response_code(500); // Server error
    echo json_encode($response);
    exit;
}


// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    // Check if required data is present
    if (isset($input['filename']) && isset($input['imageDataUrl'])) {
        $filename = $input['filename'];
        $imageDataUrl = $input['imageDataUrl']; // Expecting data:image/png;base64,....

        // --- Security: Basic Filename Sanitization ---
        // Remove potentially harmful characters and directory separators
        $filename = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $filename); // Allow letters, numbers, underscore, hyphen, dot
        $filename = basename($filename); // Prevent path traversal

        // Validate extension and ensure it's not empty
        $allowedExtensions = ['png', 'jpeg', 'jpg', 'gif', 'webp'];
        $fileExtension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        if (empty($filename) || $filename === '.' || $filename === '..') {
             $response['message'] = 'Invalid filename provided.';
             http_response_code(400); // Bad request
             echo json_encode($response);
             exit;
        }
        if (!in_array($fileExtension, $allowedExtensions)) {
             // Optionally add a default extension if missing or invalid
             $filename .= '.png';
             // Or reject:
             // $response['message'] = 'Invalid file extension. Allowed: ' . implode(', ', $allowedExtensions);
             // http_response_code(400); // Bad request
             // echo json_encode($response);
             // exit;
        }
        // --- End Security ---

        $filePath = $imageDir . $filename;

        // Decode the Base64 Data URL
        // Example: data:image/png;base64,iVBORw0KGgoAAA...
        if (preg_match('/^data:image\/(png|jpeg|jpg|gif|webp);base64,/', $imageDataUrl, $type)) {
            $encodedData = substr($imageDataUrl, strpos($imageDataUrl, ',') + 1);
            $decodedData = base64_decode($encodedData, true);

            if ($decodedData === false || strlen($decodedData) === 0 || strlen($decodedData) > 15 * 1024 * 1024) {
                $response['message'] = 'Error: Failed to decode base64 image data.';
                 http_response_code(400); // Bad request
            } else {
                // Attempt to save the file
                if (file_put_contents($filePath, $decodedData) !== false) {
                    $response['success'] = true;
                    $response['message'] = 'Image "' . htmlspecialchars($filename) . '" saved successfully.';
                    // Optional: Return the relative path or URL if needed by the client
                    $response['filepath'] = 'images/' . rawurlencode($filename);
                } else {
                    $response['message'] = 'Error: Could not write image file on server. Check permissions for images directory.';
                    // error_log("Failed to write image to $filePath"); // Log server-side for debugging
                    http_response_code(500); // Server error
                }
            }
        } else {
             $response['message'] = 'Error: Invalid image data URL format provided.';
             http_response_code(400); // Bad request
        }

    } else {
        $response['message'] = 'Error: Missing filename or image data in request.';
        http_response_code(400); // Bad request
    }
} else {
     $response['message'] = 'Error: Invalid request method. Use POST.';
     http_response_code(405); // Method Not Allowed
}

echo json_encode($response);
?>
