<?php
// Prevent direct access
if (!defined('APP_RUNNING')) {
    header('HTTP/1.0 403 Forbidden');
    exit('Direct access is not allowed.');
}

// Include the original drawText function
require_once __DIR__ . '/../functions/fonts/drawBitmapText.php';

/**
 * Get all available bitmap fonts
 */
function getAvailableBitmapFonts() {
    $fontDir = __DIR__ . '/../functions/fonts/';
    $files = glob($fontDir . 'bitmap_*.php');
    $fonts = [];
    
    foreach ($files as $file) {
        $fontName = basename($file, '.php');
        $fonts[] = $fontName;
    }
    
    return $fonts;
}

/**
 * Wrapper to bridge the original drawText function with the platform
 */
function drawTextWrapper($x, $y, $text, $color, $font = 'bitmap_5x7', $justification = 'left') {
    global $pixelData, $canvasWidth, $canvasHeight;
    
    // Ensure the pixelData array has the correct size based on canvas dimensions
    if (count($pixelData) != $canvasWidth * $canvasHeight) {
        $pixelData = array_fill(0, $canvasWidth * $canvasHeight, '#000000');
    }
    
    // Create a GD image with the exact canvas dimensions
    $img = imagecreatetruecolor($canvasWidth, $canvasHeight);
    imagefill($img, 0, 0, imagecolorallocate($img, 0, 0, 0)); // Fill with black
    
    // Convert hex color to GD color
    if (strpos($color, '#') === 0) {
        $r = hexdec(substr($color, 1, 2));
        $g = hexdec(substr($color, 3, 2));
        $b = hexdec(substr($color, 5, 2));
        $gdColor = imagecolorallocate($img, $r, $g, $b);
    } else {
        $gdColor = imagecolorallocate($img, 255, 255, 255); // Default to white
    }
    
    // Use the full file path for the font to make sure it's found
    $fontPath = __DIR__ . '/../functions/fonts/' . $font;
    
    // Draw the text on the empty GD image
    drawBitmapText($img, $text, $x, $y, $justification, $gdColor, $fontPath);
    
    // Update the platform's pixel array from the GD image
    // This is a critical part - we need to ensure this is done correctly for all canvas sizes
    $affectedPixels = [];
    for ($py = 0; $py < $canvasHeight; $py++) {
        for ($px = 0; $px < $canvasWidth; $px++) {
            $gdColor = imagecolorat($img, $px, $py);
            if ($gdColor !== 0) { // If pixel was set (not black)
                $index = $py * $canvasWidth + $px;
                if ($index < count($pixelData)) { // Ensure we don't go out of bounds
                    $r = ($gdColor >> 16) & 0xFF;
                    $g = ($gdColor >> 8) & 0xFF;
                    $b = $gdColor & 0xFF;
                    $hexColor = sprintf("#%02x%02x%02x", $r, $g, $b);
                    $pixelData[$index] = $hexColor;
                    $affectedPixels[] = ['x' => $px, 'y' => $py, 'color' => $hexColor];
                }
            }
        }
    }
    
    // Clean up
    imagedestroy($img);
    
    return $affectedPixels;
}

// Create platform-compatible function with expected parameter order
function drawText($x, $y, $text, $color, $font = 'bitmap_5x7', $justification = 'left') {
    return drawTextWrapper($x, $y, $text, $color, $font, $justification);
}

/**
 * Get data from API
 */
function getData($url, $apiKey = null) {
    // For testing, return mock data
    logOperation('getData', [
        'url' => $url,
        'apiKey' => $apiKey ? '[REDACTED]' : null
    ]);
    
    return json_encode([
        'success' => true,
        'data' => [
            'value' => rand(0, 100),
            'timestamp' => time()
        ]
    ]);
}

/**
 * Set specific pixel
 */
function setPixel($x, $y, $color) {
    global $pixelData, $canvasWidth, $canvasHeight;
    
    // Validate inputs
    $x = intval($x);
    $y = intval($y);
    $color = validateColor($color);
    
    if ($x >= 0 && $x < $canvasWidth && $y >= 0 && $y < $canvasHeight) {
        $index = $y * $canvasWidth + $x;
        $pixelData[$index] = $color;
        return true;
    }
    
    return false;
}