<!DOCTYPE html>
<html lang="{{ str_replace('_','-',app()->getLocale()) }}">

    {{-- Control Variables --}}
    @php
      // Imports
        use Carbon\Carbon;
        use App\Helpers\Database\SatCatalogsHelper;

        use App\Helpers\Support\PdfResourcesHelper;
        use App\Helpers\Support\TaxCertificateHelper;

        use App\Helpers\Formats\FormatCurrencyHelper;
        use App\Helpers\Formats\QuantityConverterHelper;

        use App\Enums\Invoicing\BillableService;
        use App\Helpers\Formats\TextTransformHelper;

      // Variables
        // Classes
        $contrast_color = PdfResourcesHelper::getTextContrastColor($invoice->taxFormat->base_color ?? "#0D6889");

        // Header
        $tax_folio = $invoice->sat_uuid ?? "0000XXXX-00XX-00XX-00XX-000XXX"; //TODO
        $cds_issuer = TaxCertificateHelper::serialHexToSatCertificateNumber($issuer->cer_serial_number);
        $emission_date = Carbon::parse($invoice->date)->format('d/m/Y H:i:s');
        $certification_date = Carbon::parse($invoice->certification_date ?? "2099-01-01")->format('d/m/Y H:i:s');

        $serie_folio = ($invoice->taxFormat->serie ?? $invoice->invoice_type)."-X";
            if (!in_array(null, [$invoice->system_service_id, $invoice->system_service_type], true)) {
                $label = BillableService::labelFrom($invoice->system_service_type);

                if ($label)
                    $serie_folio .= " | ".$label." #{$invoice->system_service_id}";
            }
    @endphp

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>{{ $title }}</title>

    @include('invoicing.invoices.pdf.resources.invoice-styles')
</head>

<body>
    {{-- Watermark --}}
    <div class="watermark">PREVIEW</div>

    {{-- Header --}}
    <header>
        {{-- Logo --}}
        <div class="row">
            <img class="secondary-logo" src="{{ $logo_src }}" alt="Hotel Logo">
        </div>
    </header>

    {{-- Footer --}}
    <footer class="text-center">
        <a href="https://harsi.mx/" class="no-spacing-text text-muted">
            HARSI HAZLO SIMPLE, HAZLO ÚTIL ©®
        </a>
        <p class="no-spacing-text">
            No Certificado SAT {{ $invoice->sat_cert_number }} /
            Fecha y hora de Certificación PAC {{ $certification_date }}
        </p>
        <p class="no-spacing-text">
            ESTE DOCUMENTO ES UNA REPRESENTACIÓN IMPRESA DE UN CFDI
        </p>
        <a href="https://harsi.mx/" class="no-spacing-text text-muted">
            https://harsi.mx/
        </a>
    </footer>

    {{-- Content --}}
    <main>

        {{-- Receiver - Issuer - CFDI Data --}}
        <section class="mt-2 px-0_5 row">

            {{-- Issuer & Receiver Data --}}
            <div class="col-6">
                <table class="table-borderless mixed-data"><tbody>

                    {{-- Issuer (RFC) --}}
                    <tr>
                        <td class="fw-semi-bold">RFC emisor:</td>
                        <td class="ps-1">{{ $issuer->tax_id }}</td>
                    </tr>

                    {{-- Issuer (Name) --}}
                    <tr>
                        <td class="fw-semi-bold">Nombre emisor:</td>
                        <td class="ps-1">{{ $issuer->legal_name }}</td>
                    </tr>

                    {{-- Receiver (RFC) --}}
                    <tr>
                        <td class="fw-semi-bold">RFC receptor:</td>
                        <td class="ps-1">{{ $invoice->receptor->tax_id }}</td>
                    </tr>

                    {{-- Receiver (Name) --}}
                    <tr>
                        <td class="fw-semi-bold">Nombre receptor:</td>
                        <td class="ps-1">{{ $invoice->receptor->legal_name }}</td>
                    </tr>

                    {{-- Receiver (CP) --}}
                    <tr>
                        <td class="fw-semi-bold">Código postal del receptor:</td>
                        <td class="ps-1">{{ $invoice->receptor->zip }}</td>
                    </tr>

                    {{-- Receiver (Tax System) --}}
                    <tr>
                        <td class="fw-semi-bold">Régimen fiscal del receptor:</td>
                        <td class="ps-1">{{ SatCatalogsHelper::getItem('c_RegimenFiscal', $invoice->receptor->tax_system, false) }}</td>
                    </tr>

                    {{-- Receiver (CFDI Use) --}}
                    <tr>
                        <td class="fw-semi-bold">Uso de CFDI:</td>
                        <td class="ps-1">{{ SatCatalogsHelper::getItem('c_UsoCFDI', $invoice->cfdi_use, false) }}</td>
                    </tr>

                </tbody></table>
            </div>

            {{-- CFDI Data --}}
            <div class="col-6">
                <table class="table-borderless mixed-data"><tbody>

                    {{-- Invoice (SAT UUID) --}}
                    <tr>
                        <td class="fw-semi-bold">Folio fiscal:</td>
                        <td class="ps-1">{{ $tax_folio }}</td>
                    </tr>

                    {{-- Invoice (CSD Number) --}}
                    <tr>
                        <td class="fw-semi-bold">No. de serie del CSD:</td>
                        <td class="ps-1">{{ $cds_issuer }}</td>
                    </tr>

                    {{-- Invoice (Series & Folio) --}}
                    <tr>
                        <td class="fw-semi-bold">Serie y folio:</td>
                        <td class="ps-1">{{ $serie_folio }}</td>
                    </tr>

                    {{-- Issuer (CP) --}}
                    <tr>
                        <td class="fw-semi-bold">Código postal del emisor:</td>
                        <td class="ps-1">{{ $issuer->zip }}</td>
                    </tr>

                    {{-- Invoice (Emission Date) --}}
                    <tr>
                        <td class="fw-semi-bold">Fecha y hora de operación:</td>
                        <td class="ps-1">{{ $emission_date }}</td>
                    </tr>

                    {{-- Invoice (Type) --}}
                    <tr>
                        <td class="fw-semi-bold">Efecto de Comprobante:</td>
                        <td class="ps-1">{{ SatCatalogsHelper::getItem('c_TipoDeComprobante', $invoice->invoice_type, false) }}</td>
                    </tr>

                    {{-- Issuer (Tax System) --}}
                    <tr>
                        <td class="fw-semi-bold">Régimen Fiscal:</td>
                        <td class="ps-1">{{ SatCatalogsHelper::getItem('c_RegimenFiscal', $issuer->tax_system, false) }}</td>
                    </tr>

                    {{-- Invoice (Export) --}}
                    @if (in_array($invoice->invoice_type, ['I', 'E']))
                        <tr>
                            <td class="fw-semi-bold">Exportación:</td>
                            <td class="ps-1">{{ SatCatalogsHelper::getItem('c_Exportacion', $invoice->export, false) }}</td>
                        </tr>
                    @endif

                </tbody></table>
            </div>

        </section>

        {{-- Concepts --}}
        <section class="mt-1 row">
          {{-- Control Variables --}}
            @php
                $federal_tax_config = [
                    [
                        'label'      => 'IVA',
                        'type'       => 'Traslado',
                        'rate_path'  => 'taxes.iva.rate',
                        'charge_path'=> 'taxes.iva',
                    ],
                    [
                        'label'      => 'IEPS',
                        'type'       => 'Traslado',
                        'rate_path'  => 'taxes.ieps.rate',
                        'charge_path'=> 'taxes.ieps',
                    ],
                    [
                        'label'      => 'ISR',
                        'type'       => 'Retención',
                        'rate_path'  => 'withholding_taxes.isr.rate',
                        'charge_path'=> 'withholding_taxes.isr',
                    ],
                    [
                        'label'      => 'IVA',
                        'type'       => 'Retención',
                        'rate_path'  => 'withholding_taxes.iva.rate',
                        'charge_path'=> 'withholding_taxes.iva',
                    ],
                ];
            @endphp

          {{-- Title --}}
            <p class="mb-1 small fw-semi-bold">Conceptos:</p>

          {{-- Concepts Summary --}}
            <table class="text-center row certify-table table-strong-bordered">
                <thead class="semi-pale-background">
                    <tr>
                        <th width="12.5%" class="py-0_5">Clave del Producto y/o Servicio</th>
                        <th width="auto" class="py-0_5">Cantidad</th>
                        <th width="12.5%" class="py-0_5">Clave de Unidad</th>
                        <th width="12.5%" class="py-0_5">Unidad</th>
                        <th width="12.5%" class="py-0_5">Valor Unitario</th>
                        <th width="12.5%" class="py-0_5">Importe</th>
                        <th width="12.5%" class="py-0_5">Descuento</th>
                        <th width="14%" class="py-0_5">Objeto Impuesto</th>
                    </tr>
                </thead>
                <tbody class="table-bordered">
                    @foreach ($invoice->taxItems as $concept)
                      {{-- Fiscal Data --}}
                        <tr>
                            <td class="px-0_5">{{ $concept->prod_serv_key }}</td>
                            <td class="px-0_5">{{ $concept->quantity }}</td>
                            <td class="px-0_5">{{ $concept->unit_key }}</td>

                            <td class="px-0_5">
                                {{ SatCatalogsHelper::getUnit($concept->unit_key, false) }}
                            </td>
                            <td class="px-0_5">
                                {{ number_format($concept->unit_price, 6) }}
                            </td>
                            <td class="px-0_5">
                                {{ number_format($concept->subtotal, 6) }}
                            </td>
                            <td class="px-0_5">
                                {{ number_format($concept->discount_total, 6) }}
                            </td>
                            <td class="px-0_5">
                                {{ SatCatalogsHelper::getItem('c_ObjetoImp', $concept->object_tax, false) }}
                            </td>
                        </tr>

                      {{-- Taxes & Description --}}
                        @php
                            // Normalizar impuestos federales
                            $federal_taxes        = (array) ($concept->tax_profile ?? []);
                            $federal_tax_charges  = (array) ($concept->tax_charges_summary ?? []);
                        @endphp

                        <tr>
                            {{-- Description --}}
                            <td class="px-0_5 fw-bold semi-pale-background">
                                Descripción
                            </td>
                            <td colspan="3" class="px-0_5 py-0_5 text-start">
                                <span class="fw-semi-bold">{{ $concept->name }}</span><br>

                                @if (!in_array($concept->description, [__('neutral_words')['none'], __('neutral_words')['none_2']]))
                                    <span>{{ mb_strtoupper($concept->description) }}</span><br>
                                @endif
                            </td>

                            {{-- Taxes --}}
                            <td colspan="4" class="py-0 cell-without-borders">
                                <table class="text-center row certify-table table-borderless">
                                    <thead><tr>
                                        <th class="py-0_5">Impuestos</th>
                                        <th class="py-0_5">Tipo</th>
                                        <th class="py-0_5">Base</th>
                                        <th class="py-0_5">Tipo Factor</th>
                                        <th class="py-0_5">Tasa o Cuota</th>
                                        <th class="py-0_5">Importe</th>
                                    </tr></thead>

                                    <tbody>
                                        @if ($concept->object_tax === '04')
                                            <tr>
                                                <td>IVA</td>
                                                <td>Trasladado</td>
                                                <td>Exento</td>
                                                <td>{{ number_format($invoice->subtotal, 6) }}</td>
                                                <td>{{ QuantityConverterHelper::str_toStrPercentage(0.0) }}</td>
                                                <td>{{ number_format(0.0, 6) }}</td>
                                            </tr>
                                        @else
                                            @foreach ($federal_tax_config as $tax)
                                                @php
                                                    $rate   = data_get($federal_taxes, $tax['rate_path']);
                                                    $charge = data_get($federal_tax_charges, $tax['charge_path']);

                                                    $base = null;
                                                    if (!is_null($rate) && !is_null($charge)) {
                                                        $rateNum   = (float) $rate;
                                                        $chargeNum = (float) $charge;

                                                        $base = ($rateNum != 0.0) ? ($chargeNum / $rateNum) : 0.0;
                                                    }
                                                @endphp

                                                @if (!is_null($rate))
                                                    <tr>
                                                        <td>{{ $tax['label'] }}</td>
                                                        <td>{{ $tax['type'] }}</td>
                                                        <td>{{ number_format($base, 6) }}</td>
                                                        <td>Tasa</td>
                                                        <td>{{ QuantityConverterHelper::str_toStrPercentage($rate) }}</td>
                                                        <td>{{ number_format($charge, 6) }}</td>
                                                    </tr>
                                                @endif
                                            @endforeach
                                        @endif
                                    </tbody>
                                </table>
                            </td>

                        </tr>

                        {{-- Separator --}}
                        @if (!$loop->last)
                            <tr><td colspan="8" class="cell-without-borders">&nbsp;</td></tr>
                        @endif
                    @endforeach
                </tbody>
            </table>

        </section>

        {{-- Totals & Payment Data --}}
        <section class="px-3 mt-0 row">

            {{-- Payment Data --}}
            <div class="col-6">
                <table class="table-borderless mixed-data">
                    {{-- Head Spacemen --}}
                    <thead>
                        <tr>
                            <th class="py-0">&nbsp;</th>
                            <th class="py-0"></th>
                        </tr>
                    </thead>

                    {{-- Body --}}
                    <tbody>

                        {{-- Currency --}}
                        <tr>
                            <td class="fw-semi-bold">Moneda:</td>
                            <td class="ps-6">{{ SatCatalogsHelper::getItem('c_Moneda', $invoice->currency, false) }}</td>
                        </tr>

                        {{-- Currency --}}
                        <tr>
                            <td class="fw-semi-bold">Forma de pago:</td>
                            <td class="ps-6">{{ SatCatalogsHelper::getItem('c_FormaPago', $invoice->payment_form, false) }}</td>
                        </tr>

                        {{-- Currency --}}
                        <tr>
                            <td class="fw-semi-bold">Método de pago:</td>
                            <td class="ps-6">{{ SatCatalogsHelper::getItem('c_MetodoPago', $invoice->payment_method, false) }}</td>
                        </tr>

                    </tbody>
                </table>
            </div>

            {{-- Totals & Federal Taxes Breakdown --}}
            <div class="col-6">
                <table class="container table-borderless mixed-data">
                    {{-- Head Spacemen --}}
                    <thead>
                        <tr>
                            <th width="25%" class="py-0">&nbsp;</th>
                            <th class="py-0"></th>
                        </tr>
                    </thead>

                    {{-- Body --}}
                    <tbody>

                        {{-- Subtotal --}}
                        <tr>
                            <td class="fw-semi-bold">Subtotal</td>
                            <td class="text-end">{{ FormatCurrencyHelper::formatCurrency($invoice->subtotal, $invoice->currency) }}</td>
                        </tr>

                        {{-- Taxes Breakdown --}}
                            @php
                                $federal_tax_profile = [];

                                // Group concepts taxes by tax
                                foreach ($invoice->taxItems as $item) {
                                    $profile = $item->tax_profile ?? [];
                                    $charges = $item->tax_charges_summary ?? [];

                                    if ($item->object_tax === "04") {
                                        $federal_tax_profile["IVA_Trasladado_Exento"] = [
                                            'label'  => "IVA",
                                            'type'   => "Exento",
                                            'rate'   => 0.00, 'charge' => 0.0,
                                        ];
                                    } else {
                                        foreach ($federal_tax_config as $ftx) {
                                            $rate   = data_get($profile, $ftx['rate_path']);
                                            $charge = data_get($charges, $ftx['charge_path']);
                                                if ($rate === null || $charge === null) continue;

                                            $key = $ftx['label'] . '_' . $rate;

                                            if (!isset($federal_tax_profile[$key])) {
                                                $federal_tax_profile[$key] = [
                                                    'label'  => $ftx['label'],
                                                    'type'   => $ftx['type'],
                                                    'rate'   => $rate, 'charge' => 0
                                                ];
                                            }

                                            $federal_tax_profile[$key]['charge'] += $charge;
                                        }
                                    }
                                }
                            @endphp
                        <tr>
                            <td class="fw-semi-bold cell-not-centered">Impuestos</td>
                            <td>
                                <table class="container row table-borderless">
                                    {{-- Head Spacemen --}}
                                    <colgroup>
                                        <col style="width:18%">
                                        <col>
                                        <col>
                                        <col>
                                    </colgroup>

                                    {{-- Body --}}
                                    <tbody>
                                        @foreach ($federal_tax_profile as $label => $ftx_profile)
                                            <tr>
                                                <td class="py-0 text-start">{{ $ftx_profile['label'] }}</td>
                                                <td class="py-0 text-start">{{ $ftx_profile['type'] }}</td>
                                                <td class="py-0 text-start">{{ QuantityConverterHelper::str_toStrPercentage($ftx_profile['rate']) }}</td>
                                                <td class="py-0 text-end">{{ FormatCurrencyHelper::formatCurrency($ftx_profile['charge'], $invoice->currency) }}<br></td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </td>

                        </tr>

                        {{-- Total --}}
                        <tr>
                            <td class="pt-0_5 fw-semi-bold">Total</td>
                            <td class="pt-0_5 text-end fw-semi-bold">{{ FormatCurrencyHelper::formatCurrency($invoice->total, $invoice->currency) }}</td>
                        </tr>

                    </tbody>
                </table>
            </div>

        </section>

        {{-- Related Documents --}}
        @if ($invoice->related_documents)
            {{-- Title --}}
            <p class="mt-3 mb-0 small fw-semi-bold">Documentos Relacionados:</p>

            <section class="mt-1 row">
                <div class="col-6">
                    <table class="table-strong-bordered">
                        <thead class="semi-pale-background">
                            <tr>
                                <th>Tipo de Relación</th>
                                <th>Folio Fiscal Relacionado</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($invoice->related_documents as $rd)
                                @php
                                    $relation_type = collect($document_relations)
                                        ->firstWhere('item_key', $rd->relation_type)?->label;
                                @endphp
                                <tr>
                                    <td>{{ TextTransformHelper::trimText($relation_type, 35) }}</td>
                                    <td class="py-0 text-start">{{ $rd->uuid }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </section>
        @endif

        {{-- Local Taxes Complement --}}
            @php
                // Normalizar impuestos locales siempre a objeto con propiedades
                $ltx_summary =  is_array($invoice->local_taxes)
                    ? (object) $invoice->local_taxes
                    : ($invoice->local_taxes ?? (object)[]);

                $transferred = collect(data_get($ltx_summary, 'transferred', []));
                $withheld    = collect(data_get($ltx_summary, 'withheld', []));

                $ltx_tr_total = $transferred->sum(fn ($item) => (float) data_get($item, 'charge', 0));
                $ltx_rt_total = $withheld->sum(fn ($item) => (float) data_get($item, 'charge', 0));
            @endphp

        @if (count($ltx_summary->transferred) || count($ltx_summary->withheld))
            <section class="px-3 mt-0 row">
                <div class="col-8">
                    {{-- Title --}}
                    <p class="mb-1 small fw-semi-bold">Complementos de impuestos locales (V1.0):</p>

                    {{-- Local Taxes Breakdown --}}
                      {{-- Transferred --}}
                        @if (count($ltx_summary->transferred))
                            <table class="mb-1 text-center table-strong-bordered mixed-data row">
                                {{-- Header & Total Transferred --}}
                                <thead>
                                    <tr><th colspan="3" class="semi-pale-background">
                                        Monto total de traslados:
                                    </th></tr>

                                    <tr><td colspan="3" class="py-0">
                                        {{ $ltx_tr_total }}
                                    </td></tr>

                                    <tr class="pale-background">
                                        <th width="42%">Impuesto Local Trasladado</th>
                                        <th>Tasa de Traslado</th>
                                        <th>Importe</th>
                                    </tr>
                                </thead>

                                {{-- Breakdown --}}
                                <tbody>
                                    @foreach ($ltx_summary->transferred as $ltx_tr)
                                        @php $ltx_tr = (array) $ltx_tr; @endphp

                                        <tr>
                                            <td class="py-0">{{ $ltx_tr['name'] }}</td>
                                            <td class="py-0">{{ QuantityConverterHelper::str_toStrPercentage($ltx_tr['rate'], 2, false) }}</td>
                                            <td class="py-0">{{ $ltx_tr['charge'] }}<br></td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        @endif

                      {{-- Withheld --}}
                        @if (count($ltx_summary->withheld))
                            <table class="mb-0 text-center table-strong-bordered mixed-data row">
                                {{-- Header & Total Transferred --}}
                                <thead>
                                    <tr><th colspan="3" class="semi-pale-background">
                                        Monto total de retenciones:
                                    </th></tr>

                                    <tr><td colspan="3" class="py-0">
                                        {{ $ltx_rt_total }}
                                    </td></tr>

                                    <tr class="pale-background">
                                        <th width="42%">Impuesto Local Retenido</th>
                                        <th>Tasa de Retención</th>
                                        <th>Importe</th>
                                    </tr>
                                </thead>

                                {{-- Breakdown --}}
                                <tbody>
                                    @foreach ($ltx_summary->withheld as $ltx_rt)
                                        @php $ltx_rt = (array) $ltx_rt; @endphp

                                        <tr>
                                            <td class="py-0">{{ $ltx_rt['name'] }}</td>
                                            <td class="py-0">{{ QuantityConverterHelper::str_toStrPercentage($ltx_rt['rate'], 2, false) }}</td>
                                            <td class="py-0">{{ $ltx_rt['charge'] }}<br></td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        @endif

                </div>
                <div class="col-5"></div>
            </section>
        @endif

        {{-- SAT Certificates --}}
        <section class="mt-2">

            {{-- CFDI Seal & SAT Seal --}}
            <div class="row">
                @php
                    $illusionary_certificated_data = 'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Repudiandae nemo debitis recusandae maiores natus doloribus quaerat? Delectus quasi nobis reprehenderit vel molestias quis ullam, qui rerum a suscipit nulla harum!';
                @endphp

                {{-- CFDI Seal --}}
                <p class="px-1">
                    <span class="fw-bold">Sello digital del CFDI:</span><br>
                    <span class="wrapped-text">{{ $illusionary_certificated_data }}</span>
                </p>

                {{-- SAT Seal --}}
                <p class="px-1 mb-0">
                    <span class="fw-bold">Sello digital del SAT:</span><br>
                    <span class="wrapped-text">{{ $illusionary_certificated_data }}</span>
                </p>
            </div>

            {{-- QR - Original String --}}
            <div class="row">

                {{-- QR Code --}}
                <div class="col-3">
                    <img class="left-qr-code" src="{{ $qr_stamp }}" alt="Invoice QR">
                    <p class="text-center pe-4">
                        <span class="fw-semi-bold">Prov. Cert.</span>
                        {{ data_get($invoice, 'response_payload.stamp.rfc_provider_cert', 'PPD101129EA3') }}
                    </p>
                </div>

                {{-- Original String --}}
                <div class="col-8">
                    <p class="pe-1">
                        <span class="fw-bold">Cadena Original del Complemento de certificación digital del SAT:</span><br>
                        <span class="wrapped-text">{{ $illusionary_certificated_data }}</span>
                    </p>
                </div>

            </div>
        </section>

    </main>

</body>

</html>
