@extends('layouts.app')

@section('title', 'POS | Veltrix v2')

@section('topbar_actions')
    <button
        type="button"
        class="btn btn-primary btn-sm vx-topbar-action d-inline-flex align-items-center gap-1"
        data-bs-toggle="modal"
        data-bs-target="#posCustomerModal"
        @if (! ($pos_enabled ?? false)) disabled @endif
    >
        <i class="bx bx-user-plus"></i>
        <span>Nuevo cliente</span>
    </button>
@endsection

@section('content')
<?php
$posEnabled = (bool) ($pos_enabled ?? false);
$posBlockReason = trim((string) ($pos_block_reason ?? ''));
$userBranchId = (int) ($user_branch_id ?? 0);
$invoiceRangeAlert = is_array($invoice_range_alert ?? null) ? $invoice_range_alert : null;
$opening = is_array($opening ?? null) ? $opening : null;
$products = is_array($products ?? null) ? $products : [];
$productVariantsMap = is_array($product_variants_map ?? null) ? $product_variants_map : [];
$customers = is_array($customers ?? null) ? $customers : [];
$paymentMethods = is_array($payment_methods ?? null) ? $payment_methods : [];
$autoPosEnabled = (bool) ($autoPosEnabled ?? false);

if ($paymentMethods === []) {
    $paymentMethods = [
        ['codigo' => 'efectivo', 'nombre' => 'Efectivo'],
        ['codigo' => 'tarjeta', 'nombre' => 'Tarjeta'],
        ['codigo' => 'transferencia', 'nombre' => 'Transferencia'],
    ];
}

$selectedCustomerId = trim((string) old('cliente_id', ''));
$selectedSaleType = strtolower(trim((string) old('tipo_venta', 'contado')));
if (!in_array($selectedSaleType, ['contado', 'credito'], true)) {
    $selectedSaleType = 'contado';
}
$selectedPaymentMethod = strtolower(trim((string) old('metodo_pago', 'efectivo')));
$paymentCodes = array_map(
    static fn (array $method): string => strtolower(trim((string) ($method['codigo'] ?? ''))),
    $paymentMethods
);
$paymentCodes = array_values(array_filter($paymentCodes, static fn (string $code): bool => $code !== ''));
if (!in_array($selectedPaymentMethod, $paymentCodes, true)) {
    $selectedPaymentMethod = $paymentCodes[0] ?? 'efectivo';
}
$selectedDiscountMode = strtolower(trim((string) old('descuento_modo', 'valor')));
if (!in_array($selectedDiscountMode, ['valor', 'porcentaje'], true)) {
    $selectedDiscountMode = 'valor';
}
$selectedDiscount = trim((string) old('descuento', '0'));
$selectedPaymentReference = trim((string) old('referencia_pago', ''));
$selectedAbono = trim((string) old('abono_inicial', '0'));
$selectedPaymentRequiresReference = in_array($selectedPaymentMethod, ['bold', 'bold_dataphone', 'bold_button', 'credibanco', 'credibanco_dataphone', 'credibanco_datafono'], true);

$productCategories = [];
foreach ($products as $product) {
    $categoryName = trim((string) ($product['categoria'] ?? ''));
    if ($categoryName === '') {
        $categoryName = 'Sin categoria';
    }

    $categoryKey = strtolower((string) preg_replace('/[^a-z0-9]+/i', '-', $categoryName));
    $categoryKey = trim($categoryKey, '-');
    if ($categoryKey === '') {
        $categoryKey = 'sin-categoria';
    }

    if (!isset($productCategories[$categoryKey])) {
        $productCategories[$categoryKey] = [
            'name' => $categoryName,
            'count' => 0,
        ];
    }

    $productCategories[$categoryKey]['count']++;
}

uasort($productCategories, static function (array $a, array $b): int {
    return strcmp((string) ($a['name'] ?? ''), (string) ($b['name'] ?? ''));
});

$topbar_actions = [
    [
        'type' => 'modal',
        'label' => 'Nuevo cliente',
        'icon' => 'bx bx-user-plus',
        'class' => 'btn btn-primary btn-sm vx-topbar-action',
        'target_modal' => '#posCustomerModal',
        'disabled' => !$posEnabled,
    ],
];
$show_company_switcher = false;
?>

<form action="<?= e(url('pos/vender')) ?>" method="post" id="posForm" data-enabled="<?= $posEnabled ? '1' : '0' ?>">
    <?= csrf_field() ?>

    <div class="row g-3 vx-pos-modern">
        <div class="col-xl-8">
            <div class="card border-0 shadow-sm vx-pos-panel">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                        <div>
                            <h1 class="h4 mb-1">Punto de venta</h1>
                            <p class="text-muted mb-0 small">Selecciona productos del catálogo y gestiona el checkout en tiempo real.</p>
                        </div>
                        <span class="badge rounded-pill text-bg-light border vx-pos-pill">
                            <i class="bx bx-package me-1"></i><?= e((string) count($products)) ?> productos
                        </span>
                    </div>

                    <?php if ($invoiceRangeAlert !== null): ?>
                        <?php
                        $alertLevel = (string) ($invoiceRangeAlert['level'] ?? 'warning');
                        $alertClass = $alertLevel === 'danger' ? 'alert-danger' : 'alert-warning';
                        ?>
                        <div class="alert <?= e($alertClass) ?>">
                            <?= e((string) ($invoiceRangeAlert['message'] ?? 'Alerta de facturación.')) ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($posBlockReason !== ''): ?>
                        <div class="alert alert-danger"><?= e($posBlockReason) ?></div>
                    <?php elseif (!$opening): ?>
                        <div class="alert alert-warning">Debes abrir caja antes de vender.</div>
                    <?php endif; ?>

                    <div class="row g-2 vx-pos-controls mb-3">
                        <div class="col-xxl-4 col-xl-4 col-lg-5 col-md-6">
                            <label class="form-label mb-1" for="cliente_id">Cliente</label>
                            <select class="form-select" name="cliente_id" id="cliente_id" <?= !$posEnabled ? 'disabled' : '' ?>>
                                <option value="" data-documento="" data-documento-visible="" data-nombre="Consumidor final" data-telefono="" data-email="" <?= $selectedCustomerId === '' ? 'selected' : '' ?>>
                                    Consumidor final
                                </option>
                                <?php foreach ($customers as $customer): ?>
                                    <?php
                                    $customerId = (string) ($customer['id'] ?? '');
                                    $customerName = trim((string) ($customer['nombre'] ?? ''));
                                    $customerDocument = trim((string) ($customer['documento'] ?? ''));
                                    $documentSearchKey = strtolower((string) preg_replace('/[^A-Za-z0-9]/', '', $customerDocument));
                                    $customerPhone = trim((string) ($customer['telefono'] ?? ''));
                                    $customerEmail = trim((string) ($customer['email'] ?? ''));
                                    $customerLabel = $customerName;
                                    if ($customerDocument !== '') {
                                        $customerLabel .= ' (' . $customerDocument . ')';
                                    }
                                    ?>
                                    <option
                                        value="<?= e($customerId) ?>"
                                        data-documento="<?= e($documentSearchKey) ?>"
                                        data-documento-visible="<?= e($customerDocument) ?>"
                                        data-nombre="<?= e($customerName) ?>"
                                        data-telefono="<?= e($customerPhone) ?>"
                                        data-email="<?= e($customerEmail) ?>"
                                        <?= $selectedCustomerId === $customerId ? 'selected' : '' ?>
                                    >
                                        <?= e($customerLabel) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-xxl-2 col-xl-2 col-lg-2 col-md-6">
                            <label class="form-label">Tipo venta</label>
                            <select class="form-select" name="tipo_venta" id="tipo_venta" <?= !$posEnabled ? 'disabled' : '' ?>>
                                <option value="contado" <?= $selectedSaleType === 'contado' ? 'selected' : '' ?>>Contado</option>
                                <option value="credito" <?= $selectedSaleType === 'credito' ? 'selected' : '' ?>>Credito</option>
                            </select>
                        </div>

                        <div class="col-xxl-2 col-xl-2 col-lg-2 col-md-6">
                            <label class="form-label">Método pago</label>
                            <select class="form-select" name="metodo_pago" id="metodo_pago" <?= !$posEnabled ? 'disabled' : '' ?>>
                                <?php foreach ($paymentMethods as $method): ?>
                                    <?php
                                    $methodCode = strtolower(trim((string) ($method['codigo'] ?? '')));
                                    $methodName = trim((string) ($method['nombre'] ?? $methodCode));
                                    if ($methodCode === '' || $methodName === '') {
                                        continue;
                                    }
                                    ?>
                                    <option value="<?= e($methodCode) ?>" <?= $selectedPaymentMethod === $methodCode ? 'selected' : '' ?>>
                                        <?= e($methodName) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div
                            class="col-xxl-3 col-xl-3 col-lg-3 col-md-6 <?= !$selectedPaymentRequiresReference ? 'd-none' : '' ?>"
                            id="paymentReferenceContainer"
                        >
                            <label class="form-label" for="referencia_pago">Ref. transacción</label>
                            <input
                                type="text"
                                class="form-control"
                                name="referencia_pago"
                                id="referencia_pago"
                                value="<?= e($selectedPaymentReference) ?>"
                                placeholder="Id transacción datáfono"
                                autocomplete="off"
                                <?= !$posEnabled ? 'disabled' : '' ?>
                            >
                        </div>

                        <div
                            class="col-xxl-3 col-xl-3 col-lg-3 col-md-6 <?= $selectedPaymentMethod === 'efectivo' ? '' : 'd-none' ?>"
                            id="cashAmountContainer"
                        >
                            <label class="form-label" for="pago_cliente">Pago del cliente</label>
                            <input
                                type="number"
                                class="form-control"
                                id="pago_cliente"
                                name="pago_cliente"
                                inputmode="numeric"
                                min="0"
                                step="1"
                                placeholder="0"
                                autocomplete="off"
                                <?= !$posEnabled ? 'disabled' : '' ?>
                            >
                        </div>

                        <div class="col-xxl-3 col-xl-4 col-lg-4 col-md-6 vx-pos-discount-col">
                            <label class="form-label text-nowrap">Descuento global</label>
                            <input type="hidden" name="descuento" id="descuento" value="<?= e($selectedDiscount === '' ? '0' : $selectedDiscount) ?>">
                            <input type="hidden" name="descuento_modo" id="descuento_modo" value="<?= e($selectedDiscountMode) ?>">
                            <div class="input-group vx-pos-discount-group">
                                <select class="form-select" id="descuento_modo_selector" <?= !$posEnabled ? 'disabled' : '' ?>>
                                    <option value="valor" <?= $selectedDiscountMode === 'valor' ? 'selected' : '' ?>>$</option>
                                    <option value="porcentaje" <?= $selectedDiscountMode === 'porcentaje' ? 'selected' : '' ?>>%</option>
                                </select>
                                <input
                                    type="text"
                                    class="form-control vx-pos-discount-input"
                                    id="descuento_display"
                                    inputmode="decimal"
                                    autocomplete="off"
                                    placeholder="0"
                                    maxlength="11"
                                    <?= !$posEnabled ? 'disabled' : '' ?>
                                >
                            </div>
                        </div>

                        <div class="col-xxl-3 col-xl-4 col-lg-4 col-md-6 <?= $selectedSaleType !== 'credito' ? 'd-none' : '' ?>" id="abonoContainer">
                            <label class="form-label">Abono inicial</label>
                            <input
                                type="number"
                                class="form-control"
                                step="0.01"
                                min="0"
                                value="<?= e($selectedAbono === '' ? '0' : $selectedAbono) ?>"
                                name="abono_inicial"
                                id="abono_inicial"
                                <?= !$posEnabled ? 'disabled' : '' ?>
                            >
                        </div>

                        <div class="col-12">
                            <small class="d-block text-muted vx-pos-customer-info mt-1" id="cliente_info">Consumidor final.</small>
                        </div>
                    </div>

                    <div class="alert alert-info py-2 px-3 mb-3 <?= $selectedSaleType === 'credito' ? '' : 'd-none' ?>" id="creditNotice">
                        En venta a credito debes seleccionar cliente. El saldo queda en cuentas por cobrar.
                    </div>

                    <div class="vx-pos-toolbar mb-3">
                        <div class="input-group">
                            <span class="input-group-text bg-white border-end-0"><i class="bx bx-search"></i></span>
                            <input
                                type="search"
                                id="productSearchInput"
                                class="form-control border-start-0"
                                placeholder="Buscar producto por nombre, SKU, código o categoría..."
                                autocomplete="off"
                                <?= !$posEnabled ? 'disabled' : '' ?>
                            >
                            <button class="btn btn-outline-secondary" type="button" id="clearProductSearch" <?= !$posEnabled ? 'disabled' : '' ?>>Limpiar</button>
                        </div>
                    </div>

                    <div class="vx-pos-category-tabs mb-3" id="categoryTabs">
                        <button type="button" class="vx-pos-category-btn is-active" data-category="all" <?= !$posEnabled ? 'disabled' : '' ?>>
                            Todas <span><?= e((string) count($products)) ?></span>
                        </button>
                        <?php foreach ($productCategories as $categoryKey => $category): ?>
                            <button type="button" class="vx-pos-category-btn" data-category="<?= e($categoryKey) ?>" <?= !$posEnabled ? 'disabled' : '' ?>>
                                <?= e((string) ($category['name'] ?? 'Categoria')) ?>
                                <span><?= e((string) ((int) ($category['count'] ?? 0))) ?></span>
                            </button>
                        <?php endforeach; ?>
                    </div>

                    <div class="vx-pos-grid" id="productGrid">
                        <?php foreach ($products as $product): ?>
                            <?php
                            $productId = (int) ($product['id'] ?? 0);
                            $productName = trim((string) ($product['nombre'] ?? 'Producto'));
                            $productSku = trim((string) ($product['sku'] ?? ''));
                            $productBarcode = trim((string) ($product['codigo_barras'] ?? ''));
                            $productCategory = trim((string) ($product['categoria'] ?? ''));
                            if ($productCategory === '') {
                                $productCategory = 'Sin categoria';
                            }
                            $productCategoryKey = strtolower((string) preg_replace('/[^a-z0-9]+/i', '-', $productCategory));
                            $productCategoryKey = trim($productCategoryKey, '-');
                            if ($productCategoryKey === '') {
                                $productCategoryKey = 'sin-categoria';
                            }
                            $productPrice = (float) ($product['precio_venta'] ?? 0);
                            $productStock = (float) ($product['stock_actual'] ?? 0);
                            $productMaxQty = (int) floor($productStock);
                            $productVariants = is_array($productVariantsMap[$productId] ?? null) ? $productVariantsMap[$productId] : [];
                            $productVariants = array_values(array_filter($productVariants, static function (array $variant): bool {
                                return (int) ($variant['activo'] ?? 0) === 1;
                            }));
                            $variantsPayload = array_map(static function (array $variant): array {
                                $variantStockRaw = $variant['cantidad'] ?? null;
                                $variantStock = null;
                                if ($variantStockRaw !== null && $variantStockRaw !== '') {
                                    $variantStock = (int) $variantStockRaw;
                                }

                                return [
                                    'id' => (int) ($variant['id'] ?? 0),
                                    'nombre' => (string) ($variant['nombre'] ?? ''),
                                    'precio_venta' => (float) ($variant['precio_venta'] ?? 0),
                                    'cantidad' => $variantStock,
                                ];
                            }, $productVariants);
                            $variantsJson = json_encode($variantsPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                            if (!is_string($variantsJson)) {
                                $variantsJson = '[]';
                            }
                            $variantsCount = count($variantsPayload);
                            $searchIndex = strtolower(trim($productName . ' ' . $productSku . ' ' . $productBarcode . ' ' . $productCategory));
                            $cardDisabled = !$posEnabled || $productMaxQty < 1;
                            ?>
                            <button
                                type="button"
                                class="vx-pos-product-card <?= $cardDisabled ? 'is-disabled' : '' ?>"
                                data-product-id="<?= e((string) $productId) ?>"
                                data-name="<?= e($productName) ?>"
                                data-price="<?= e((string) $productPrice) ?>"
                                data-stock="<?= e((string) $productStock) ?>"
                                data-tax-rate="<?= e((string) ((float) ($product['impuesto_porcentaje'] ?? 0))) ?>"
                                data-category="<?= e($productCategoryKey) ?>"
                                data-search="<?= e($searchIndex) ?>"
                                data-has-variants="<?= $variantsCount > 0 ? '1' : '0' ?>"
                                data-variants="<?= e($variantsJson) ?>"
                                <?= $cardDisabled ? 'disabled' : '' ?>
                            >
                                <div class="vx-pos-product-image-wrap">
                                    <img src="<?= e(product_image_url((string) ($product['imagen'] ?? ''))) ?>" alt="<?= e($productName) ?>" class="vx-pos-product-image">
                                </div>
                                <div class="vx-pos-product-body">
                                    <h3 class="vx-pos-product-name" title="<?= e($productName) ?>"><?= e($productName) ?></h3>
                                    <div class="vx-pos-product-meta">
                                        <?php if ($productSku !== ''): ?>
                                            <span>SKU <?= e($productSku) ?></span>
                                        <?php else: ?>
                                            <span><?= e($productCategory) ?></span>
                                        <?php endif; ?>
                                        <strong><?= e(money($productPrice)) ?></strong>
                                    </div>
                                    <?php if ($variantsCount > 0): ?>
                                        <span class="vx-pos-variant-badge">
                                            <i class="bx bx-slider-alt me-1"></i><?= e((string) $variantsCount) ?> variaciones
                                        </span>
                                    <?php endif; ?>
                                    <small class="text-muted">Stock <?= e((string) $productMaxQty) ?></small>
                                </div>
                            </button>
                        <?php endforeach; ?>
                    </div>

                    <div class="text-center text-muted py-4 border rounded-3 d-none" id="noProductResults">
                        No se encontraron productos con ese criterio.
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-4">
            <div class="card border-0 shadow-sm vx-pos-panel vx-pos-checkout-card mb-3">
                <div class="card-body d-flex flex-column">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h2 class="h6 mb-0">Checkout</h2>
                        <span class="badge rounded-pill text-bg-light border" id="cartItemsCount">0 items</span>
                    </div>

                    <div class="vx-pos-checkout-list" id="checkoutList"></div>
                    <div class="text-center text-muted py-4 border rounded-3" id="checkoutEmpty">
                        Tu carrito está vacío.
                    </div>

                    <div class="vx-pos-summary mt-3">
                        <div class="vx-pos-summary-row">
                            <span>Subtotal</span>
                            <strong id="checkoutSubtotal">$0.00</strong>
                        </div>
                        <div class="vx-pos-summary-row">
                            <span>Descuento total</span>
                            <strong id="checkoutDiscountDisplay">$0.00</strong>
                        </div>
                        <div class="vx-pos-summary-row">
                            <span>Impuestos</span>
                            <strong id="checkoutTaxes">$0.00</strong>
                        </div>
                        <div class="vx-pos-summary-row vx-pos-summary-total">
                            <span>Total</span>
                            <strong id="checkoutTotal">$0.00</strong>
                        </div>
                        <div class="d-none mt-3 rounded-3 p-3 text-center" id="cashChangeRow" style="background: #d1fae5; border: 2px solid #10b981;">
                            <div class="text-success fw-semibold mb-1" style="font-size: 0.85rem; letter-spacing: 0.03em; text-transform: uppercase;">
                                <i class="bx bx-refresh me-1"></i>Cambio a devolver
                            </div>
                            <div id="cashChangeAmount" class="fw-bold text-success" style="font-size: 2rem; line-height: 1.1;">$0.00</div>
                        </div>
                    </div>

                    <div id="cartHiddenContainer"></div>

                    @if ($autoPosEnabled)
                        {{-- Auto mode ON: always create, no toggle shown --}}
                        <input type="hidden" name="generar_envio" value="1">
                    @else
                        {{-- Manual mode: toggle appears only when a client is selected --}}
                        <div id="posEnvioBox" class="d-none mt-3 px-3 py-2 rounded-3"
                             style="background:#f0f9ff;border:1px solid #bae6fd">
                            <div class="d-flex align-items-center justify-content-between gap-2">
                                <div>
                                    <div class="fw-semibold" style="font-size:.82rem;color:#0369a1">
                                        <i class="bx bxs-truck me-1"></i>Generar envío
                                    </div>
                                    <div style="font-size:.72rem;color:#64748b">La gente de despacho recibirá esta orden</div>
                                </div>
                                <div class="form-check form-switch mb-0 ms-2 flex-shrink-0">
                                    <input class="form-check-input" type="checkbox" role="switch"
                                           id="generarEnvioCheck" name="generar_envio" value="1"
                                           style="width:2.2rem;height:1.15rem;cursor:pointer" checked
                                           <?= !$posEnabled ? 'disabled' : '' ?>>
                                </div>
                            </div>
                        </div>
                    @endif

                    <div class="d-grid gap-2 mt-3">
                        <button class="btn btn-outline-secondary" type="button" id="clearCart" <?= !$posEnabled ? 'disabled' : '' ?>>
                            Limpiar orden
                        </button>
                        <button class="btn btn-success" type="submit" id="checkoutSubmit" <?= !$posEnabled ? 'disabled' : '' ?>>
                            Registrar venta
                        </button>
                    </div>
                </div>
            </div>

        </div>
    </div>
</form>

<div class="modal fade" id="posVariantModal" tabindex="-1" aria-labelledby="posVariantModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h2 class="h6 mb-0" id="posVariantModalLabel">Seleccionar variación</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="mb-2">
                    <strong id="posVariantProductName">Producto</strong>
                    <small class="d-block text-muted" id="posVariantHelper">Selecciona los atributos para agregar al checkout.</small>
                </div>
                <div class="row g-2" id="posVariantAttributesContainer"></div>
                <div class="row g-2 mt-1">
                    <div class="col-md-6">
                        <label class="form-label">Precio</label>
                        <input type="text" class="form-control" id="posVariantPriceDisplay" value="$0.00" readonly>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Cantidad</label>
                        <input type="number" class="form-control" id="posVariantQtyInput" min="1" step="1" value="1" autocomplete="off">
                    </div>
                </div>
                <div class="mt-2">
                    <span class="badge text-bg-light border" id="posVariantStockBadge">Stock: 0</span>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
                <button class="btn btn-primary" type="button" id="posVariantAddButton">
                    <i class="bx bx-plus me-1"></i>Agregar al checkout
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="posCustomerModal" tabindex="-1" aria-labelledby="posCustomerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <form id="posCustomerForm" data-create-url="<?= e(route('pos.customers.store')) ?>">
                <div class="modal-header">
                    <h2 class="h6 mb-0" id="posCustomerModalLabel">Nuevo cliente</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="_token" value="<?= e(csrf_token()) ?>">
                    <div class="row g-2">
                        <div class="col-12">
                            <label class="form-label">Nombre</label>
                            <input class="form-control" name="nombre" maxlength="150" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Cédula / Documento</label>
                            <input class="form-control" name="documento" maxlength="60">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Teléfono</label>
                            <input class="form-control" name="telefono" maxlength="40">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Email</label>
                            <input class="form-control" type="email" name="email" maxlength="150">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Dirección</label>
                            <input class="form-control" name="direccion" maxlength="255">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
                    <button class="btn btn-primary" type="submit">
                        <i class="bx bx-save me-1"></i>Crear cliente
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
$salePostedId = (int) session('sale_posted_id', 0);
$salePostedTotal = (float) session('sale_posted_total', 0);
$salePostedPagoCliente = (float) session('sale_posted_pago_cliente', 0);
$salePostedCambio = (float) session('sale_posted_cambio', 0);
$salePostedMetodoPago = strtolower((string) session('sale_posted_metodo_pago', ''));
$saleIsCash = $salePostedMetodoPago === 'efectivo';
$fmtCop = static fn (float $value): string => '$' . number_format($value, 0, ',', '.');
?>
<style>
    #posSaleSuccessModal .vx-sale-success-card { border-radius: 18px; overflow: hidden; }
    #posSaleSuccessModal .vx-sale-success-hero {
        background: linear-gradient(135deg, #ecfdf5 0%, #dbeafe 100%);
        padding: 2rem 1.5rem 1.5rem;
        text-align: center;
    }
    #posSaleSuccessModal .vx-sale-success-icon {
        width: 88px; height: 88px;
        background: #fff;
        border: 4px solid #a7f3d0;
        box-shadow: 0 10px 25px -10px rgba(16, 185, 129, 0.45);
    }
    #posSaleSuccessModal .vx-sale-success-icon i { font-size: 2.75rem; color: #10b981; }
    #posSaleSuccessModal .vx-sale-ticket-pill {
        display: inline-flex; align-items: center; gap: .35rem;
        background: rgba(16, 185, 129, .12); color: #047857;
        padding: .25rem .75rem; border-radius: 999px;
        font-weight: 600; font-size: .8rem; letter-spacing: .02em;
    }
    #posSaleSuccessModal .vx-sale-change-card {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: #fff; border-radius: 14px;
        padding: 1.25rem 1.5rem;
        box-shadow: 0 12px 30px -12px rgba(16, 185, 129, .55);
    }
    #posSaleSuccessModal .vx-sale-change-label {
        text-transform: uppercase; letter-spacing: .12em;
        font-size: .72rem; opacity: .9;
    }
    #posSaleSuccessModal .vx-sale-change-amount {
        font-size: 2.5rem; font-weight: 800; line-height: 1.1;
    }
    #posSaleSuccessModal .vx-sale-summary {
        background: #f8fafc; border-radius: 12px;
        padding: .85rem 1rem;
    }
    #posSaleSuccessModal .vx-sale-summary-row {
        display: flex; justify-content: space-between; align-items: center;
        font-size: .9rem; padding: .25rem 0;
    }
    #posSaleSuccessModal .vx-sale-summary-row + .vx-sale-summary-row { border-top: 1px dashed #e2e8f0; }
    #posSaleSuccessModal .vx-sale-summary-row span:first-child { color: #64748b; }
    #posSaleSuccessModal .vx-sale-summary-row span:last-child { font-weight: 600; color: #0f172a; }
    #posSaleSuccessModal .vx-sale-actions .btn {
        border-radius: 10px; font-weight: 500;
    }
</style>
<div class="modal fade" id="posSaleSuccessModal" tabindex="-1" aria-labelledby="posSaleSuccessLabel" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow vx-sale-success-card">
            <div class="vx-sale-success-hero">
                <div class="vx-sale-success-icon mx-auto mb-3 d-flex align-items-center justify-content-center rounded-circle">
                    <i class="bx bx-check"></i>
                </div>
                <h2 class="h3 fw-bold mb-1" id="posSaleSuccessLabel">¡Venta registrada!</h2>
                <p class="text-muted small mb-2">La operación se procesó correctamente.</p>
                <span class="vx-sale-ticket-pill" id="posSaleSuccessTicket">
                    <i class="bx bx-receipt"></i>
                    <span>Ticket #<?= e($salePostedId) ?></span>
                </span>
            </div>

            <div class="modal-body p-4 pt-3">
                <div class="vx-sale-change-card mb-3 <?= $saleIsCash ? '' : 'd-none' ?>" id="posSaleChangeCard">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <div class="vx-sale-change-label">Cambio a devolver</div>
                            <div class="vx-sale-change-amount" id="posSaleChangeAmount"><?= e($fmtCop($salePostedCambio)) ?></div>
                        </div>
                        <i class="bx bx-money-withdraw" style="font-size: 3rem; opacity: .6;"></i>
                    </div>
                </div>

                <div class="vx-sale-summary mb-3">
                    <div class="vx-sale-summary-row">
                        <span><i class="bx bx-credit-card me-1"></i>Método de pago</span>
                        <span class="text-capitalize" id="posSaleMetodoPago"><?= e($salePostedMetodoPago !== '' ? $salePostedMetodoPago : '—') ?></span>
                    </div>
                    <div class="vx-sale-summary-row">
                        <span><i class="bx bx-purchase-tag me-1"></i>Total venta</span>
                        <span id="posSaleTotal"><?= e($fmtCop($salePostedTotal)) ?></span>
                    </div>
                    <div class="vx-sale-summary-row <?= $saleIsCash ? '' : 'd-none' ?>" id="posSalePagoClienteRow">
                        <span><i class="bx bx-wallet me-1"></i>Recibido</span>
                        <span id="posSalePagoCliente"><?= e($fmtCop($salePostedPagoCliente)) ?></span>
                    </div>
                </div>

                <div class="d-grid mb-3">
                    <button type="button" class="btn btn-primary btn-lg" data-bs-dismiss="modal" id="posSaleSuccessContinue">
                        <i class="bx bx-check-circle me-1"></i> Continuar
                    </button>
                </div>

                <div class="vx-sale-actions d-flex flex-wrap gap-2 justify-content-center">
                    <a href="#" target="_blank" rel="noopener" class="btn btn-outline-primary btn-sm" data-sale-action="factura-print">
                        <i class="bx bx-printer me-1"></i>Imprimir factura
                    </a>
                    <a href="<?= e(route('pos.index')) ?>" class="btn btn-outline-primary btn-sm">
                        <i class="bx bx-plus me-1"></i>Nueva venta
                    </a>
                    <a href="#" target="_blank" rel="noopener" class="btn btn-outline-primary btn-sm" data-sale-action="ticket-print">
                        <i class="bx bx-receipt me-1"></i>Imprimir ticket
                    </a>
                    <a href="#" class="btn btn-outline-primary btn-sm" data-sale-action="factura-pdf">
                        <i class="bx bx-download me-1"></i>Descargar PDF
                    </a>
                    <a href="<?= e(route('ventas.index')) ?>" class="btn btn-outline-primary btn-sm">
                        <i class="bx bx-history me-1"></i>Ver historial
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/css/tom-select.bootstrap5.min.css">
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/js/tom-select.complete.min.js"></script>
<script src="<?= e(asset('assets/js/pos.js')) ?>"></script>

@if ($salePostedId > 0)
<script>
(function () {
    const saleId = {{ (int) $salePostedId }};
    const urls = {
        'factura-print': "{{ url('ventas') }}/" + saleId + "/factura/imprimir",
        'factura-pdf': "{{ url('ventas') }}/" + saleId + "/factura/pdf",
        'ticket-print': "{{ url('ventas') }}/" + saleId + "/ticket/imprimir",
    };
    const modalEl = document.getElementById('posSaleSuccessModal');
    if (!modalEl) return;
    modalEl.querySelectorAll('[data-sale-action]').forEach((el) => {
        const key = el.getAttribute('data-sale-action');
        if (urls[key]) el.setAttribute('href', urls[key]);
    });
    const show = () => {
        if (window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(modalEl).show();
        }
    };
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', show, { once: true });
    } else {
        show();
    }
})();
</script>
@endif

@if (!$autoPosEnabled)
<script>
(function () {
    const clienteSelect = document.getElementById('cliente_id');
    const envioBox      = document.getElementById('posEnvioBox');
    if (!clienteSelect || !envioBox) return;

    function syncEnvioBox() {
        const hasCliente = clienteSelect.value !== '';
        envioBox.classList.toggle('d-none', !hasCliente);
    }

    clienteSelect.addEventListener('change', syncEnvioBox);

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', syncEnvioBox);
    } else {
        syncEnvioBox();
    }
})();
</script>
@endif

@endsection
