<?php
$document = is_array($document ?? null) ? $document : [];
$details = is_array($details ?? null) ? $details : [];
$docType = (string) ($document['tipo_documento'] ?? 'factura');
$docLabel = $docType === 'nota_credito'
    ? 'NOTA CREDITO'
    : ($docType === 'nota_debito' ? 'NOTA DEBITO' : 'FACTURA');

$subtotal = (float) ($document['subtotal'] ?? 0);
$discount = (float) ($document['venta_descuento'] ?? 0);
$taxes = (float) ($document['impuestos'] ?? 0);
$total = (float) ($document['total'] ?? 0);
$paid = (float) ($document['total_pagado'] ?? 0);
$paymentMethods = trim((string) ($document['metodos_pago'] ?? ''));
$cufe = trim((string) ($document['cufe'] ?? ''));
$qrPath = trim((string) ($document['qr_path'] ?? ''));
$fiscalSettings = is_array($fiscalSettings ?? null) ? $fiscalSettings : [];
$factusConfigured = (bool) ($factusConfigured ?? false);
$dianResolution = is_array($dianResolution ?? null) ? $dianResolution : [];

$resolutionNumber = trim((string) ($dianResolution['numero_resolucion'] ?? ($fiscalSettings['resolucion_dian'] ?? '')));
$resolutionPrefix = trim((string) ($dianResolution['prefijo'] ?? ''));
$resolutionRangeFrom = trim((string) ($dianResolution['rango_desde'] ?? ''));
$resolutionRangeTo = trim((string) ($dianResolution['rango_hasta'] ?? ''));
$resolutionDateFromRaw = trim((string) ($dianResolution['fecha_desde'] ?? ''));
$resolutionDateToRaw = trim((string) ($dianResolution['fecha_hasta'] ?? ''));

$resolutionDateFrom = $resolutionDateFromRaw;
$resolutionDateTo = $resolutionDateToRaw;
$resolutionMonths = '';
if ($resolutionDateFromRaw !== '' && $resolutionDateToRaw !== '') {
    $fromTs = strtotime($resolutionDateFromRaw);
    $toTs = strtotime($resolutionDateToRaw);
    if ($fromTs !== false) {
        $resolutionDateFrom = date('Y/m/d', $fromTs);
    }
    if ($toTs !== false) {
        $resolutionDateTo = date('Y/m/d', $toTs);
    }

    try {
        $fromDate = new DateTimeImmutable($resolutionDateFromRaw);
        $toDate = new DateTimeImmutable($resolutionDateToRaw);
        $interval = $fromDate->diff($toDate);
        $months = ((int) $interval->y * 12) + (int) $interval->m;
        if ((int) $interval->d > 0) {
            $months++;
        }
        if ($months > 0) {
            $resolutionMonths = (string) $months . ' MESES';
        }
    } catch (Throwable) {
        $resolutionMonths = '';
    }
}

$fiscalRegime = trim((string) ($fiscalSettings['regimen_fiscal'] ?? ''));
$fiscalActivity = trim((string) ($fiscalSettings['actividad_economica'] ?? ''));
$isVatResponsible = trim((string) ($fiscalSettings['responsable_iva'] ?? '0')) === '1';
$isElectronicBilling = trim((string) ($fiscalSettings['facturacion_electronica'] ?? '0')) === '1';
$techProviderName = trim((string) ($fiscalSettings['fe_proveedor_tecnologico'] ?? 'FACTUS S.A.S.'));
$techProviderNit = trim((string) ($fiscalSettings['fe_proveedor_nit'] ?? ''));
$softwareName = trim((string) ($fiscalSettings['fe_software_nombre'] ?? 'VELTRIX POS'));
$softwareMakerName = trim((string) ($fiscalSettings['fe_fabricante_nombre'] ?? ''));
$softwareMakerNit = trim((string) ($fiscalSettings['fe_fabricante_nit'] ?? ''));

$qrImageSrc = '';
if ($qrPath !== '') {
    if (preg_match('/^https?:\/\//i', $qrPath) === 1) {
        $qrImageSrc = $qrPath;
    } else {
        $absoluteQrPath = base_path('public/' . ltrim($qrPath, '/'));
        if (is_file($absoluteQrPath) && is_readable($absoluteQrPath)) {
            $mimeType = '';
            if (function_exists('mime_content_type')) {
                $detected = @mime_content_type($absoluteQrPath);
                if (is_string($detected) && $detected !== '') {
                    $mimeType = $detected;
                }
            }
            if ($mimeType === '') {
                $ext = strtolower((string) pathinfo($absoluteQrPath, PATHINFO_EXTENSION));
                $mimeType = match ($ext) {
                    'jpg', 'jpeg' => 'image/jpeg',
                    'png' => 'image/png',
                    'webp' => 'image/webp',
                    'gif' => 'image/gif',
                    default => 'application/octet-stream',
                };
            }

            $binary = @file_get_contents($absoluteQrPath);
            if (is_string($binary) && $binary !== '') {
                $qrImageSrc = 'data:' . $mimeType . ';base64,' . base64_encode($binary);
            }
        }
    }
}

$qrFallbackSrc = '';
if ($cufe !== '') {
    $qrFallbackSrc = 'https://quickchart.io/qr?size=220&text=' . rawurlencode($cufe);
}

if ($qrImageSrc === '' && $qrFallbackSrc !== '') {
    $qrImageSrc = $qrFallbackSrc;
}

$saleDateRaw = trim((string) ($document['fecha_emision'] ?? ($document['venta_fecha'] ?? '')));
$saleDate = $saleDateRaw;
$saleTime = '';
if ($saleDateRaw !== '') {
    $timestamp = strtotime($saleDateRaw);
    if ($timestamp !== false) {
        $saleDate = date('d/m/Y', $timestamp);
        $saleTime = date('H:i', $timestamp);
    }
}

$lineItems = [];
$taxSummary = [];
$lineGrossTotal = 0.0;
$lineNetBaseTotal = 0.0;
$lineTaxTotal = 0.0;
$lineDiscountTotal = 0.0;
$totalItems = 0.0;
foreach ($details as $line) {
    $lineQty = (float) ($line['cantidad'] ?? 0);
    $lineUnitPrice = (float) ($line['precio_unitario'] ?? 0);
    $lineGross = round($lineQty * $lineUnitPrice, 2);
    $lineTax = (float) ($line['impuesto'] ?? 0);
    $lineTotal = (float) ($line['total_linea'] ?? 0);
    $lineBase = max(0.0, $lineTotal - $lineTax);
    $lineDiscount = max(0.0, round($lineGross - $lineBase, 2));

    $lineGrossTotal += $lineGross;
    $lineNetBaseTotal += $lineBase;
    $lineTaxTotal += $lineTax;
    $lineDiscountTotal += $lineDiscount;
    $totalItems += $lineQty;

    $lineItems[] = [
        'descripcion' => (string) ($line['descripcion'] ?? ''),
        'cantidad' => $lineQty,
        'gross' => $lineGross,
        'base' => $lineBase,
        'impuesto' => $lineTax,
        'descuento' => $lineDiscount,
        'total' => $lineTotal,
    ];

    if ($lineTax <= 0.0001) {
        continue;
    }

    $rate = $lineBase > 0.0001 ? round(($lineTax / $lineBase) * 100, 2) : 0.0;
    $rateKey = number_format($rate, 2, '.', '');

    if (!isset($taxSummary[$rateKey])) {
        $taxSummary[$rateKey] = [
            'base' => 0.0,
            'impuesto' => 0.0,
            'tasa' => $rate,
        ];
    }

    $taxSummary[$rateKey]['base'] += $lineBase;
    $taxSummary[$rateKey]['impuesto'] += $lineTax;
}
ksort($taxSummary, SORT_NATURAL);

if ($taxSummary !== []) {
    $summaryTaxSum = 0.0;
    foreach ($taxSummary as $row) {
        $summaryTaxSum += (float) ($row['impuesto'] ?? 0);
    }
    $taxDifference = round($taxes - $summaryTaxSum, 2);
    if (abs($taxDifference) >= 0.01) {
        end($taxSummary);
        $lastKey = key($taxSummary);
        if ($lastKey !== null && isset($taxSummary[$lastKey])) {
            $taxSummary[$lastKey]['impuesto'] = round((float) ($taxSummary[$lastKey]['impuesto'] ?? 0) + $taxDifference, 2);
            $rateDenominator = max(0.0001, (float) ($taxSummary[$lastKey]['tasa'] ?? 0));
            if ($rateDenominator > 0.0001) {
                $taxSummary[$lastKey]['base'] = round(((float) $taxSummary[$lastKey]['impuesto'] * 100) / $rateDenominator, 2);
            }
        }
        reset($taxSummary);
    }
}

$discountLabel = $discount > 0.0001 ? $discount : $lineDiscountTotal;
$taxableBase = max(0.0, round($subtotal - $discountLabel, 2));
$computedTotal = round($taxableBase + $taxes, 2);
$finalTotal = abs($computedTotal - $total) <= 0.02 ? $total : $computedTotal;
$itemsLabel = (int) round($totalItems) > 0 ? (int) round($totalItems) : count($details);
$hasFeEvidence = $cufe !== '' || $qrPath !== '';
$showElectronicContext = $hasFeEvidence;
$hasResolutionData = $resolutionNumber !== ''
    || $resolutionPrefix !== ''
    || $resolutionRangeFrom !== ''
    || $resolutionRangeTo !== ''
    || $resolutionDateFrom !== ''
    || $resolutionDateTo !== '';
$showResolutionBlock = $hasResolutionData && ($showElectronicContext || !$factusConfigured);
?>

<style>
    .ticket-wrap {
        width: 80mm;
        max-width: 100%;
        margin: 0 auto;
        font-family: "Courier New", Courier, monospace;
        font-size: 11px;
        line-height: 1.3;
        color: #111;
    }
    .ticket-divider,
    .ticket-divider-thin {
        border-top: 1px dashed #333;
        margin: 6px 0;
    }
    .ticket-divider-thin {
        border-top-color: #777;
        margin: 4px 0;
    }
    .ticket-center {
        text-align: center;
    }
    .ticket-title {
        text-transform: uppercase;
        font-weight: 700;
        letter-spacing: 0.3px;
    }
    .ticket-row {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 8px;
    }
    .ticket-row-label {
        color: #222;
    }
    .ticket-row-value {
        text-align: right;
        white-space: nowrap;
    }
    .ticket-compact {
        font-size: 10px;
    }
    .ticket-products-head {
        display: grid;
        grid-template-columns: 1fr auto;
        gap: 8px;
        font-weight: 700;
        text-transform: uppercase;
    }
    .ticket-product {
        margin-bottom: 4px;
    }
    .ticket-product-desc {
        display: block;
        word-break: break-word;
    }
    .ticket-product-meta {
        margin-top: 1px;
        font-size: 9px;
        color: #333;
    }
    .ticket-save {
        text-align: center;
        font-weight: 800;
        font-size: 15px;
        letter-spacing: 0.2px;
        margin: 8px 0 3px;
    }
    .ticket-total-block {
        text-align: center;
        margin: 4px 0;
    }
    .ticket-total-label {
        font-size: 10px;
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }
    .ticket-total-value {
        font-size: 17px;
        font-weight: 800;
        line-height: 1.15;
    }
    .ticket-tax-head,
    .ticket-tax-row {
        display: grid;
        grid-template-columns: 44px 56px 44px 1fr;
        gap: 6px;
        align-items: baseline;
    }
    .ticket-tax-head {
        font-weight: 700;
        text-transform: uppercase;
    }
    .ticket-tax-row span:nth-child(2),
    .ticket-tax-row span:nth-child(4) {
        text-align: right;
    }
    .ticket-tax-row span {
        white-space: nowrap;
    }
    .ticket-footer-title {
        text-transform: uppercase;
        font-weight: 700;
        text-align: center;
        letter-spacing: 0.25px;
    }
    .ticket-footer-block {
        font-size: 10px;
        line-height: 1.25;
    }
    .ticket-footer-line {
        margin: 1px 0;
    }
    .ticket-footer-line-cufe {
        word-break: break-all;
        overflow-wrap: anywhere;
        line-height: 1.2;
    }
    .ticket-footer-line strong {
        font-weight: 700;
    }
    .ticket-qrcode {
        margin: 7px auto 5px;
        width: 108px;
        height: 108px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .ticket-qrcode img {
        max-width: 108px;
        max-height: 108px;
        width: 100%;
        height: 100%;
        object-fit: contain;
        image-rendering: pixelated;
    }
    .ticket-muted {
        color: #333;
    }
    @media print {
        @page {
            size: 80mm auto;
            margin: 2mm;
        }
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-3 d-print-none">
    <h1 class="h6 mb-0">Ticket fiscal</h1>
    <div class="d-flex gap-2">
        <button class="btn btn-sm btn-primary" type="button" onclick="window.print()">Imprimir</button>
        <a class="btn btn-sm btn-light" href="<?= e(url('ventas/' . (int) ($document['venta_id'] ?? 0))) ?>">Volver</a>
    </div>
</div>

<div class="ticket-wrap">
    <div class="ticket-center ticket-compact">
        <strong><?= e((string) ($document['empresa_nombre'] ?? 'Veltrix POS')) ?></strong><br>
        NIT: <?= e((string) ($document['empresa_nit'] ?? '-')) ?><br>
        <?= e((string) ($document['empresa_direccion'] ?? '-')) ?><br>
        Tel: <?= e((string) ($document['empresa_telefono'] ?? '-')) ?><br>
        Local: <?= e((string) ($document['sucursal_nombre'] ?? 'Sucursal general')) ?>
    </div>

    <div class="ticket-divider"></div>

    <div class="ticket-title ticket-center"><?= e($docLabel) ?></div>
    <div class="ticket-divider-thin"></div>
    <div class="ticket-compact">
        <div class="ticket-row">
            <span class="ticket-row-label">Ticket</span>
            <span class="ticket-row-value"><?= e((string) ($document['numero'] ?? '-')) ?></span>
        </div>
        <div class="ticket-row">
            <span class="ticket-row-label">Fecha</span>
            <span class="ticket-row-value"><?= e($saleDate !== '' ? $saleDate : '-') ?></span>
        </div>
        <div class="ticket-row">
            <span class="ticket-row-label">Hora</span>
            <span class="ticket-row-value"><?= e($saleTime !== '' ? $saleTime : '-') ?></span>
        </div>
        <div class="ticket-row">
            <span class="ticket-row-label">Cajero</span>
            <span class="ticket-row-value"><?= e((string) ($document['cajero'] ?? '-')) ?></span>
        </div>
        <div class="ticket-row">
            <span class="ticket-row-label">Cliente</span>
            <span class="ticket-row-value"><?= e((string) ($document['cliente_documento'] ?? '-')) ?></span>
        </div>
        <div class="ticket-center"><?= e((string) ($document['cliente_nombre'] ?? 'Consumidor final')) ?></div>
    </div>

    <div class="ticket-divider"></div>

    <div class="ticket-products-head">
        <span>Descripcion</span>
        <span>Importe</span>
    </div>
    <div class="ticket-divider-thin"></div>

    <?php foreach ($lineItems as $line): ?>
        <div class="ticket-product">
            <div class="ticket-row">
                <span class="ticket-product-desc">
                    <?= e(number_format((float) ($line['cantidad'] ?? 0), 2, '.', '')) ?>x
                    <?= e((string) ($line['descripcion'] ?? '')) ?>
                </span>
                <span class="ticket-row-value"><?= e(money((float) ($line['total'] ?? 0))) ?></span>
            </div>
            <div class="ticket-product-meta">
                <?php if ((float) ($line['descuento'] ?? 0) > 0.0001): ?>
                    Desc: -<?= e(money((float) ($line['descuento'] ?? 0))) ?> |
                <?php endif; ?>
                IVA: <?= e(money((float) ($line['impuesto'] ?? 0))) ?> |
                Bruto: <?= e(money((float) ($line['gross'] ?? 0))) ?>
            </div>
        </div>
    <?php endforeach; ?>

    <?php if ($lineItems === []): ?>
        <div class="ticket-center">Sin líneas registradas</div>
    <?php endif; ?>

    <div class="ticket-divider"></div>

    <div class="ticket-row">
        <span class="ticket-row-label">Subtotal bruto</span>
        <span class="ticket-row-value"><?= e(money($subtotal)) ?></span>
    </div>
    <?php if ($discountLabel > 0.0001): ?>
        <div class="ticket-save">AHORRO: -<?= e(money($discountLabel)) ?></div>
    <?php endif; ?>
    <div class="ticket-row">
        <span class="ticket-row-label">Base gravable</span>
        <span class="ticket-row-value"><?= e(money($taxableBase)) ?></span>
    </div>
    <div class="ticket-row">
        <span class="ticket-row-label">IVA</span>
        <span class="ticket-row-value"><?= e(money($taxes)) ?></span>
    </div>

    <div class="ticket-total-block">
        <div class="ticket-total-label">Total</div>
        <div class="ticket-total-value"><?= e(money($finalTotal)) ?></div>
        <div class="ticket-compact"><?= e((string) $itemsLabel) ?> articulos</div>
    </div>

    <div class="ticket-divider"></div>

    <div class="ticket-title ticket-center">Pago</div>
    <div class="ticket-divider-thin"></div>
    <div class="ticket-row">
        <span class="ticket-row-label"><?= e($paymentMethods !== '' ? $paymentMethods : 'Sin método') ?></span>
        <span class="ticket-row-value"><?= e(money($paid > 0 ? $paid : $finalTotal)) ?></span>
    </div>

    <div class="ticket-divider"></div>
    <div class="ticket-tax-head ticket-compact">
        <span>Tasa</span>
        <span>Importe</span>
        <span>Tipo</span>
        <span>Base IVA excl.</span>
    </div>
    <div class="ticket-divider-thin"></div>
    <?php if ($taxSummary !== []): ?>
        <?php foreach ($taxSummary as $row): ?>
            <div class="ticket-tax-row ticket-compact">
                <span>IVA</span>
                <span><?= e(money((float) ($row['impuesto'] ?? 0))) ?></span>
                <span><?= e(number_format((float) ($row['tasa'] ?? 0), 0, ',', '.')) ?>%</span>
                <span><?= e(money((float) ($row['base'] ?? 0))) ?></span>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="ticket-tax-row ticket-compact">
            <span>IVA</span>
            <span><?= e(money(0)) ?></span>
            <span>0%</span>
            <span><?= e(money(0)) ?></span>
        </div>
    <?php endif; ?>

    <div class="ticket-divider"></div>

    <div class="ticket-compact">
        <div class="ticket-row">
            <span class="ticket-row-label">Impuestos</span>
            <span class="ticket-row-value"><?= e(money($taxes)) ?></span>
        </div>
        <div class="ticket-row">
            <span class="ticket-row-label">Estado</span>
            <span class="ticket-row-value"><?= e((string) ($document['estado'] ?? 'emitida')) ?></span>
        </div>
    </div>

    <?php if ($showResolutionBlock): ?>
        <div class="ticket-divider"></div>

        <div class="ticket-footer-title">Autorizacion numeracion de facturacion</div>
        <div class="ticket-footer-block">
            <div class="ticket-footer-line">
                <strong>Numero:</strong>
                <?= e($resolutionNumber !== '' ? $resolutionNumber : 'Sin configurar') ?>
            </div>
            <div class="ticket-footer-line">
                <strong>Numeracion:</strong>
                <?= e($resolutionNumber !== '' ? 'AUTORIZADA' : 'PENDIENTE CONFIGURACION') ?>
            </div>
            <div class="ticket-footer-line">
                <strong>Rango:</strong>
                desde <?= e(($resolutionPrefix !== '' ? $resolutionPrefix : '') . ($resolutionRangeFrom !== '' ? $resolutionRangeFrom : '?')) ?>
                hasta <?= e(($resolutionPrefix !== '' ? $resolutionPrefix : '') . ($resolutionRangeTo !== '' ? $resolutionRangeTo : '?')) ?>
            </div>
            <?php if ($resolutionDateFrom !== '' || $resolutionDateTo !== ''): ?>
                <div class="ticket-footer-line">
                    <strong>Vigencia:</strong>
                    desde <?= e($resolutionDateFrom !== '' ? $resolutionDateFrom : '-') ?>
                </div>
                <div class="ticket-footer-line">
                    hasta <?= e($resolutionDateTo !== '' ? $resolutionDateTo : '-') ?>
                    <?= $resolutionMonths !== '' ? ' - ' . e($resolutionMonths) : '' ?>
                </div>
            <?php endif; ?>
        </div>

        <div class="ticket-divider-thin"></div>
    <?php endif; ?>

    <div class="ticket-center ticket-footer-block ticket-muted">
        <?php if ($fiscalRegime !== ''): ?>
            <div class="ticket-footer-line">Regimen fiscal: <?= e($fiscalRegime) ?></div>
        <?php endif; ?>
        <?php if ($fiscalActivity !== ''): ?>
            <div class="ticket-footer-line">Actividad economica: <?= e($fiscalActivity) ?></div>
        <?php endif; ?>
        <?php if ($isVatResponsible): ?>
            <div class="ticket-footer-line">Responsable de IVA</div>
        <?php endif; ?>
        <?php if ($showElectronicContext && $cufe !== ''): ?>
            <div class="ticket-footer-line ticket-footer-line-cufe"><strong>CUFE:</strong> <?= e($cufe) ?></div>
        <?php endif; ?>
    </div>

    <?php if ($showElectronicContext && $qrImageSrc !== ''): ?>
        <div class="ticket-qrcode">
            <img
                src="<?= e($qrImageSrc) ?>"
                alt="QR Factura electrónica"
                onerror="<?php if ($qrFallbackSrc !== ''): ?>this.onerror=function(){this.style.display='none';};this.src='<?= e($qrFallbackSrc) ?>';<?php else: ?>this.style.display='none';<?php endif; ?>"
            >
        </div>
    <?php elseif ($showElectronicContext && $qrPath !== ''): ?>
        <div class="ticket-center ticket-compact ticket-muted">
            QR: <?= e($qrPath) ?>
        </div>
    <?php endif; ?>

    <div class="ticket-center ticket-footer-block">
        <?php if ($showElectronicContext): ?>
            <div class="ticket-footer-line">
                <strong>Elaborado:</strong> <?= e($softwareName !== '' ? $softwareName : 'VELTRIX POS') ?>
            </div>
            <div class="ticket-footer-line">
                <strong>Proveedor tecnologico:</strong> <?= e($techProviderName) ?>
                <?= $techProviderNit !== '' ? ' NIT: ' . e($techProviderNit) : '' ?>
            </div>
            <div class="ticket-footer-line">
                <strong>Software:</strong> <?= e($softwareName !== '' ? $softwareName : 'VELTRIX POS') ?>
            </div>
            <?php if ($softwareMakerName !== ''): ?>
                <div class="ticket-footer-line">
                    <strong>Fabricante:</strong> <?= e($softwareMakerName) ?>
                    <?= $softwareMakerNit !== '' ? ' NIT: ' . e($softwareMakerNit) : '' ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
        <div class="ticket-divider-thin"></div>
        Gracias por su compra<br>
        <?php if ($showElectronicContext): ?>
            Consulte su factura electrónica en su portal.
        <?php endif; ?>
    </div>
</div>
<?php /**PATH /Applications/XAMPP/xamppfiles/htdocs/veltrix-v2/resources/views/modules/facturacion/ticket.blade.php ENDPATH**/ ?>