<?php
$document = is_array($document ?? null) ? $document : (is_array($invoice ?? null) ? $invoice : []);
$invoice = $document;
$details = is_array($details ?? null) ? $details : [];
$pdfFallback = (bool) ($pdf_fallback ?? false);
$docType = (string) ($invoice['tipo_documento'] ?? 'factura');
$docLabel = $docType === 'nota_credito'
    ? 'Nota crédito'
    : ($docType === 'nota_debito' ? 'Nota débito' : 'Factura de venta');
$docReference = (string) ($invoice['documento_referencia_numero'] ?? '');
$subtotal = (float) ($invoice['subtotal'] ?? 0);
$discount = (float) ($invoice['venta_descuento'] ?? 0);
$taxes = (float) ($invoice['impuestos'] ?? 0);
$total = (float) ($invoice['total'] ?? 0);
$taxableBase = max(0.0, round($subtotal - $discount, 2));
$cufe = trim((string) ($invoice['cufe'] ?? ''));
$qrPath = trim((string) ($invoice['qr_path'] ?? ''));
$qrImageSrc = '';
$qrDisplayLink = '';

if ($qrPath !== '') {
    if (preg_match('/^data:image\//i', $qrPath) === 1) {
        $qrImageSrc = $qrPath;
    } elseif (preg_match('/^https?:\/\//i', $qrPath) === 1) {
        $parsedPath = (string) (parse_url($qrPath, PHP_URL_PATH) ?? '');
        $extension = strtolower((string) pathinfo($parsedPath, PATHINFO_EXTENSION));
        $isImageUrl = in_array($extension, ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'], true);
        if ($isImageUrl) {
            $qrImageSrc = $qrPath;
        } else {
            $qrDisplayLink = $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;
}

$companyLogoPath = trim((string) ($invoice['empresa_logo'] ?? ''));
$companyLogoSrc = '';
if ($companyLogoPath !== '') {
    $publicLogoPath = base_path('public/' . ltrim($companyLogoPath, '/'));
    if (is_file($publicLogoPath) && is_readable($publicLogoPath)) {
        $mimeType = '';
        if (function_exists('mime_content_type')) {
            $detected = @mime_content_type($publicLogoPath);
            if (is_string($detected) && $detected !== '') {
                $mimeType = $detected;
            }
        }

        if ($mimeType === '') {
            $extension = strtolower((string) pathinfo($publicLogoPath, PATHINFO_EXTENSION));
            $mimeType = match ($extension) {
                'jpg', 'jpeg' => 'image/jpeg',
                'png' => 'image/png',
                'webp' => 'image/webp',
                'gif' => 'image/gif',
                default => 'application/octet-stream',
            };
        }

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

    if ($companyLogoSrc === '') {
        $companyLogoSrc = url($companyLogoPath);
    }
}

$taxSummary = [];
foreach ($details as $line) {
    $lineTax = (float) ($line['impuesto'] ?? 0);
    if ($lineTax <= 0.0001) {
        continue;
    }

    $lineTotal = (float) ($line['total_linea'] ?? 0);
    $lineBase = max(0.0, $lineTotal - $lineTax);
    $rate = $lineBase > 0.0001 ? round(($lineTax / $lineBase) * 100, 2) : 0.0;
    $rateKey = number_format($rate, 2, '.', '');

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

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

<style>
    .invoice-fe-meta {
        font-size: 0.95rem;
    }
    .invoice-fe-meta .invoice-cufe {
        overflow-wrap: anywhere;
        word-break: break-word;
        line-height: 1.35;
    }
    .invoice-fe-meta .invoice-link {
        overflow-wrap: anywhere;
        word-break: break-word;
    }
    .invoice-fe-qr img {
        max-width: 140px;
        max-height: 140px;
        border: 1px solid #e6e9f1;
        border-radius: 10px;
        padding: 4px;
        background: #fff;
    }
    @media print {
        .invoice-fe-qr img {
            max-width: 120px;
            max-height: 120px;
        }
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4 d-print-none">
    <div>
        <h1 class="h4 mb-0"><?= e($docLabel) ?></h1>
        <small class="text-muted">Veltrix POS</small>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-primary" type="button" onclick="window.print()">Imprimir</button>
        <?php if ($pdfFallback): ?>
            <a class="btn btn-success" href="#" onclick="window.print(); return false;">Guardar como PDF</a>
        <?php endif; ?>
        <a class="btn btn-light" href="<?= e(url('ventas/' . (int) ($invoice['venta_id'] ?? 0))) ?>">Volver</a>
    </div>
</div>
<?php if ($pdfFallback): ?>
    <div class="alert alert-warning d-print-none">
        No hay motor PDF instalado en el servidor. Usa "Guardar como PDF" desde la impresión del navegador.
    </div>
<?php endif; ?>

<div class="mb-4">
    <div class="row g-2">
        <div class="col-md-6">
            <?php if ($companyLogoSrc !== ''): ?>
                <div class="mb-2">
                    <img src="<?= e($companyLogoSrc) ?>" alt="Logo empresa" style="max-height: 72px; width: auto;">
                </div>
            <?php endif; ?>
            <h2 class="h6 mb-2">Empresa</h2>
            <div><strong><?= e((string) ($invoice['empresa_nombre'] ?? '')) ?></strong></div>
            <div>NIT: <?= e((string) ($invoice['empresa_nit'] ?? '-')) ?></div>
            <div>Email: <?= e((string) ($invoice['empresa_email'] ?? '-')) ?></div>
            <div>Teléfono: <?= e((string) ($invoice['empresa_telefono'] ?? '-')) ?></div>
            <div>Dirección: <?= e((string) ($invoice['empresa_direccion'] ?? '-')) ?></div>
        </div>
        <div class="col-md-6 text-md-end">
            <h2 class="h6 mb-2">Documento</h2>
            <div><strong><?= e($docLabel) ?>: <?= e((string) ($invoice['numero'] ?? '')) ?></strong></div>
            <div>Estado: <?= e((string) ($invoice['estado'] ?? 'emitida')) ?></div>
            <div>Fecha emisión: <?= e((string) ($invoice['fecha_emision'] ?? '')) ?></div>
            <?php if ($docReference !== ''): ?>
                <div>Referencia: <?= e($docReference) ?></div>
            <?php endif; ?>
            <div>Sucursal: <?= e((string) ($invoice['sucursal_nombre'] ?? 'General')) ?></div>
            <div>Cajero: <?= e((string) ($invoice['cajero'] ?? '-')) ?></div>
            <?php if ($cufe !== '' || $qrImageSrc !== '' || $qrDisplayLink !== ''): ?>
                <div class="invoice-fe-meta mt-2 p-2 border rounded bg-light text-start text-md-end">
                    <?php if ($cufe !== ''): ?>
                        <div class="invoice-cufe"><strong>CUFE:</strong> <?= e($cufe) ?></div>
                    <?php endif; ?>
                    <?php if ($qrDisplayLink !== ''): ?>
                        <div class="invoice-link">
                            <strong>Consulta DIAN:</strong>
                            <a href="<?= e($qrDisplayLink) ?>" target="_blank" rel="noopener">Abrir enlace</a>
                        </div>
                    <?php endif; ?>
                    <?php if ($qrImageSrc !== ''): ?>
                        <div class="invoice-fe-qr mt-2">
                            <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 endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php if ((string) ($invoice['motivo_documento'] ?? '') !== ''): ?>
    <div class="mb-3">
        <h2 class="h6 mb-2">Motivo del documento</h2>
        <p class="mb-0"><?= e((string) $invoice['motivo_documento']) ?></p>
    </div>
<?php endif; ?>

<?php if ((string) ($invoice['estado'] ?? '') === 'anulada'): ?>
    <div class="alert alert-secondary">
        Documento anulado<?= (string) ($invoice['anulado_at'] ?? '') !== '' ? ' el ' . e((string) $invoice['anulado_at']) : '' ?>.
        <?php if ((string) ($invoice['anulado_motivo'] ?? '') !== ''): ?>
            Motivo: <?= e((string) $invoice['anulado_motivo']) ?>.
        <?php endif; ?>
    </div>
<?php endif; ?>

<div class="mb-4">
    <h2 class="h6 mb-2">Cliente</h2>
    <div class="row g-2">
        <div class="col-md-6">Nombre: <?= e((string) ($invoice['cliente_nombre'] ?? 'Consumidor final')) ?></div>
        <div class="col-md-6">Documento: <?= e((string) ($invoice['cliente_documento'] ?? '-')) ?></div>
        <div class="col-md-6">Email: <?= e((string) ($invoice['cliente_email'] ?? '-')) ?></div>
        <div class="col-md-6">Teléfono: <?= e((string) ($invoice['cliente_telefono'] ?? '-')) ?></div>
    </div>
</div>

<div class="mb-4">
    <h2 class="h6 mb-2">Detalle</h2>
    <table class="table table-bordered table-sm">
        <thead>
        <tr>
            <th>Descripción</th>
            <th class="text-end">Cantidad</th>
            <th class="text-end">Precio</th>
            <th class="text-end">Impuesto</th>
            <th class="text-end">Total</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($details as $line): ?>
            <tr>
                <td><?= e((string) ($line['descripcion'] ?? '')) ?></td>
                <td class="text-end"><?= e((string) ($line['cantidad'] ?? '0')) ?></td>
                <td class="text-end"><?= e(money((float) ($line['precio_unitario'] ?? 0))) ?></td>
                <td class="text-end"><?= e(money((float) ($line['impuesto'] ?? 0))) ?></td>
                <td class="text-end"><?= e(money((float) ($line['total_linea'] ?? 0))) ?></td>
            </tr>
        <?php endforeach; ?>
        <?php if (empty($details)): ?>
            <tr>
                <td colspan="5" class="text-center text-muted">Sin líneas de detalle.</td>
            </tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if ($taxSummary !== []): ?>
    <div class="mb-4">
        <h2 class="h6 mb-2">Operación de impuestos</h2>
        <table class="table table-bordered table-sm">
            <thead>
            <tr>
                <th>Tipo</th>
                <th class="text-end">Tasa</th>
                <th class="text-end">Base</th>
                <th class="text-end">Importe</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($taxSummary as $taxRow): ?>
                <tr>
                    <td>IVA</td>
                    <td class="text-end"><?= e(number_format((float) ($taxRow['tasa'] ?? 0), 2, ',', '.')) ?>%</td>
                    <td class="text-end"><?= e(money((float) ($taxRow['base'] ?? 0))) ?></td>
                    <td class="text-end"><?= e(money((float) ($taxRow['impuesto'] ?? 0))) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<div class="row g-2 justify-content-end">
    <div class="col-md-4">
        <table class="table table-bordered table-sm">
            <tbody>
            <tr>
                <th>Subtotal</th>
                <td class="text-end"><?= e(money($subtotal)) ?></td>
            </tr>
            <tr>
                <th>Descuento</th>
                <td class="text-end">-<?= e(money($discount)) ?></td>
            </tr>
            <tr>
                <th>Base gravable</th>
                <td class="text-end"><?= e(money($taxableBase)) ?></td>
            </tr>
            <tr>
                <th>Impuestos</th>
                <td class="text-end"><?= e(money($taxes)) ?></td>
            </tr>
            <tr>
                <th>Total</th>
                <td class="text-end"><strong><?= e(money($total)) ?></strong></td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
