<?php
$orders = is_array($orders ?? null) ? $orders : [];
$orderDetailsMap = is_array($order_details ?? null) ? $order_details : [];
$orderReceptionsMap = is_array($order_receptions ?? null) ? $order_receptions : [];
$productVariantsMap = is_array($product_variants_map ?? null) ? $product_variants_map : [];
?>

<div class="row g-3 mb-3">
    <div class="col-md-4">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Total compras</span>
                <h2 class="h4 mb-0"><?= e(money($summary['total_compras'] ?? 0)) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Total pagado</span>
                <h2 class="h4 mb-0 text-success"><?= e(money($summary['total_pagado'] ?? 0)) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Saldo por pagar</span>
                <h2 class="h4 mb-0 text-danger"><?= e(money($summary['total_saldo'] ?? 0)) ?></h2>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
        <h2 class="h5 mb-3">Órdenes de compra y recepciones parciales</h2>
        <div class="vx-oc-table-wrap">
            <table class="table table-hover align-middle mb-0 vx-oc-table">
                <thead>
                <tr>
                    <th>OC</th>
                    <th>Proveedor</th>
                    <th>Total</th>
                    <th>Progreso</th>
                    <th>Estado</th>
                    <th class="text-center">Acción</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($orders as $order): ?>
                    <?php
                    $orderId = (int) ($order['id'] ?? 0);
                    $orderedQty = (float) ($order['cantidad_ordenada'] ?? 0);
                    $receivedQty = (float) ($order['cantidad_recibida'] ?? 0);
                    $progressPct = $orderedQty > 0 ? min(100, max(0, ($receivedQty / $orderedQty) * 100)) : 0;
                    $progressPctLabel = number_format($progressPct, 0, '.', '');
                    $orderedQtyLabel = number_format($orderedQty, 2, '.', '');
                    $receivedQtyLabel = number_format($receivedQty, 2, '.', '');
                    $pendingQtyLabel = number_format(max(0, $orderedQty - $receivedQty), 2, '.', '');
                    $status = strtolower(trim((string) ($order['estado'] ?? 'abierta')));
                    $statusLabel = match ($status) {
                        'completa' => 'Completa',
                        'parcial' => 'Parcial',
                        'anulada' => 'Anulada',
                        default => 'Abierta',
                    };
                    $statusClass = match ($status) {
                        'completa' => 'text-bg-success',
                        'parcial' => 'text-bg-warning',
                        'anulada' => 'text-bg-secondary',
                        default => 'text-bg-primary',
                    };
                    $orderCode = (string) ($order['numero'] ?? ('OC-' . $orderId));
                    $supplierName = trim((string) ($order['proveedor'] ?? ''));
                    $detailModalId = 'orderDetailModal' . $orderId;
                    ?>
                    <tr>
                        <td>
                            <div class="vx-oc-code">
                                <span><?= e($orderCode) ?></span>
                                <small class="text-muted">#<?= e((string) $orderId) ?></small>
                            </div>
                        </td>
                        <td>
                            <div class="fw-semibold"><?= e($supplierName !== '' ? $supplierName : 'Sin proveedor') ?></div>
                        </td>
                        <td>
                            <span class="vx-oc-total"><?= e(money((float) ($order['total'] ?? 0))) ?></span>
                        </td>
                        <td>
                            <div class="vx-oc-progress">
                                <div class="progress">
                                    <div class="progress-bar" role="progressbar" style="width: <?= e(number_format($progressPct, 2, '.', '')) ?>%"></div>
                                </div>
                                <div class="vx-oc-progress-meta">
                                    <span><?= e($receivedQtyLabel) ?> / <?= e($orderedQtyLabel) ?></span>
                                    <span><?= e($progressPctLabel) ?>%</span>
                                </div>
                                <small class="text-muted d-block">Pendiente: <?= e($pendingQtyLabel) ?></small>
                            </div>
                        </td>
                        <td>
                            <span class="badge vx-oc-state-badge <?= e($statusClass) ?>">
                                <?= e($statusLabel) ?>
                            </span>
                        </td>
                        <td class="text-center">
                            <div class="vx-oc-actions">
                                <button
                                    class="btn btn-sm btn-outline-primary vx-oc-icon-btn"
                                    type="button"
                                    data-bs-toggle="modal"
                                    data-bs-target="#<?= e($detailModalId) ?>"
                                    title="<?= e($status !== 'completa' && $status !== 'anulada' ? 'Ver / recibir' : 'Ver detalle') ?>"
                                    aria-label="<?= e($status !== 'completa' && $status !== 'anulada' ? 'Ver / recibir' : 'Ver detalle') ?>"
                                >
                                    <i class="bx bx-show-alt"></i>
                                    <span class="visually-hidden"><?= e($status !== 'completa' && $status !== 'anulada' ? 'Ver / recibir' : 'Ver detalle') ?></span>
                                </button>
                                <a
                                    class="btn btn-sm btn-outline-dark vx-oc-icon-btn"
                                    href="<?= e(url('compras/ordenes/' . $orderId . '/pdf')) ?>"
                                    target="_blank"
                                    rel="noopener"
                                    title="Descargar PDF"
                                    aria-label="Descargar PDF"
                                >
                                    <i class="bx bxs-file-pdf"></i>
                                    <span class="visually-hidden">Descargar PDF</span>
                                </a>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($orders)): ?>
                    <tr>
                        <td colspan="6" class="text-center text-muted">No hay órdenes de compra registradas.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php foreach ($orders as $order): ?>
            <?php
            $orderId = (int) ($order['id'] ?? 0);
            $orderedQty = (float) ($order['cantidad_ordenada'] ?? 0);
            $receivedQty = (float) ($order['cantidad_recibida'] ?? 0);
            $pendingQtyLabel = number_format(max(0, $orderedQty - $receivedQty), 2, '.', '');
            $orderedQtyLabel = number_format($orderedQty, 2, '.', '');
            $receivedQtyLabel = number_format($receivedQty, 2, '.', '');
            $details = is_array($orderDetailsMap[$orderId] ?? null) ? $orderDetailsMap[$orderId] : [];
            $receptions = is_array($orderReceptionsMap[$orderId] ?? null) ? $orderReceptionsMap[$orderId] : [];
            $canReceive = (string) ($order['estado'] ?? '') !== 'anulada' && (string) ($order['estado'] ?? '') !== 'completa';
            $orderDateRaw = trim((string) ($order['fecha'] ?? ''));
            $orderDate = $orderDateRaw;
            $orderTime = '';
            if ($orderDateRaw !== '') {
                $orderTimestamp = strtotime($orderDateRaw);
                if ($orderTimestamp !== false) {
                    $orderDate = date('Y-m-d', $orderTimestamp);
                    $orderTime = date('H:i', $orderTimestamp);
                }
            }
            $status = strtolower(trim((string) ($order['estado'] ?? 'abierta')));
            $statusLabel = match ($status) {
                'completa' => 'Completa',
                'parcial' => 'Parcial',
                'anulada' => 'Anulada',
                default => 'Abierta',
            };
            $statusClass = match ($status) {
                'completa' => 'text-bg-success',
                'parcial' => 'text-bg-warning',
                'anulada' => 'text-bg-secondary',
                default => 'text-bg-primary',
            };
            $orderCode = (string) ($order['numero'] ?? ('OC-' . $orderId));
            $supplierName = trim((string) ($order['proveedor'] ?? ''));
            $branchName = trim((string) ($order['sucursal'] ?? ''));
            if ($branchName === '') {
                $branchName = 'Sin sucursal';
            }
            $detailModalId = 'orderDetailModal' . $orderId;
            ?>
            <div class="modal fade" id="<?= e($detailModalId) ?>" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-xl modal-dialog-scrollable">
                    <div class="modal-content border-0 shadow">
                        <div class="modal-header">
                            <h2 class="h6 mb-0">
                                Orden <?= e($orderCode) ?> · <?= e($statusLabel) ?>
                            </h2>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row g-2 mb-3">
                                <div class="col-md-4"><strong>Proveedor:</strong> <?= e($supplierName !== '' ? $supplierName : 'Sin proveedor') ?></div>
                                <div class="col-md-4"><strong>Sucursal:</strong> <?= e($branchName) ?></div>
                                <div class="col-md-4"><strong>Fecha:</strong> <?= e($orderDate) ?><?= $orderTime !== '' ? ' ' . e($orderTime) : '' ?></div>
                                <div class="col-md-4"><strong>Total:</strong> <?= e(money((float) ($order['total'] ?? 0))) ?></div>
                                <div class="col-md-4"><strong>Ordenado:</strong> <?= e($orderedQtyLabel) ?></div>
                                <div class="col-md-4"><strong>Recibido:</strong> <?= e($receivedQtyLabel) ?> · <strong>Pendiente:</strong> <?= e($pendingQtyLabel) ?></div>
                                <div class="col-md-4">
                                    <strong>Estado:</strong>
                                    <span class="badge vx-oc-state-badge <?= e($statusClass) ?> ms-1"><?= e($statusLabel) ?></span>
                                </div>
                            </div>

                            <div class="row g-3 vx-oc-detail-panel">
                                <div class="col-lg-8">
                                    <h3 class="h6">Recepción parcial</h3>
                                    <?php if ($canReceive): ?>
                                        <form action="<?= e(url('compras/ordenes/' . $orderId . '/recibir')) ?>" method="post">
                                            <?= csrf_field() ?>
                                            <div class="table-responsive">
                                                <table class="table table-sm table-bordered">
                                                    <thead>
                                                    <tr>
                                                        <th>Producto</th>
                                                        <th>Ordenado</th>
                                                        <th>Recibido</th>
                                                        <th>Pendiente</th>
                                                        <th>Recibir ahora</th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    <?php foreach ($details as $detail): ?>
                                                        <?php $pending = max(0, (float) ($detail['cantidad_pendiente'] ?? 0)); ?>
                                                        <tr>
                                                            <td>
                                                                <?= e((string) ($detail['producto'] ?? '')) ?>
                                                                <?php if (!empty($detail['variante_nombre'])): ?>
                                                                    <small class="d-block text-muted">Variante: <?= e((string) $detail['variante_nombre']) ?></small>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td><?= e((string) ($detail['cantidad'] ?? 0)) ?></td>
                                                            <td><?= e((string) ($detail['cantidad_recibida'] ?? 0)) ?></td>
                                                            <td><?= e((string) $pending) ?></td>
                                                            <td>
                                                                <input
                                                                    type="number"
                                                                    step="1"
                                                                    min="0"
                                                                    max="<?= e((string) max(0, (int) floor($pending))) ?>"
                                                                    class="form-control form-control-sm"
                                                                    name="recibir_cantidad[<?= e((string) $detail['id']) ?>]"
                                                                    value="0"
                                                                >
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                            <div class="row g-2">
                                                <div class="col-md-9">
                                                    <input class="form-control form-control-sm" name="recepcion_observacion" placeholder="Observación de recepción (opcional)">
                                                </div>
                                                <div class="col-md-3">
                                                    <button class="btn btn-sm btn-success w-100" type="submit">Registrar recepción</button>
                                                </div>
                                            </div>
                                        </form>
                                    <?php else: ?>
                                        <div class="alert alert-secondary mb-0">Esta orden no admite nuevas recepciones.</div>
                                    <?php endif; ?>
                                </div>
                                <div class="col-lg-4">
                                    <h3 class="h6">Recepciones registradas</h3>
                                    <ul class="list-group list-group-flush">
                                        <?php foreach ($receptions as $reception): ?>
                                            <li class="list-group-item px-0 py-2">
                                                <strong><?= e((string) ($reception['numero_recepcion'] ?? '')) ?></strong><br>
                                                <small class="text-muted"><?= e((string) ($reception['fecha_recepcion'] ?? '')) ?></small><br>
                                                <span><?= e(money((float) ($reception['total_recepcion'] ?? 0))) ?></span>
                                            </li>
                                        <?php endforeach; ?>
                                        <?php if (empty($receptions)): ?>
                                            <li class="list-group-item px-0 py-2 text-muted">Sin recepciones aún.</li>
                                        <?php endif; ?>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-dismiss="modal">Cerrar</button>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <h2 class="h5 mb-3">Historial de compras</h2>
        <table class="table table-striped table-hover align-middle mb-0 vx-purchase-history-table">
            <thead>
            <tr>
                <th>ID</th>
                <th>Fecha</th>
                <th>Proveedor</th>
                <th>Total</th>
                <th>Estado</th>
                <th>Acción</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($purchases as $purchase): ?>
                <?php
                $purchaseId = (int) ($purchase['id'] ?? 0);
                $estadoPago = (string) ($purchase['estado_pago'] ?? 'pendiente');
                $estadoCompra = (string) ($purchase['estado'] ?? 'recibida');
                $canPay = (float) ($purchase['saldo'] ?? 0) > 0.0001 && $estadoCompra !== 'anulada' && has_permission('compras.pagar');
                $canCancel = $estadoCompra !== 'anulada' && (float) ($purchase['pagado'] ?? 0) <= 0.0001 && has_permission('compras.anular');
                $detailModalId = 'purchaseDetailModal' . $purchaseId;
                $paymentModalId = 'purchasePaymentModal' . $purchaseId;
                ?>
                <tr>
                    <td>#<?= e((string) $purchaseId) ?></td>
                    <td><?= e((string) ($purchase['fecha'] ?? '')) ?></td>
                    <td><?= e((string) ($purchase['proveedor'] ?? '')) ?></td>
                    <td class="fw-semibold"><?= e(money((float) ($purchase['total'] ?? 0))) ?></td>
                    <td>
                        <div class="d-flex flex-column gap-1">
                            <span class="badge <?= $estadoPago === 'pagada' ? 'text-bg-success' : ($estadoPago === 'parcial' ? 'text-bg-warning' : ($estadoPago === 'anulada' ? 'text-bg-secondary' : 'text-bg-danger')) ?>">
                                Cobro: <?= e($estadoPago) ?>
                            </span>
                            <span class="badge <?= $estadoCompra === 'anulada' ? 'text-bg-secondary' : 'text-bg-primary' ?>">
                                Compra: <?= e($estadoCompra) ?>
                            </span>
                        </div>
                    </td>
                    <td>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="bx bx-dots-vertical-rounded"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li>
                                    <button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#<?= e($detailModalId) ?>">
                                        <i class="bx bx-info-circle me-1"></i>Detalle
                                    </button>
                                </li>
                                <?php if ($canPay): ?>
                                    <li>
                                        <button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#<?= e($paymentModalId) ?>">
                                            <i class="bx bx-credit-card me-1"></i>Pagar
                                        </button>
                                    </li>
                                <?php endif; ?>
                                <?php if ($canCancel): ?>
                                    <li><hr class="dropdown-divider"></li>
                                    <li>
                                        <form action="<?= e(url('compras/' . $purchaseId . '/anular')) ?>" method="post" onsubmit="return confirm('Esta acción reversará inventario. ¿Deseas continuar?');">
                                            <?= csrf_field() ?>
                                            <button class="dropdown-item text-danger" type="submit">
                                                <i class="bx bx-x-circle me-1"></i>Anular
                                            </button>
                                        </form>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </td>
                </tr>

                <div class="modal fade" id="<?= e($detailModalId) ?>" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-lg modal-dialog-centered">
                        <div class="modal-content border-0 shadow">
                            <div class="modal-header">
                                <h2 class="h6 mb-0">Compra #<?= e((string) $purchaseId) ?></h2>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row g-2">
                                    <div class="col-md-6"><strong>Proveedor:</strong> <?= e((string) ($purchase['proveedor'] ?? '')) ?></div>
                                    <div class="col-md-6"><strong>Usuario:</strong> <?= e((string) ($purchase['usuario'] ?? '')) ?></div>
                                    <div class="col-md-6"><strong>Fecha:</strong> <?= e((string) ($purchase['fecha'] ?? '')) ?></div>
                                    <div class="col-md-6"><strong>Origen:</strong>
                                        <?php if (!empty($purchase['orden_numero'])): ?>
                                            <?= e((string) $purchase['orden_numero']) ?><?= !empty($purchase['recepcion_compra_id']) ? ' · RC #' . e((string) $purchase['recepcion_compra_id']) : '' ?>
                                        <?php else: ?>
                                            Directa
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-md-4"><strong>Subtotal:</strong> <?= e(money((float) ($purchase['subtotal'] ?? 0))) ?></div>
                                    <div class="col-md-4"><strong>Impuestos:</strong> <?= e(money((float) ($purchase['impuestos'] ?? 0))) ?></div>
                                    <div class="col-md-4"><strong>Total:</strong> <?= e(money((float) ($purchase['total'] ?? 0))) ?></div>
                                    <div class="col-md-4"><strong>Pagado:</strong> <span class="text-success fw-semibold"><?= e(money((float) ($purchase['pagado'] ?? 0))) ?></span></div>
                                    <div class="col-md-4"><strong>Saldo:</strong> <span class="text-danger fw-semibold"><?= e(money((float) ($purchase['saldo'] ?? 0))) ?></span></div>
                                    <div class="col-md-4"><strong>Estado:</strong> <?= e($estadoCompra) ?> / <?= e($estadoPago) ?></div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">Cerrar</button>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($canPay): ?>
                    <div class="modal fade" id="<?= e($paymentModalId) ?>" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content border-0 shadow">
                                <div class="modal-header">
                                    <h2 class="h6 mb-0">Registrar pago · Compra #<?= e((string) $purchaseId) ?></h2>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                                </div>
                                <form action="<?= e(url('compras/' . $purchaseId . '/pagar')) ?>" method="post">
                                    <div class="modal-body">
                                        <?= csrf_field() ?>
                                        <div class="row g-2">
                                            <div class="col-md-6">
                                                <label class="form-label">Monto</label>
                                                <input
                                                    type="number"
                                                    step="0.01"
                                                    min="0.01"
                                                    max="<?= e((string) ($purchase['saldo'] ?? 0)) ?>"
                                                    class="form-control"
                                                    name="monto"
                                                    value="<?= e(number_format((float) ($purchase['saldo'] ?? 0), 2, '.', '')) ?>"
                                                    required
                                                >
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Método</label>
                                                <select class="form-select" name="metodo_pago" required>
                                                    <?php foreach (($paymentMethods ?? []) as $paymentMethod): ?>
                                                        <option value="<?= e((string) ($paymentMethod['codigo'] ?? 'efectivo')) ?>">
                                                            <?= e((string) ($paymentMethod['nombre'] ?? 'Metodo')) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-12">
                                                <label class="form-label">Referencia</label>
                                                <input class="form-control" name="referencia" placeholder="Comprobante, banco, etc.">
                                            </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">Guardar pago</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
            <?php if ($purchases === []): ?>
                <tr><td colspan="6" class="text-center text-muted py-3">No hay compras registradas.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="card border-0 shadow-sm mt-3">
    <div class="card-body">
        <h2 class="h5 mb-3">Pagos recientes de compras</h2>
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                <tr>
                    <th>ID Pago</th>
                    <th>Compra</th>
                    <th>Proveedor</th>
                    <th>Fecha pago</th>
                    <th>Metodo</th>
                    <th>Referencia</th>
                    <th>Monto</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($payments as $payment): ?>
                    <tr>
                        <td><?= e((string) $payment['id']) ?></td>
                        <td>#<?= e((string) $payment['compra_id']) ?></td>
                        <td><?= e($payment['proveedor']) ?></td>
                        <td><?= e($payment['fecha_pago']) ?></td>
                        <td><?= e($payment['metodo_pago']) ?></td>
                        <td><?= e($payment['referencia'] ?? '') ?></td>
                        <td class="text-success fw-semibold"><?= e(money($payment['monto'])) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="purchaseCreateModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow vx-purchase-modal">
            <div class="modal-header">
                <h2 class="h5 mb-0">Registrar compra</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <form action="<?= e(url('compras')) ?>" method="post" id="purchaseForm">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div class="row g-2 mb-3 vx-purchase-toolbar">
                        <div class="col-md-6">
                            <label class="form-label">Proveedor</label>
                            <select class="form-select" name="proveedor_id" id="purchaseSupplier" required>
                                <option value="">Seleccione...</option>
                                <?php foreach ($suppliers as $supplier): ?>
                                    <option value="<?= e((string) $supplier['id']) ?>"><?= e($supplier['nombre']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Impuestos globales</label>
                            <input type="number" step="0.01" value="0" class="form-control purchase-number" name="impuestos" id="purchaseTaxes">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Total compra</label>
                            <input type="text" class="form-control purchase-grand-total" id="purchaseGrandTotal" value="$0,00" readonly>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-bordered align-middle vx-purchase-entry-table mb-0" id="purchaseTable">
                            <thead>
                            <tr>
                                <th style="width: 27%">Producto</th>
                                <th style="width: 18%">Variación</th>
                                <th style="width: 12%">Cantidad</th>
                                <th style="width: 14%">Costo unitario</th>
                                <th style="width: 12%">Impuesto línea (opc.)</th>
                                <th style="width: 11%">Total</th>
                                <th style="width: 6%"></th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td>
                                    <select class="form-select purchase-product" name="producto_id[]" required>
                                        <option value="">Seleccione...</option>
                                        <?php foreach ($products as $product): ?>
                                            <?php
                                            $productId = (int) ($product['id'] ?? 0);
                                            $productSku = trim((string) ($product['sku'] ?? ''));
                                            $productLabel = (string) ($product['nombre'] ?? '');
                                            if ($productSku !== '') {
                                                $productLabel .= ' [' . $productSku . ']';
                                            }
                                            $productLabel .= ' (Stock actual: ' . (string) ($product['stock_actual'] ?? 0) . ')';
                                            $productVariants = is_array($productVariantsMap[$productId] ?? null) ? $productVariantsMap[$productId] : [];
                                            $productVariantsPayload = 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'] ?? ''),
                                                    'cantidad' => $variantStock,
                                                ];
                                            }, $productVariants);
                                            $productVariantsJson = json_encode($productVariantsPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                            if (!is_string($productVariantsJson)) {
                                                $productVariantsJson = '[]';
                                            }
                                            ?>
                                            <option
                                                value="<?= e((string) $productId) ?>"
                                                data-cost="<?= e((string) $product['precio_compra']) ?>"
                                                data-supplier-id="<?= e((string) ($product['proveedor_id'] ?? '')) ?>"
                                                data-has-variants="<?= !empty($productVariantsPayload) ? '1' : '0' ?>"
                                                data-variants="<?= e($productVariantsJson) ?>"
                                            >
                                                <?= e($productLabel) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td>
                                    <select class="form-select purchase-variant" name="variante_id[]" disabled>
                                        <option value="">Sin variación</option>
                                    </select>
                                </td>
                                <td><input type="number" step="1" min="1" class="form-control purchase-qty purchase-number" name="cantidad[]" value="1" required></td>
                                <td><input type="number" step="0.01" min="0.01" class="form-control purchase-cost purchase-number" name="costo_unitario[]" value="0" required></td>
                                <td><input type="number" step="0.01" min="0" class="form-control purchase-line-tax purchase-number" name="impuesto_linea[]" value="0"></td>
                                <td><input type="text" class="form-control purchase-line-total purchase-money-readonly" value="$0,00" readonly data-raw="0.00"></td>
                                <td><button class="btn btn-sm btn-outline-danger purchase-remove-row vx-purchase-remove-row" type="button">x</button></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <small class="text-muted d-block mt-2">Si el producto tiene variaciones activas, la selección de variación es obligatoria.</small>
                </div>
                <div class="modal-footer justify-content-between">
                    <button class="btn btn-outline-secondary btn-sm" type="button" id="purchaseAddRow">
                        <i class="bx bx-plus me-1"></i>Agregar producto
                    </button>
                    <div class="d-flex gap-2">
                        <button class="btn btn-light btn-sm" type="button" data-bs-dismiss="modal">Cancelar</button>
                        <button class="btn btn-primary btn-sm" type="submit">
                            <i class="bx bx-save me-1"></i>Registrar compra
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="purchaseOrderCreateModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow vx-purchase-modal">
            <div class="modal-header">
                <h2 class="h5 mb-0">Crear orden de compra (OC)</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <form action="<?= e(url('compras/ordenes')) ?>" method="post" id="purchaseOrderForm">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div class="row g-2 mb-3">
                        <div class="col-md-6">
                            <label class="form-label">Proveedor</label>
                            <select class="form-select" name="oc_proveedor_id" id="purchaseOrderSupplier" required>
                                <option value="">Seleccione...</option>
                                <?php foreach ($suppliers as $supplier): ?>
                                    <option value="<?= e((string) $supplier['id']) ?>"><?= e($supplier['nombre']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Observación</label>
                            <input class="form-control" name="oc_observacion" maxlength="255" placeholder="Opcional">
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-bordered align-middle vx-purchase-entry-table mb-0" id="purchaseOrderTable">
                            <thead>
                            <tr>
                                <th style="width: 27%">Producto</th>
                                <th style="width: 18%">Variación</th>
                                <th style="width: 12%">Cantidad</th>
                                <th style="width: 14%">Costo unitario</th>
                                <th style="width: 12%">Impuesto línea (opc.)</th>
                                <th style="width: 11%">Total</th>
                                <th style="width: 6%"></th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td>
                                    <select class="form-select purchase-product" name="oc_producto_id[]" required>
                                        <option value="">Seleccione...</option>
                                        <?php foreach ($products as $product): ?>
                                            <?php
                                            $orderProductId = (int) ($product['id'] ?? 0);
                                            $orderProductSku = trim((string) ($product['sku'] ?? ''));
                                            $orderProductLabel = (string) ($product['nombre'] ?? '');
                                            if ($orderProductSku !== '') {
                                                $orderProductLabel .= ' [' . $orderProductSku . ']';
                                            }
                                            $orderProductLabel .= ' (Stock actual: ' . (string) ($product['stock_actual'] ?? 0) . ')';
                                            $orderProductVariants = is_array($productVariantsMap[$orderProductId] ?? null) ? $productVariantsMap[$orderProductId] : [];
                                            $orderProductVariantsPayload = 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'] ?? ''),
                                                    'cantidad' => $variantStock,
                                                ];
                                            }, $orderProductVariants);
                                            $orderProductVariantsJson = json_encode($orderProductVariantsPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                            if (!is_string($orderProductVariantsJson)) {
                                                $orderProductVariantsJson = '[]';
                                            }
                                            ?>
                                            <option
                                                value="<?= e((string) $orderProductId) ?>"
                                                data-cost="<?= e((string) $product['precio_compra']) ?>"
                                                data-supplier-id="<?= e((string) ($product['proveedor_id'] ?? '')) ?>"
                                                data-has-variants="<?= !empty($orderProductVariantsPayload) ? '1' : '0' ?>"
                                                data-variants="<?= e($orderProductVariantsJson) ?>"
                                            >
                                                <?= e($orderProductLabel) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td>
                                    <select class="form-select purchase-variant" name="oc_variante_id[]" disabled>
                                        <option value="">Sin variación</option>
                                    </select>
                                </td>
                                <td><input type="number" step="1" min="1" class="form-control purchase-qty purchase-number" name="oc_cantidad[]" value="1" required></td>
                                <td><input type="number" step="0.01" min="0.01" class="form-control purchase-cost purchase-number" name="oc_costo_unitario[]" value="0" required></td>
                                <td><input type="number" step="0.01" min="0" class="form-control purchase-line-tax purchase-number" name="oc_impuesto_linea[]" value="0"></td>
                                <td><input type="text" class="form-control purchase-line-total purchase-money-readonly" value="$0,00" readonly data-raw="0.00"></td>
                                <td><button class="btn btn-sm btn-outline-danger purchase-remove-row vx-purchase-remove-row" type="button">x</button></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button class="btn btn-outline-secondary btn-sm" type="button" id="purchaseOrderAddRow">
                        <i class="bx bx-plus me-1"></i>Agregar línea
                    </button>
                    <div class="d-flex gap-2">
                        <button class="btn btn-light btn-sm" type="button" data-bs-dismiss="modal">Cancelar</button>
                        <button class="btn btn-warning btn-sm" type="submit">
                            <i class="bx bx-file me-1"></i>Crear OC
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
