<?= $this->extend('layouts/main_layout') ?>
<?= $this->section('content') ?>

<div class="flex items-center justify-between mb-6">
    <h2 class="text-2xl font-bold text-gray-900"><i class="bi bi-pencil-square"></i> Editar Venta #<?= $sale['id_venta'] ?></h2>
    <a href="<?= site_url('sales') ?>" class="bg-teal-100 border border-gray-200 rounded-lg px-4 py-2 text-sm transition hover:bg-gray-50 text-gray-600 no-underline inline-flex items-center gap-2">
        <i class="bi bi-arrow-left"></i> Volver
    </a>
</div>

<div class="bg-emerald-100 rounded-xl shadow-sm border border-gray-100">
    <div class="border-b border-gray-100 px-6 py-4">
        <h5 class="font-semibold text-gray-900"><i class="bi bi-info-circle text-teal-600"></i> Venta #<?= $sale['id_venta'] ?> - <?= date('d/m/Y H:i', strtotime($sale['fecha'])) ?> - Vendedor: <?= $sale['username'] ?></h5>
    </div>
    <div class="p-6">
        <form method="post" action="<?= site_url('sales/' . $sale['id_venta']) ?>" id="editSaleForm">
            <?= csrf_field() ?>

            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider font-semibold">
                        <tr>
                            <th class="text-left px-4 py-3">Producto</th>
                            <th class="text-left px-4 py-3">Codigo</th>
                            <th class="text-center px-4 py-3">Stock Actual</th>
                            <th class="text-center px-4 py-3">Cant. Actual</th>
                            <th class="text-center px-4 py-3">Nueva Cantidad</th>
                            <th class="text-right px-4 py-3">P. Unitario</th>
                            <th class="text-right px-4 py-3">Subtotal</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        <?php foreach ($sale['details'] as $i => $detail):
                            $productModel = new \App\Models\ProductModel();
                            $product = $productModel->find($detail['id_producto']);
                        ?>
                        <tr class="hover:bg-gray-50">
                            <input type="hidden" name="detalle_id[]" value="<?= $detail['id_detalle'] ?>">
                            <td class="px-4 py-3 text-gray-600"><?= esc($detail['producto_nombre']) ?></td>
                            <td class="px-4 py-3 text-gray-600"><?= esc($detail['codigo_unico']) ?></td>
                            <td class="px-4 py-3 text-center">
                                <span class="<?= ($product['stock_actual'] + $detail['cantidad']) <= 5 ? 'bg-rose-100 text-rose-700' : 'bg-emerald-100 text-emerald-700' ?> rounded-lg px-2.5 py-1 text-xs font-semibold">
                                    <?= $product['stock_actual'] + $detail['cantidad'] ?>
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center border border-slate-200 text-gray-600"><?= $detail['cantidad'] ?></td>
                            <td class="px-4 py-3 border border-slate-200 text-gray-600" style="width: 120px;">
                                <input type="number" name="detalle_cantidad[]"
                                       class="w-full bg-teal-100 border border-slate-200 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-400 cantidad-input"
                                       value="<?= old("detalle_cantidad.$i", $detail['cantidad']) ?>"
                                       min="1" required
                                       data-precio="<?= $detail['precio_unitario'] ?>"
                                       data-stock="<?= $product['stock_actual'] + $detail['cantidad'] ?>">
                            </td>
                            <td class="px-4 py-3" style="width: 100px;">
                                <input type="number" name="detalle_precio[]"
                                       class="w-full bg-teal-100 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 precio-input text-right"
                                       value="<?= number_format($detail['precio_unitario'], 2, '.', '') ?>"
                                       min="0.01" step="0.01" required
                                       data-cantidad="<?= $detail['cantidad'] ?>">
                            </td>
                            <td class="px-4 py-3 text-right font-semibold text-gray-900 subtotal-cell">S/ <?= number_format($detail['subtotal'], 2) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot class="bg-gray-50">
                        <tr>
                            <th colspan="6" class="text-right px-4 py-3 font-semibold text-gray-700">TOTAL <span class="text-xs font-normal text-gray-400">(IGV incluido)</span></th>
                            <th class="text-right px-4 py-3 font-bold text-teal-700" id="totalDisplay">S/ <?= number_format($sale['total'], 2) ?></th>
                        </tr>
                        <tr class="text-xs text-gray-400">
                            <th colspan="6" class="text-right px-4 py-1">Base Imponible</th>
                            <th class="text-right px-4 py-1">S/ <?= number_format($sale['total'] / 1.18, 2) ?></th>
                        </tr>
                        <tr class="text-xs text-gray-400">
                            <th colspan="6" class="text-right px-4 py-1">IGV (18%)</th>
                            <th class="text-right px-4 py-1">S/ <?= number_format($sale['total'] * 0.18 / 1.18, 2) ?></th>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
                <div>
                    <label for="id_forma_pago" class="block text-sm font-medium text-gray-500 mb-1">Forma de Pago *</label>
                    <select name="id_forma_pago" id="id_forma_pago" class="w-full bg-teal-100 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500" required>
                        <option value="">Seleccione...</option>
                        <?php foreach ($paymentMethods as $pm): ?>
                        <option value="<?= $pm['id_forma_pago'] ?>"
                            <?= ($sale['payments'][0]['id_forma_pago'] ?? '') == $pm['id_forma_pago'] ? 'selected' : '' ?>>
                            <?= ucfirst($pm['nombre']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="md:col-span-2">
                    <label for="observaciones" class="block text-sm font-medium text-gray-500 mb-1">Observaciones</label>
                    <textarea name="observaciones" id="observaciones" class="w-full bg-teal-100 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500" rows="2"><?= old('observaciones', $sale['observaciones']) ?></textarea>
                </div>
            </div>

            <div class="flex justify-end gap-3 mt-6">
                <a href="<?= site_url('sales') ?>" class="bg-teal-100 border border-gray-200 rounded-lg px-5 py-2.5 text-sm transition hover:bg-gray-50 text-gray-600 no-underline inline-flex items-center gap-2">Cancelar</a>
                <button type="submit" class="bg-teal-600 hover:bg-teal-700 text-white px-5 py-2.5 rounded-lg text-sm font-medium transition inline-flex items-center gap-2 shadow-sm">
                    <i class="bi bi-save"></i> Actualizar Venta
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function recalcularFila(row) {
    var cantInput = row.querySelector('.cantidad-input');
    var precioInput = row.querySelector('.precio-input');
    var cant = parseInt(cantInput.value) || 0;
    var precio = parseFloat(precioInput.value) || 0;
    var stock = parseInt(cantInput.getAttribute('data-stock'));

    if (cant > stock) {
        Swal.fire({ icon: 'warning', title: 'Stock insuficiente', text: 'Stock disponible: ' + stock, timer: 3000, showConfirmButton: false });
        cantInput.value = stock;
        cant = stock;
    }

    var subtotal = cant * precio;
    row.querySelector('.subtotal-cell').textContent = 'S/ ' + subtotal.toFixed(2);
    calcTotal();
}

document.querySelectorAll('.cantidad-input').forEach(function(input) {
    input.addEventListener('input', function() {
        recalcularFila(this.closest('tr'));
    });
});

document.querySelectorAll('.precio-input').forEach(function(input) {
    input.addEventListener('input', function() {
        recalcularFila(this.closest('tr'));
    });
});

function calcTotal() {
    var total = 0;
    document.querySelectorAll('.cantidad-input').forEach(function(input) {
        var row = input.closest('tr');
        var precio = parseFloat(row.querySelector('.precio-input').value) || 0;
        var cant = parseInt(input.value) || 0;
        total += cant * precio;
    });
    document.getElementById('totalDisplay').textContent = 'S/ ' + total.toFixed(2);
}
</script>

<?= $this->endSection() ?>