<?php $__env->startSection('title', 'Venta | Veltrix v2'); ?>

<?php $__env->startSection('content'); ?>
<?php
$sale = is_array($sale ?? null) ? $sale : [];
$documents = is_array($documents ?? null) ? $documents : [];
$trailTotals = is_array($trail_totals ?? null) ? $trail_totals : [];
$saleId = (int) ($sale['id'] ?? 0);
$saleStatus = strtolower(trim((string) ($sale['estado'] ?? 'pendiente')));
$paymentMethodsRaw = strtolower(trim((string) ($sale['metodos_pago'] ?? '')));
$paymentMethods = array_values(array_filter(array_map(
    static fn (string $method): string => trim($method),
    explode(',', $paymentMethodsRaw)
), static fn (string $method): bool => $method !== ''));
$isCredibancoDataphone = false;
foreach ($paymentMethods as $methodCode) {
    if (in_array($methodCode, ['credibanco', 'credibanco_dataphone', 'credibanco_datafono'], true)) {
        $isCredibancoDataphone = true;
        break;
    }
}
$printBlockedByWebhook = $isCredibancoDataphone && $saleStatus !== 'pagada';

$topbarSaleTitle = $saleId > 0 ? ('Venta #'.$saleId) : 'Venta';
?>

<?php $__env->startSection('page_title', $topbarSaleTitle); ?>
<?php $__env->startSection('page_subtitle', 'Gestion operativa en tiempo real'); ?>
<?php $__env->startSection('page_icon', 'bx bxs-receipt'); ?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h1 class="h5 mb-0">Trazabilidad documental de la venta #<?= e((string) $saleId) ?></h1>
    <a class="btn btn-sm btn-light" href="<?= e(url('ventas')) ?>">Volver a ventas</a>
</div>

<?php if ($printBlockedByWebhook): ?>
    <div class="alert alert-warning">
        Esta venta está pendiente de confirmación por webhook de Credibanco. La impresión de ticket/factura se habilita al aprobarse el pago.
    </div>
<?php endif; ?>

<div class="row g-3 mb-3">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h2 class="h6">Resumen de la venta</h2>
                <div class="row g-2 small">
                    <div class="col-md-3"><strong>Documento:</strong> <?= e((string) ($sale['documento_numero'] ?? ('POS-' . $saleId))) ?></div>
                    <div class="col-md-3"><strong>Fecha:</strong> <?= e((string) ($sale['fecha'] ?? '')) ?></div>
                    <div class="col-md-3"><strong>Sucursal:</strong> <?= e((string) ($sale['sucursal'] ?? 'Sin sucursal')) ?></div>
                    <div class="col-md-3"><strong>Cajero:</strong> <?= e((string) ($sale['cajero'] ?? '-')) ?></div>
                    <div class="col-md-4"><strong>Cliente:</strong> <?= e((string) ($sale['cliente'] ?? 'Consumidor final')) ?></div>
                    <div class="col-md-4"><strong>Total venta:</strong> <?= e(money((float) ($sale['total'] ?? 0))) ?></div>
                    <div class="col-md-4"><strong>Estado cobro:</strong> <?= e((string) ($sale['estado_pago'] ?? 'pendiente')) ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h2 class="h6">Balance documental</h2>
                <p class="mb-1">Facturado: <strong><?= e(money((float) ($trailTotals['total_facturado'] ?? 0))) ?></strong></p>
                <p class="mb-1">Notas crédito: <strong class="text-danger"><?= e(money((float) ($trailTotals['total_notas_credito'] ?? 0))) ?></strong></p>
                <p class="mb-1">Notas débito: <strong class="text-success"><?= e(money((float) ($trailTotals['total_notas_debito'] ?? 0))) ?></strong></p>
                <p class="mb-0">Neto documental: <strong><?= e(money((float) ($trailTotals['total_neto_documental'] ?? 0))) ?></strong></p>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-lg-6">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h2 class="h6 mb-3">Emitir nota crédito</h2>
                <?php if (has_permission('facturacion.notas')): ?>
                    <form action="<?= e(url('ventas/' . $saleId . '/nota-credito')) ?>" method="post" class="row g-2">
                        <?= csrf_field() ?>
                        <div class="col-md-4">
                            <label class="form-label">Monto</label>
                            <input type="number" step="0.01" min="0.01" name="monto" class="form-control" required>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label">Motivo</label>
                            <input type="text" name="motivo" class="form-control" required maxlength="255" placeholder="Devolución parcial, descuento posterior, etc.">
                        </div>
                        <div class="col-12">
                            <button class="btn btn-outline-danger btn-sm" type="submit">Emitir nota crédito</button>
                        </div>
                    </form>
                <?php else: ?>
                    <p class="text-muted mb-0">Sin permiso para emitir notas.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h2 class="h6 mb-3">Emitir nota débito</h2>
                <?php if (has_permission('facturacion.notas')): ?>
                    <form action="<?= e(url('ventas/' . $saleId . '/nota-debito')) ?>" method="post" class="row g-2">
                        <?= csrf_field() ?>
                        <div class="col-md-4">
                            <label class="form-label">Monto</label>
                            <input type="number" step="0.01" min="0.01" name="monto" class="form-control" required>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label">Motivo</label>
                            <input type="text" name="motivo" class="form-control" required maxlength="255" placeholder="Recargo, ajuste posterior, etc.">
                        </div>
                        <div class="col-12">
                            <button class="btn btn-outline-success btn-sm" type="submit">Emitir nota débito</button>
                        </div>
                    </form>
                <?php else: ?>
                    <p class="text-muted mb-0">Sin permiso para emitir notas.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <h2 class="h6 mb-3">Documentos de la venta</h2>
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Tipo</th>
                    <th>Número</th>
                    <th>Referencia</th>
                    <th>Total</th>
                    <th>Estado</th>
                    <th>Motivo</th>
                    <th>Fecha</th>
                    <th>Acciones</th>
                </tr>
                </thead>
                <tbody>
                <?php if ($documents === []): ?>
                    <tr><td colspan="9" class="text-center text-muted">No hay documentos asociados.</td></tr>
                <?php endif; ?>
                <?php foreach ($documents as $doc): ?>
                    <?php
                    $docId = (int) ($doc['id'] ?? 0);
                    $docType = (string) ($doc['tipo_documento'] ?? 'factura');
                    $typeLabel = $docType === 'nota_credito'
                        ? 'Nota crédito'
                        : ($docType === 'nota_debito' ? 'Nota débito' : 'Factura');
                    $typeBadge = $docType === 'nota_credito'
                        ? 'text-bg-danger'
                        : ($docType === 'nota_debito' ? 'text-bg-success' : 'text-bg-primary');
                    $isCanceled = (string) ($doc['estado'] ?? '') === 'anulada';
                    ?>
                    <tr>
                        <td><?= e((string) $docId) ?></td>
                        <td><span class="badge <?= e($typeBadge) ?>"><?= e($typeLabel) ?></span></td>
                        <td><?= e((string) ($doc['numero'] ?? '')) ?></td>
                        <td><?= e((string) ($doc['documento_referencia_numero'] ?? '-')) ?></td>
                        <td><?= e(money((float) ($doc['total'] ?? 0))) ?></td>
                        <td>
                            <span class="badge <?= $isCanceled ? 'text-bg-secondary' : 'text-bg-success' ?>">
                                <?= e((string) ($doc['estado'] ?? 'emitida')) ?>
                            </span>
                        </td>
                        <td><?= e((string) (($doc['motivo_documento'] ?? '') !== '' ? $doc['motivo_documento'] : ($doc['anulado_motivo'] ?? '-'))) ?></td>
                        <td><?= e((string) ($doc['fecha_emision'] ?? '')) ?></td>
                        <td>
                            <?php if ($printBlockedByWebhook): ?>
                                <button class="btn btn-sm btn-outline-secondary" type="button" disabled>Imprimir</button>
                                <button class="btn btn-sm btn-outline-secondary mt-1 mt-md-0" type="button" disabled>PDF</button>
                            <?php else: ?>
                                <a class="btn btn-sm btn-outline-primary" target="_blank" rel="noopener" href="<?= e(url('ventas/' . $saleId . '/documentos/' . $docId . '/imprimir')) ?>">Imprimir</a>
                                <a class="btn btn-sm btn-outline-success mt-1 mt-md-0" target="_blank" rel="noopener" href="<?= e(url('ventas/' . $saleId . '/documentos/' . $docId . '/pdf')) ?>">PDF</a>
                            <?php endif; ?>
                            <?php if (!$isCanceled && has_permission('facturacion.anular_documento')): ?>
                                <form action="<?= e(url('ventas/' . $saleId . '/documentos/' . $docId . '/anular')) ?>" method="post" class="mt-1">
                                    <?= csrf_field() ?>
                                    <input type="text" class="form-control form-control-sm mb-1" name="motivo_anulacion" placeholder="Motivo anulación" required maxlength="255">
                                    <button class="btn btn-sm btn-outline-danger w-100" type="submit">Anular documento</button>
                                </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Applications/XAMPP/xamppfiles/htdocs/veltrix-v2/resources/views/modules/ventas/show.blade.php ENDPATH**/ ?>