<?php

namespace App\Support;

use Exception;
use GdImage;
use Mike42\Escpos\EscposImage;

/**
 * Compatibilidad PHP 8+ (GdImage) para escpos-php 2.2.
 */
final class EscposGdImage extends EscposImage
{
    public function readImageFromGdResource(GdImage $im): void
    {
        if (! EscposImage::isGdLoaded()) {
            throw new Exception(__METHOD__." requires 'gd' extension.");
        }

        $imgHeight = imagesy($im);
        $imgWidth = imagesx($im);
        $imgData = str_repeat("\0", $imgHeight * $imgWidth);
        for ($y = 0; $y < $imgHeight; $y++) {
            for ($x = 0; $x < $imgWidth; $x++) {
                $cols = imagecolorsforindex($im, imagecolorat($im, $x, $y));
                $greyness = (int) (($cols['red'] + $cols['green'] + $cols['blue']) / 3) >> 7;
                $black = (1 - $greyness) >> ($cols['alpha'] >> 6);
                $imgData[$y * $imgWidth + $x] = $black;
            }
        }
        $this->setImgWidth($imgWidth);
        $this->setImgHeight($imgHeight);
        $this->setImgData($imgData);
    }

    public function loadFromPngBinary(string $png): bool
    {
        if ($png === '' || ! function_exists('imagecreatefromstring')) {
            return false;
        }

        $im = @imagecreatefromstring($png);
        if ($im === false) {
            return false;
        }

        $this->readImageFromGdResource($im);
        imagedestroy($im);

        return $this->getWidth() > 0 && $this->getHeight() > 0;
    }
}
