<?php
function drawBitmapText($image, $text, $x_start, $y_start, $justification, $color, $bitmapFileName) {
    // Ensure inputs are integers
    $x_start = (int)$x_start;
    $y_start = (int)$y_start;

    // Include the bitmap file dynamically
    $filePath = $bitmapFileName . '.php';
    if (file_exists($filePath)) {
        require_once $filePath;
    } else {
        error_log("File not found: " . $filePath);
        return;
    }

    $funcName = 'get' . ucfirst(basename($bitmapFileName));
    if (!function_exists($funcName)) {
        error_log("Function does not exist: " . $funcName);
        return;
    }

    $bitmaps = $funcName();

    // Calculate total width of the text to be drawn
    $totalWidth = 0;
    foreach (str_split($text) as $char) {
        if (isset($bitmaps[$char])) {
            $totalWidth += count($bitmaps[$char][0]) + 1;  // Add 1 for spacing
        }
    }
    $totalWidth -= 1;  // Remove extra space after last character

    // Adjust x_start based on justification
    if ($justification == 'center') {
        $x_start -= (int)($totalWidth / 2); // Explicitly cast the result to an integer
    } elseif ($justification == 'right') {
        $x_start -= $totalWidth; // Already an integer
    }

    // Ensure x_start is not negative
    $x_start = max(0, $x_start);

    // Draw the text using the bitmaps
    foreach (str_split($text) as $char) {
        if (!isset($bitmaps[$char])) continue;
        $bitmap = $bitmaps[$char];
        foreach ($bitmap as $rowIndex => $row) {
            foreach ($row as $colIndex => $pixel) {
                if ($pixel === 1) {
                    imagesetpixel($image, $x_start + $colIndex, $y_start + $rowIndex, $color);
                }
            }
        }
        $x_start += count($bitmap[0]) + 1;  // Advance x by the width of the character
    }
}
?>
