<?php

function zpl_to_png($zpl, $dpi = 203) {

    $width  = intval(4 * $dpi); // 4 inches
    $height = intval(2 * $dpi); // 2 inches

    $im = imagecreatetruecolor($width, $height);

    $white = imagecolorallocate($im, 255,255,255);
    $black = imagecolorallocate($im, 0,0,0);
    imagefill($im, 0,0, $white);

    // Extremely simplified simulation:
    // 1. Extract all ^FO, ^A, ^FD commands
    // 2. Draw text in approximate positions
    // 3. barcode = simple black rectangle placeholder

    $lines = explode("^", $zpl);
    $x = 20; 
    $y = 20;

    foreach($lines as $cmd) {

        if (str_starts_with($cmd, "FO")) {
            $p = explode(",", substr($cmd, 2));
            $x = intval($p[0]);
            $y = intval($p[1]);
        }

        if (str_starts_with($cmd, "A0")) {
            // font size approx
            preg_match('/A0N,(\d+),(\d+)/', $cmd, $m);
            $fs = $m[1] ?? 30;
        }

        if (str_starts_with($cmd, "FD")) {
            $text = substr($cmd, 2);
            imagestring($im, 5, $x, $y, $text, $black);
            $y += 20;
        }

        if (str_starts_with($cmd, "BC")) {
            // draw fake barcode
            imagefilledrectangle($im, $x, $y, $x+($dpi*2), $y+($dpi*0.5), $black);
            $y += intval($dpi*0.6);
        }
    }

    ob_start();
    imagepng($im, null, 9);
    $png = ob_get_clean();

    imagedestroy($im);

    return $png;
}
