<?php

namespace App\Support;

use Picqer\Barcode\BarcodeGeneratorPNG;
use Throwable;

/**
 * Código de barras embebido en PDF (data URI PNG).
 */
final class SeguimientoBarcode
{
    /**
     * @param  string  $payload  Texto a codificar (código QR/folio existente de la orden).
     * @return string data:image/png;base64,... o cadena vacía si falla.
     */
    public static function pngDataUri(string $payload): string
    {
        $binary = self::pngBinary($payload, 2, 52);

        return $binary !== null ? 'data:image/png;base64,'.base64_encode($binary) : '';
    }

    public static function pngBinary(string $payload, int $widthFactor = 2, int $height = 52): ?string
    {
        $payload = trim($payload);
        if ($payload === '') {
            return null;
        }

        try {
            $generator = new BarcodeGeneratorPNG();

            return $generator->getBarcode($payload, $generator::TYPE_CODE_128, $widthFactor, $height);
        } catch (Throwable) {
            return null;
        }
    }
}

