<?php

namespace App\Http\Controllers;

use App\Models\Bien;
use App\Services\AdministracionService;
use App\Services\AsignacionOperacionUtilityService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class AdministracionController extends Controller
{
    public function __construct(
        private readonly AdministracionService $administracionService,
        private readonly AsignacionOperacionUtilityService $barcodeUtilityService,
    ) {
    }

    public function index(): View
    {
        return view($this->administracionService->indexViewName());
    }

    public function barcodeGenerator(Request $request): View
    {
        $bienes = Bien::query()
            ->with('tipoInsumo:id,nombre')
            ->where('codigo', 'like', 'ABS%')
            ->orderBy('descripcion')
            ->get(['id', 'codigo', 'descripcion', 'tipo', 'unidad', 'peso']);

        $selectedBienId = (int) $request->integer('bien');
        $selectedBien = $selectedBienId > 0
            ? $bienes->firstWhere('id', $selectedBienId)
            : $bienes->first();

        $barcodeValue = $selectedBien?->codigo;

        return view('administracion.barcode-generator', [
            'bienes' => $bienes,
            'selectedBien' => $selectedBien,
            'barcodeValue' => $barcodeValue,
            'barcodeSvg' => $barcodeValue !== null ? $this->barcodeUtilityService->buildBarcodeSvg($barcodeValue) : null,
            'copias' => 8
        ]);
    }

    public function barcodeImage(Bien $bien): Response
    {
        abort_unless(str_starts_with((string) $bien->codigo, 'ABS'), 404);

        $barcodeBinary = $this->barcodeUtilityService->buildBarcodeBinary((string) $bien->codigo);

        abort_unless($barcodeBinary !== null, 404);

        return response($barcodeBinary, 200, [
            'Content-Type' => 'image/png',
            'Content-Disposition' => 'inline; filename="bien-' . $bien->id . '-barcode.png"',
        ]);
    }
}
