<?php

namespace Daniv04\HaciendaPackage\Services\Pdf;

use Daniv04\HaciendaPackage\Models\Receipt;
use Illuminate\Support\Facades\Log;

class PdfGeneratorService
{
    /**
     * Generate a PDF for the given Receipt and return raw bytes.
     *
     * @throws \RuntimeException if barryvdh/laravel-dompdf is not installed
     */
    public function generate(Receipt $receipt): string
    {
        if (!class_exists(\Barryvdh\DomPDF\Facade\Pdf::class)) {
            throw new \RuntimeException(
                'barryvdh/laravel-dompdf is required for PDF generation. ' .
                'Run: composer require barryvdh/laravel-dompdf'
            );
        }

        $receipt->loadMissing('payload');
        $payload = $receipt->payload->payload_json ?? [];

        $data = [
            'receipt'       => $receipt,
            'payload'       => $payload,
            'emissor'       => $payload['Emisor']         ?? [],
            'receptor'      => $payload['Receptor']       ?? [],
            'lines'         => $payload['DetalleServicio']['LineaDetalle'] ?? [],
            'summary'       => $payload['ResumenFactura'] ?? [],
            'encabezado'    => $payload['Encabezado']     ?? [],
            'documentLabel' => $this->resolveLabel($receipt->receipt_type),
        ];

        $pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView(
            'hacienda-package::invoices.invoice',
            $data
        );
        $pdf->setPaper('A4', 'portrait');

        return $pdf->output();
    }

    private function resolveLabel(string $type): string
    {
        return match ($type) {
            'FE'  => 'Factura Electrónica',
            'FEE' => 'Factura Electrónica de Exportación',
            'FEC' => 'Factura Electrónica de Compra',
            'TE'  => 'Tiquete Electrónico',
            'ND'  => 'Nota de Débito',
            'NC'  => 'Nota de Crédito',
            'REP' => 'Recibo Electrónico de Pago',
            'CA' => 'Confirmación de Comprobante Electrónico',
            'CAP' => 'Confirmación Parcial de Comprobante Electrónico',
            'CR' => 'Confirmación de Rechazo de Comprobante Electrónico',
            default => 'Comprobante Electrónico',
        };
    }
}
