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

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

function processDrawTextCall($matches) {
    $x = $matches[1];
    $y = $matches[2];
    $text = $matches[3];

    // Process Color Parameter - Extract RGB values from hex
    $colorParam = $matches[4];  // Process Color Parameter - Extract RGB values from hex
    $colorParam = trim($colorParam, "'\"");  // Remove quotes if they exist

    // Check if it's a hex color or a reference to a predefined color
    if (strpos($colorParam, '#') === 0) {
        // It's a hex color like "#00FF00"
        $hexColor = ltrim($colorParam, '#'); // Remove '#' if present

        // Validate hex color format
        if (preg_match('/^[0-9A-Fa-f]{6}$/', $hexColor)) {
            // Convert to RGB values
            $r = hexdec(substr($hexColor, 0, 2));
            $g = hexdec(substr($hexColor, 2, 2));
            $b = hexdec(substr($hexColor, 4, 2));
            $color = "imagecolorallocate(\$image, $r, $g, $b)";
        } else {
            // Invalid hex color, use white as fallback
            $color = "\$white";
        }
    } elseif (strpos($colorParam, '$') === 0) {
        // It's a variable reference like $white, $red, etc.
        $color = $colorParam;
    } else {
        // It might be a variable name without the $
        $color = '$' . $colorParam;
    }
    
    // Handle optional parameters
    $font = isset($matches[5]) ? $matches[5] : "'bitmap_5x7'";
    $justification = isset($matches[6]) ? $matches[6] : "'left'";

    // Process font parameter to ensure proper format
    // Remove surrounding quotes if present
    $fontStr = trim($font, "'\"");
    if (strpos($fontStr, 'bitmap_') !== 0) { $fontStr = 'bitmap_' . $fontStr; } // Check if it has bitmap_ prefix, if not, add it
    if (substr($fontStr, -4) === '.php') { $fontStr = substr($fontStr, 0, -4); } // Remove .php suffix if present
    $font = "'" . $fontStr . "'"; // Re-add quotes
    
    // Build the new function call with the proper parameter order
    // Original format: drawText($image, $text, $x_pos, $y_pos, 'justification', $color, $fontFiles . 'bitmap_file_name')
    return "drawText(\$image, $text, $x, $y, $justification, $color, \$fontFiles . $font)";
};

// 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['title']) || !isset($data['mode'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid request data']);
    exit;
}

// Sanitize inputs
$title = sanitizeInput($data['title']);
$mode = $data['mode'] === 'no-code' ? 'no-code' : 'low-code';

// Create username_appTitle.php file
$username = isset($_SESSION['username']) ? $_SESSION['username'] : 'guest';
$fileName = $username . '_' . preg_replace('/[^a-zA-Z0-9_-]/', '', $title) . '.php';

// Directory to save the file
$directory = '../apps/' . ($data['visibility'] === 'private' ? 'private' : 'public');

// Ensure directory exists
if (!is_dir($directory)) {
    mkdir($directory, 0755, true);
}

$filePath = $directory . '/' . $fileName;

if (!isset($data['code'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Code is required for low-code mode']);
    exit;
}

// Add wrapper code - Follow exact format specified
$fileContent = "<?php\n\n";
$fileContent .= "error_reporting(E_ALL & ~E_DEPRECATED);\n";
$fileContent .= "ini_set('display_errors', 1);\n";
$fileContent .= "ini_set('display_startup_errors', 1);\n";
$fileContent .= "error_reporting(E_ALL);\n";
$fileContent .= "require_once \$_SERVER['DOCUMENT_ROOT'] . '/config.php';\n";
$fileContent .= "require_once \$_SERVER['DOCUMENT_ROOT'] . '/helperFunctions/RLE.php'; // include RLE function\n";
$fileContent .= "require_once \$_SERVER['DOCUMENT_ROOT'] . '/helperFunctions/RLEbinary.php'; // include RLE function\n";
$fileContent .= "require_once \$_SERVER['DOCUMENT_ROOT'] . '/helperFunctions/image_to_rgb565.php'; // OG RGB 565 Function\n";
$fileContent .= "require_once \$_SERVER['DOCUMENT_ROOT'] . '/helperFunctions/image_to_rgb565_json.php'; // JSON OUTPUT RGB 565\n";
$fileContent .= "require_once \$_SERVER['DOCUMENT_ROOT'] . '/helperFunctions/image_to_rgb565_json_RLE.php'; // RLE 565 Output function\n\n";

// RLE Flag configuration
$fileContent .= "// RLE Flag set in config\n";
$fileContent .= "global \$runRLE; // needs definition in every functions its used as global so the pointer works to the config file.\n";
$fileContent .= "global \$runRLEbinary;\n\n";

// Directory setup for output and fonts
$fileContent .= "\$output_dir = \$_SERVER['DOCUMENT_ROOT'] . \"/GDN/App_Output/BIN/customFcn\"; // Output directory\n";
$fileContent .= "\$fontFiles = \$_SERVER['DOCUMENT_ROOT'] . '/GDN/functions/fonts/';\n";
$fileContent .= "require \$_SERVER['DOCUMENT_ROOT'] . '/GDN/functions/fonts/drawText.php'; // drawText()\n\n";

$fileContent .= "// Generated app: $title\n";
$fileContent .= "// Created by: $username\n";
$fileContent .= "// Created at: " . date('Y-m-d H:i:s') . "\n";


// Create the file content
if ($mode === 'low-code') {

    
    $code = $data['code'];
    
    $fileContent .= "// Execution Interval: " . (isset($data['executionTime']) ? (int)$data['executionTime'] : 5) . " minutes\n\n";
    // Canvas size from body data-canvas-size attribute
    $canvasWidth = 64;
    $canvasHeight = 32;
    
    if (isset($data['canvasSize'])) {
        list($width, $height) = explode('x', $data['canvasSize']);
        $canvasWidth = (int)$width;
        $canvasHeight = (int)$height;
    } elseif (isset($_GET['size'])) {
        list($width, $height) = explode('x', $_GET['size']);
        $canvasWidth = (int)$width;
        $canvasHeight = (int)$height;
    }
    
    // Start of user code section
    $fileContent .= "// ----- USER CODE SECTION BEGIN -----\n\n";
    
    // Add base canvas setup if not included in user code
    if (strpos($code, 'imagecreatetruecolor') === false) {
        $fileContent .= "// Initialize canvas and colors\n";
        $fileContent .= "\$width = $canvasWidth;\n";
        $fileContent .= "\$height = $canvasHeight;\n";
        $fileContent .= "\$image = imagecreatetruecolor(\$width, \$height);\n";
        $fileContent .= "\$black = imagecolorallocate(\$image, 0, 0, 0);\n";
        $fileContent .= "\$white = imagecolorallocate(\$image, 255, 255, 255);\n";
        $fileContent .= "\$red = imagecolorallocate(\$image, 255, 0, 0);\n";
        $fileContent .= "\$green = imagecolorallocate(\$image, 0, 255, 0);\n";
        $fileContent .= "\$blue = imagecolorallocate(\$image, 0, 0, 255);\n";
        $fileContent .= "\$cyan = imagecolorallocate(\$image, 0, 255, 255);\n";
        $fileContent .= "\$yellow = imagecolorallocate(\$image, 255, 255, 0);\n";
        $fileContent .= "\$magenta = imagecolorallocate(\$image, 255, 0, 255);\n\n";
        $fileContent .= "// Fill background with black\n";
        $fileContent .= "imagefill(\$image, 0, 0, \$black);\n\n";
    }
        
    // Process the user's PHP code, removing any PHP tags
    $processedCode = $code;
    $processedCode = str_replace(['<?php', '?>'], '', $processedCode);

    // THIS HIJACKS CANVAS DRAW TEXT AND TRANSLATES TO THE DRAWTEXT(BITMAP) CUSTOM FUNCTION
    // Use regex to find and replace drawText function calls with the correct parameter order
    $pattern = '/drawText\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*([^,]+)\s*,\s*([^,]+)(?:\s*,\s*([^,]+))?(?:\s*,\s*([^,)]+))?\s*\)/';

    $processedCode = preg_replace_callback($pattern, 'processDrawTextCall', $processedCode);

    // Add user code
    $fileContent .= $processedCode . "\n\n";
    $fileContent .= "// ----- USER CODE SECTION END -----\n\n";




} else if ($mode === 'no-code') {
    // No-code mode
    $inputs = $data['inputs'] ?? [];
    
    $fileContent .= "// Execution Interval: " . (isset($data['executionTime']) ? (int)$data['executionTime'] : 5) . " minutes\n\n";
    
    // Canvas size from body data-canvas-size attribute
    $canvasWidth = 64;
    $canvasHeight = 32;
    
    // Check all possible ways the canvas size might be provided
    if (isset($data['canvas_size'])) {
        list($width, $height) = explode('x', $data['canvas_size']);
        $canvasWidth = (int)$width;
        $canvasHeight = (int)$height;
    } elseif (isset($data['canvasSize'])) {
        list($width, $height) = explode('x', $data['canvasSize']);
        $canvasWidth = (int)$width;
        $canvasHeight = (int)$height;
    } elseif (isset($_POST['canvas_size'])) {
        list($width, $height) = explode('x', $_POST['canvas_size']);
        $canvasWidth = (int)$width;
        $canvasHeight = (int)$height;
    } elseif (isset($_GET['size'])) {
        list($width, $height) = explode('x', $_GET['size']);
        $canvasWidth = (int)$width;
        $canvasHeight = (int)$height;
    }

    // Basic canvas setup
    $fileContent .= "// Initialize canvas with dimensions: {$canvasWidth}x{$canvasHeight}\n";
    $fileContent .= "\$width = $canvasWidth;\n";
    $fileContent .= "\$height = $canvasHeight;\n";
    $fileContent .= "\$image = imagecreatetruecolor(\$width, \$height);\n";
    $fileContent .= "\$black = imagecolorallocate(\$image, 0, 0, 0);\n";
    $fileContent .= "\$white = imagecolorallocate(\$image, 255, 255, 255);\n";
    $fileContent .= "\$red = imagecolorallocate(\$image, 255, 0, 0);\n";
    $fileContent .= "\$green = imagecolorallocate(\$image, 0, 255, 0);\n";
    $fileContent .= "\$blue = imagecolorallocate(\$image, 0, 0, 255);\n";
    $fileContent .= "\$cyan = imagecolorallocate(\$image, 0, 255, 255);\n";
    $fileContent .= "\$yellow = imagecolorallocate(\$image, 255, 255, 0);\n";
    $fileContent .= "\$magenta = imagecolorallocate(\$image, 255, 0, 255);\n\n";
    $fileContent .= "imagefill(\$image, 0, 0, \$black);\n\n";
    
    // Add user inputs as variables
    $fileContent .= "// ----- USER CODE SECTION BEGIN -----\n\n";
    foreach ($inputs as $key => $value) {
        if ($value) {
            $fileContent .= "\${$key} = " . var_export($value, true) . ";\n";
        }
    }
    $fileContent .= "\n";
    
    // Process the provided code from workflow
    if (isset($data['code']) && !empty($data['code'])) {
        $fileContent .= "// Generated code from workflow blocks\n";
        // Process drawText calls in the workflow-generated code
        $pattern = '/drawText\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*([^,]+)\s*,\s*([^,]+)(?:\s*,\s*([^,]+))?(?:\s*,\s*([^,)]+))?\s*\)/';
        $processedWorkflowCode = preg_replace_callback($pattern, 'processDrawTextCall', $data['code']);
        $fileContent .= $processedWorkflowCode . " \n\n";
    } else {
        // Fallback sample code
        $fileContent .= "// Default sample code (no blocks in workflow)\n";
        $fileContent .= "\$bitmapFileName = \$fontFiles . 'bitmap_4x5';\n";
        $sampleText = [
            ['text' => 'Unknown Input:', 'color' => '$white', 'y' => 5],
            ['text' => 'Generated with GLANCE', 'color' => '$cyan', 'y' => 15],
            ['text' => 'No-Code Interface', 'color' => '$green', 'y' => 25]
        ];
        
        foreach ($sampleText as $index => $item) {
            $fileContent .= "drawText(\$image, '{$item['text']}', \$width/2, {$item['y']}, 'center', {$item['color']}, \$bitmapFileName);\n";
        }
        $fileContent .= "\n";
    }


    $fileContent .= "// ----- USER CODE SECTION ENDS -----\n\n";

}

$fileContent .= "// Function to set a single pixel\n";
$fileContent .= "function setPixel(\$x, \$y, \$color) {\n";
$fileContent .= "    global \$image;\n";
$fileContent .= "    // Convert hex color to GD color if needed\n";
$fileContent .= "    if (strpos(\$color, '#') === 0) {\n";
$fileContent .= "        \$hex = ltrim(\$color, '#');\n";
$fileContent .= "        \$r = hexdec(substr(\$hex, 0, 2));\n";
$fileContent .= "        \$g = hexdec(substr(\$hex, 2, 2));\n";
$fileContent .= "        \$b = hexdec(substr(\$hex, 4, 2));\n";
$fileContent .= "        \$gdColor = imagecolorallocate(\$image, \$r, \$g, \$b);\n";
$fileContent .= "    } else {\n";
$fileContent .= "        \$gdColor = \$color; // Assume it's already a GD color\n";
$fileContent .= "    }\n";
$fileContent .= "    imagesetpixel(\$image, \$x, \$y, \$gdColor);\n";
$fileContent .= "}\n\n";

// Add an option to save debug image
$fileContent .= "\n// Save debug image if flag is enabled\n";
$fileContent .= "\$saveImageFlag = true; // Set to true to save a debug PNG of the LED panel\n";
$fileContent .= "if (\$saveImageFlag) {\n";
$fileContent .= "    \$debug_dir = \$_SERVER['DOCUMENT_ROOT'] . '/GDN/debug_images';\n";
$fileContent .= "    if (!is_dir(\$debug_dir)) {\n";
$fileContent .= "        mkdir(\$debug_dir, 0755, true);\n";
$fileContent .= "    }\n";
$fileContent .= "    \$image_file_path = \$debug_dir . '/" . $title . ".png';\n";
$fileContent .= "    imagepng(\$image, \$image_file_path);\n";
$fileContent .= "    echo \"<br>Debug image saved to: \$image_file_path\";\n";
$fileContent .= "}\n";

// Output generation section for no-code mode
$fileContent .= "\$output_file_path = \$output_dir . '/" . $title . "';\n\n";

$fileContent .= "if(!\$runRLEbinary){\n\n";
$fileContent .= "    if(\$runRLE){\n";
$fileContent .= "        \$json_output = image_to_rgb565_json_RLE(\$image, '', '');\n";
$fileContent .= "    } else {\n";
$fileContent .= "        \$json_output = image_to_rgb565_json(\$image);\n";
$fileContent .= "    }\n";
$fileContent .= "    file_put_contents(\$output_file_path . '.json', \$json_output); // Make sure to use the full path\n";
$fileContent .= "    \n";
$fileContent .= "    // Echo out the JSON content\n";
$fileContent .= "    // echo \"New JSON Data:\\n\";\n";
$fileContent .= "    echo json_encode(json_decode(\$json_output), JSON_PRETTY_PRINT);\n";
$fileContent .= "    \n";
$fileContent .= "} else {\n";
$fileContent .= "    \$image_data = image_to_rgb565(\$image);\n";
$fileContent .= "    \$bin_file_path = \$output_file_path . '.bin'; // Use the provided directory path\n\n";
$fileContent .= "    // Generate RLE Binary\n";
$fileContent .= "    \$filename = compressAndSaveImageData(\$image_data, \$bin_file_path);\n";
$fileContent .= "    if (\$filename) {\n";
$fileContent .= "        echo \"File saved successfully: \$bin_file_path\";\n";
$fileContent .= "    } else {\n";
$fileContent .= "        echo \"Failed to save file.\";\n";
$fileContent .= "    }\n";
$fileContent .= "}\n";
$fileContent .= "imagedestroy(\$image);\n\n";

$fileContent .= "\$db = null;\n\n";
$fileContent .= "?>";

// Save the file
if (file_put_contents($filePath, $fileContent)) {
    echo json_encode([
        'success' => true,
        'message' => 'Application saved successfully',
        'fileName' => $fileName
    ]);
} else {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to save application'
    ]);
}
?>

