<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Ticket {{ $orden->folio_unico }}</title>
    <style>
        @page { margin: 0; }
        html { box-sizing: border-box; margin: 0; padding: 0; width: 227.56pt; }
        *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
        /*
         * setPaper(80mm) = 227.56pt. Caja interior + borde en pt evita desborde a la derecha y hace visible el borde
         * (DomPDF trata mal body+mm+img data-uri a tamaño intrínseco).
         */
        body {
            font-family: DejaVu Sans, sans-serif;
            font-size: 8.5px;
            width: 227.56pt;
            max-width: 227.56pt;
            margin: 0;
            padding: 0;
            color: #000;
            overflow-wrap: break-word;
            word-wrap: break-word;
        }
        .ticket-root {
            width: 219pt;
            max-width: 219pt;
            margin: 0 auto;
            padding: 4pt 5pt 8pt;
            border: 0.45pt solid #000;
            text-align: left;
        }
        .center { text-align: center; }
        .logo { max-width: 100%; max-height: 14mm; margin: 2px auto 4px; display: block; }
        .empresa { font-weight: bold; font-size: 9px; margin-bottom: 1px; }
        .fiscal { font-size: 6.5px; line-height: 1.25; margin-bottom: 2px; color: #111; }
        hr {
            border: none;
            border-top: 0.35pt dashed #000;
            margin: 4px 0;
            width: 100%;
            height: 0;
        }
        .ticket-line {
            font-weight: bold;
            font-size: 7.5px;
            margin: 4px 0;
            text-align: center;
            word-break: break-word;
        }
        .section-title {
            text-align: center;
            font-weight: bold;
            font-size: 9px;
            margin: 8px 0 4px;
            letter-spacing: 0.02em;
        }
        table.tgrid {
            width: 100%;
            max-width: 100%;
            table-layout: fixed;
            border-collapse: collapse;
            font-size: 7px;
            margin: 2px 0 4px;
        }
        table.tgrid th { text-align: left; font-weight: bold; border-bottom: 1px solid #000; padding: 1px 0; vertical-align: bottom; }
        table.tgrid th.num { text-align: right; }
        table.tgrid td { padding: 1px 0; border-bottom: 1px dotted #666; vertical-align: top; }
        table.tgrid td.concepto {
            word-wrap: break-word;
            overflow-wrap: break-word;
            word-break: break-word;
        }
        table.tgrid td.num { text-align: right; font-size: 6.5px; white-space: nowrap; }
        .subline { font-size: 6.5px; padding-left: 2px; margin: 0 0 1px; line-height: 1.25; }
        .section-total { text-align: right; font-weight: bold; font-size: 8px; margin: 2px 0 6px; padding-top: 2px; border-top: 1px dashed #000; }
        .resumen { font-size: 7.5px; line-height: 1.35; margin: 4px 0; width: 100%; max-width: 100%; }
        .resumen .row { display: table; width: 100%; table-layout: fixed; }
        .resumen .row > span { display: table-cell; }
        .resumen .lbl { width: 58%; word-wrap: break-word; }
        .resumen .val { text-align: right; font-weight: bold; width: 42%; white-space: nowrap; }
        .total-final {
            font-size: 10px;
            font-weight: bold;
            margin: 4px 0;
            text-align: right;
            border-top: 1px solid #000;
            padding-top: 3px;
            width: 100%;
            max-width: 100%;
            word-break: break-word;
        }
        /* Cierre del ticket: cliente, políticas, leyendas y QR — todo centrado */
        .ticket-cierre {
            text-align: center;
            font-size: 8.5px;
            line-height: 1.38;
            margin-top: 4px;
        }
        .ticket-cierre .fiscal {
            text-align: center;
        }
        .nota-pago { font-size: 8px; margin: 4px 0 8px; font-style: italic; text-align: center; }
        .bloque-cliente { font-size: 8.5px; line-height: 1.4; margin: 6px 0; text-align: center; }
        .gracias { text-align: center; font-weight: bold; font-size: 9.5px; margin: 10px 0 5px; }
        .atendio { text-align: center; font-size: 8px; margin-bottom: 8px; }
        .politicas-titulo { font-weight: bold; font-size: 9px; text-align: center; margin: 10px 0 5px; }
        .politicas {
            font-size: 8px;
            line-height: 1.38;
            color: #222;
            text-align: center;
            margin-bottom: 8px;
        }
        .politicas li { margin-bottom: 5px; padding-left: 0; list-style-position: inside; text-align: center; }
        .politicas ol { padding-left: 0; margin: 0; text-align: center; list-style-position: inside; }
        .legal { font-size: 8px; text-align: center; margin-top: 8px; font-weight: bold; line-height: 1.4; }
        .barcode-wrap {
            text-align: center;
            margin: 8px auto 4px;
            width: 100%;
            max-width: 100%;
            overflow: hidden;
        }
        .barcode-wrap img {
            display: block;
            margin: 0 auto;
            width: 190pt;
            height: 48pt;
            max-width: 100%;
        }
        .barcode-caption { font-size: 7.5px; margin-top: 5px; text-align: center; line-height: 1.35; }
    </style>
</head>
<body>
    @php
        use App\Support\LaundrySemaphoreColorResolver;
        use App\Support\TicketObservationLines;
        use App\Support\TicketThermalSections;

        $entregaCarbon = LaundrySemaphoreColorResolver::promisedAt($orden);
        if (! $entregaCarbon instanceof \Illuminate\Support\Carbon) {
            $entregaCarbon = \Illuminate\Support\Carbon::parse($entregaCarbon, config('app.timezone'));
        }
        $entregaStr = LaundrySemaphoreColorResolver::formatEntregaTicket($entregaCarbon);

        $replaceVars = [
            '{folio}' => (string) ($orden->folio_unico ?? ''),
            '{fecha_hora}' => (string) optional($orden->created_at)->format('d/m/Y H:i:s'),
            '{fecha}' => (string) optional($orden->created_at)->format('d/m/Y'),
            '{cliente}' => (string) ($orden->cliente_nombre ?? ''),
            '{total}' => number_format((float) ($orden->total ?? 0), 2),
            '{fecha_entrega}' => $entregaCarbon->format('d/m/Y'),
            '{fecha_entrega_hora}' => $entregaCarbon->format('H:i'),
            '{fecha_entrega_dia}' => strtoupper($entregaCarbon->locale('es')->isoFormat('ddd')),
            '{fecha_entrega_completa}' => $entregaStr,
            '{recepcionista}' => (string) ($orden->recepcionista->name ?? 'N/D'),
        ];

        $headerLines = collect([
            $config?->ticket_encabezado_nombre ?? null,
            ! empty($config?->ticket_encabezado_rfc) ? 'RFC: '.$config->ticket_encabezado_rfc : null,
            $config?->ticket_encabezado_domicilio ?? null,
            $config?->ticket_encabezado_cp_ciudad ?? null,
            ! empty($config?->ticket_encabezado_telefono) ? 'TELEFONO: '.$config->ticket_encabezado_telefono : null,
            $config?->ticket_encabezado_linea_folio ?? null,
        ])
            ->map(fn ($line) => trim((string) $line))
            ->filter(fn ($line) => $line !== '')
            ->map(fn ($line) => strtr($line, $replaceVars))
            ->values();

        $footerLines = collect(preg_split("/\r\n|\n|\r/", (string) ($config?->ticket_footer_text ?? '')))
            ->map(fn ($line) => trim((string) $line))
            ->filter(fn ($line) => $line !== '')
            ->map(fn ($line) => strtr($line, $replaceVars))
            ->values();

        $part = TicketThermalSections::partition($detalles);
        $cargas = $part['cargas'];
        $servicios = $part['servicios'];
        $contenido = $part['contenido'];
        $subCargas = TicketThermalSections::sectionSubtotal($cargas);
        $subServicios = TicketThermalSections::sectionSubtotal($servicios);
        $ropaSublines = TicketThermalSections::detalleRopaSublines($orden->detalles_ropa ?? null);

        $sumLineas = (float) collect($detalles)->sum(fn ($d) => (float) $d->subtotal);
        $subtotalOrden = (float) ($orden->subtotal ?? 0) > 0 ? (float) $orden->subtotal : $sumLineas;
        $impuestos = (float) ($orden->impuestos ?? 0);
        $total = (float) ($orden->total ?? 0);
        $anticipo = 0.0;
        $saldo = max(0, $total - $anticipo);
        $registros = collect($detalles)->count();

        $entrega = $entregaCarbon->copy();
        $entregaStr = LaundrySemaphoreColorResolver::formatEntregaTicket($entrega);

        $politicasDefault = [
            'LA CARGA MÍNIMA ES DE 3 KG. PARA SERVICIOS NORMAL, EXPRESS y SÚPER EXPRESS.',
            'EL TICKET ES INDISPENSABLE PARA RECOGER SUS PRENDAS.',
            'LOS CAMBIOS O RECLAMACIONES POR PIEZAS FALTANTES O DAÑOS DEBERÁN HACERSE A MÁS TARDAR 3 DÍAS DESPUÉS DE LA ENTREGA.',
            'TIEMPO MÁXIMO EN BODEGA ES DE 8 DÍAS A PARTIR DE LA FECHA DE ENTREGA DE LA PRENDA, DESPUÉS DE ESE TIEMPO LA LAVANDERÍA QUEDA LIBERADA DE TODA RESPONSABILIDAD.',
        ];
    @endphp

    <div class="ticket-root">

    @if($config && $config->logo_url)
        <img src="{{ $config->logo_url }}" alt="Logo" class="logo" />
    @endif
    <div class="center">
        @if($headerLines->isNotEmpty())
            @foreach($headerLines as $line)
                <div class="fiscal">{{ $line }}</div>
            @endforeach
        @else
            <div class="empresa">{{ $config->nombre_empresa ?? config('app.name') }}</div>
            @if($config && ($config->rfc || $config->direccion))
                <div class="fiscal">
                    @if(!empty($config->rfc)) RFC: {{ $config->rfc }}<br> @endif
                    @if(!empty($config->direccion)) {{ $config->direccion }} @endif
                    @if(!empty($config->telefono))<br>{{ $config->telefono }} @endif
                </div>
            @endif
        @endif
    </div>

    <div class="ticket-line">
        TICKET: {{ $orden->folio_unico }} &nbsp;|&nbsp; EXP: {{ $orden->created_at->format('d/m/Y') }} &nbsp;|&nbsp; {{ $orden->created_at->format('H:i:s') }}
    </div>
    <hr>

    @if($cargas->isNotEmpty())
        <div class="section-title">CARGAS MÍNIMAS</div>
        <table class="tgrid" cellspacing="0" cellpadding="0">
            <colgroup>
                <col style="width: 30%;" />
                <col style="width: 16%;" />
                <col style="width: 13%;" />
                <col style="width: 13%;" />
                <col style="width: 28%;" />
            </colgroup>
            <thead>
                <tr>
                    <th class="concepto">CONCEPTO</th>
                    <th class="num">P. UNIT.</th>
                    <th class="num">CANT.</th>
                    <th class="num">DESC.</th>
                    <th class="num">IMPORTE</th>
                </tr>
            </thead>
            <tbody>
                @foreach($cargas as $idx => $d)
                    <tr>
                        <td class="concepto">
                            <strong>{{ strtoupper(TicketThermalSections::lineConcepto($d)) }}</strong>
                            @if($idx === 0 && count($ropaSublines) > 0)
                                @foreach($ropaSublines as $sl)
                                    <div class="subline">→ {{ \Illuminate\Support\Str::limit($sl, 120) }}</div>
                                @endforeach
                            @endif
                        </td>
                        <td class="num">${{ number_format((float) $d->precio_unitario, 2) }}</td>
                        <td class="num">{{ number_format((float) $d->cantidad, 2) }}</td>
                        <td class="num">$0.00</td>
                        <td class="num">${{ number_format((float) $d->subtotal, 2) }}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>
        <div class="section-total">${{ number_format($subCargas, 2) }}</div>
    @endif

    @if($servicios->isNotEmpty())
        <div class="section-title">SERVICIOS GENERALES</div>
        <table class="tgrid" cellspacing="0" cellpadding="0">
            <colgroup>
                <col style="width: 30%;" />
                <col style="width: 16%;" />
                <col style="width: 13%;" />
                <col style="width: 13%;" />
                <col style="width: 28%;" />
            </colgroup>
            <thead>
                <tr>
                    <th class="concepto">CONCEPTO</th>
                    <th class="num">P. UNIT.</th>
                    <th class="num">CANT.</th>
                    <th class="num">DESC.</th>
                    <th class="num">IMPORTE</th>
                </tr>
            </thead>
            <tbody>
                @foreach($servicios as $d)
                    <tr>
                        <td class="concepto">{{ TicketThermalSections::lineConcepto($d) }}</td>
                        <td class="num">${{ number_format((float) $d->precio_unitario, 2) }}</td>
                        <td class="num">{{ number_format((float) $d->cantidad, 2) }}</td>
                        <td class="num">$0.00</td>
                        <td class="num">${{ number_format((float) $d->subtotal, 2) }}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>
        <div class="section-total">${{ number_format($subServicios, 2) }}</div>
    @endif

    @if($contenido->isNotEmpty())
        <div class="section-title">CONTENIDO DEL SERVICIO</div>
        <table class="tgrid" cellspacing="0" cellpadding="0">
            <colgroup>
                <col style="width: 70%;" />
                <col style="width: 30%;" />
            </colgroup>
            <thead>
                <tr>
                    <th class="concepto">DETALLE</th>
                    <th class="num">CANT.</th>
                </tr>
            </thead>
            <tbody>
                @foreach($contenido as $d)
                    <tr>
                        <td class="concepto">{{ TicketThermalSections::lineConcepto($d) }}</td>
                        <td class="num">{{ number_format((float) $d->cantidad, 0) }}</td>
                    </tr>
                    @if(!empty($d->observations))
                        <tr>
                            <td class="concepto subline" colspan="2">→ {{ \Illuminate\Support\Str::limit($d->observations, 120) }}</td>
                        </tr>
                    @endif
                @endforeach
            </tbody>
        </table>
    @endif

    @if($cargas->isEmpty() && $servicios->isEmpty())
        <table class="tgrid" cellspacing="0" cellpadding="0">
            <colgroup>
                <col style="width: 30%;" />
                <col style="width: 16%;" />
                <col style="width: 13%;" />
                <col style="width: 13%;" />
                <col style="width: 28%;" />
            </colgroup>
            <tbody>
                <tr>
                    <td class="concepto" colspan="5">{{ $orden->tipo_servicio ?? 'Servicio' }}</td>
                </tr>
                <tr>
                    <td class="concepto">—</td>
                    <td class="num">—</td>
                    <td class="num">1.00</td>
                    <td class="num">$0.00</td>
                    <td class="num">${{ number_format($total, 2) }}</td>
                </tr>
            </tbody>
        </table>
        <div class="section-total">${{ number_format($total, 2) }}</div>
    @endif

    <div class="resumen">
        <div class="row"><span class="lbl">Registros:</span><span class="val">{{ $registros }}</span></div>
        <div class="row"><span class="lbl">Impuestos:</span><span class="val">{{ number_format($impuestos, 2) }}</span></div>
        <div class="row"><span class="lbl">Recibido:</span><span class="val">$0.00</span></div>
        <div class="row"><span class="lbl">Cambio:</span><span class="val">$0.00</span></div>
    </div>
    <div class="total-final">TOTAL: ${{ number_format($total, 2) }}</div>
    <div class="resumen">
        <div class="row"><span class="lbl">ANTICIPO:</span><span class="val">$0.00</span></div>
        <div class="row"><span class="lbl">SALDO:</span><span class="val">${{ number_format($saldo, 2) }}</span></div>
    </div>
    <div class="ticket-cierre">
    @if($anticipo <= 0.0001)
        <div class="nota-pago">NO DEJO ANTICIPO</div>
    @endif

    <div class="bloque-cliente">
        <strong>CLIENTE:</strong> {{ $orden->cliente_nombre ?? '—' }}<br>
        <strong>SE ENTREGA:</strong> {{ $entregaStr }}<br>
        <strong>PENDIENTE DE PAGAR:</strong> ${{ number_format($saldo, 2) }}
    </div>

    @if(TicketObservationLines::hasAny($ticketObservations))
        <hr>
        @if(!empty($ticketObservations['garment_sections']))
            <div class="section-title" style="font-size:8px">{{ $ticketObsTitlePrenda }}</div>
            @foreach($ticketObservations['garment_sections'] as $sec)
                <div class="fiscal"><strong>{{ $sec['title'] }}</strong></div>
                @foreach($sec['lines'] as $line)
                    <div class="fiscal">• {{ \Illuminate\Support\Str::limit($line, 220) }}</div>
                @endforeach
            @endforeach
        @endif
        @foreach($ticketObservations['general_lines'] as $gl)
            <div class="fiscal"><strong>{{ $gl['label'] }}:</strong> {{ \Illuminate\Support\Str::limit($gl['text'], 220) }}</div>
        @endforeach
    @endif

    <div class="gracias">¡GRACIAS POR SU PREFERENCIA!</div>
    <div class="atendio">LE ATENDIÓ: {{ \Illuminate\Support\Str::upper(optional($orden->recepcionista)->name ?? 'N/D') }}</div>

    <div class="politicas-titulo">POLITICAS DEL SERVICIO</div>
    @if($footerLines->isNotEmpty())
        <div class="politicas">
            @foreach($footerLines as $line)
                <div>{{ $line }}</div>
            @endforeach
        </div>
    @elseif($config && !empty($config->terminos_condiciones))
        <div class="politicas">{{ \Illuminate\Support\Str::limit(strip_tags((string) $config->terminos_condiciones), 1200) }}</div>
    @else
        <ol class="politicas">
            @foreach($politicasDefault as $p)
                <li value="{{ $loop->iteration }}">{{ $p }}</li>
            @endforeach
        </ol>
    @endif

    <div class="legal">ESTE TICKET NO ES UN COMPROBANTE FISCAL<br>COPIA PARA EL CLIENTE</div>

    <hr>
    @if(!empty($barcodeSeguimientoDataUri))
        <div class="barcode-wrap">
            <img
                src="{!! $barcodeSeguimientoDataUri !!}"
                width="240"
                height="70"
                style="width: 190pt; height: 48pt; display: block; margin: 0 auto;"
                alt="Código de barras seguimiento"
            />
            <div class="barcode-caption">Escanee en Lavandería (Escanear / escaneo por área).</div>
            @if(!empty($barcodeSeguimientoPayload))
                <div class="barcode-caption" style="font-weight: bold; letter-spacing: 0.04em;">{{ $barcodeSeguimientoPayload }}</div>
            @endif
            @if(!empty($urlSeguimiento))
                <div class="fiscal center" style="word-break: break-all; margin-top: 4px;">Consulta pública: {{ $urlSeguimiento }}</div>
            @endif
        </div>
    @else
        <div class="fiscal center">Consulta pública: {{ e($urlSeguimiento ?? '') }}</div>
    @endif
    </div>

    </div>

</body>
</html>
