<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Milon\Barcode\DNS1D;
use Illuminate\Support\Facades\Response;

class BarcodeController extends Controller
{
    /**
     * Generate a barcode image.
     *
     * @param  string  $text
     * @return \Illuminate\Http\Response
     */
    public function generate($text)
    {
        try {
            $barcode = new DNS1D();
            // Generate barcode as SVG for better print quality.
            // Parameters: getBarcodeSVG($code, $type, $widthFactor, $height, $color)
            $svg = $barcode->getBarcodeSVG($text, 'C128', 2, 50, 'black');
            return Response::make($svg, 200, ['Content-Type' => 'image/svg+xml']);
        } catch (\Exception $e) {
            // Log the error and return a placeholder or error image if something goes wrong.
            \Log::error("Barcode generation failed for text: {$text}. Error: " . $e->getMessage());
            // You can return a 1x1 transparent pixel as a fallback
            $placeholder = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=');
            return Response::make($placeholder)->header('Content-Type', 'image/png');
        }
    }
}
