<?php
session_start();
define('APP_RUNNING', true);

// Include core files
require_once '../lib/security.php';
require_once '../lib/draw.php';

// Set up canvas
$canvasWidth = isset($_GET['size']) ? (int)$_GET['size'] : 64;
$canvasHeight = 32;

// If a size string like "128x32" is passed, parse it
if (isset($_GET['size']) && strpos($_GET['size'], 'x') !== false) {
    list($width, $height) = explode('x', $_GET['size']);
    $canvasWidth = (int)$width;
    $canvasHeight = (int)$height;
}

$pixelData = array_fill(0, $canvasWidth * $canvasHeight, '#000000');
// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Get request data
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);

if (!$data || !isset($data['code'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid request data']);
    exit;
}

// Sanitize code
$code = $data['code'];

// Create a sandbox to execute the code
try {
    // Execute the code in a sandbox
    ob_start();
    eval($code);
    ob_end_clean();
    
    // Return the pixel data
    echo json_encode([
        'success' => true,
        'pixelData' => $pixelData
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>