<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('title', null, []); ?> 
        <div class="d-flex align-items-center gap-2">
            <a href="<?php echo e(route('compras.index')); ?>" class="btn btn-sm btn-light rounded-circle shadow-sm border-0 me-2" title="Volver a Compras">
                <i class="bi bi-arrow-left text-secondary"></i>
            </a>
            <span class="text-secondary fw-normal">Compras / Editar Orden / </span> <?php echo e($orden->numero); ?>

        </div>
     <?php $__env->endSlot(); ?>

    <div class="row justify-content-center">
        <div class="col-lg-10">
            <div class="card border-0 shadow-lg rounded-4">
                <div class="card-header bg-white border-bottom-0 pb-0 pt-4 px-4">
                    <h4 class="fw-bold mb-0 text-dark">
                        <i class="bi bi-pencil-square text-primary me-2"></i> Modificando Orden: <span class="text-primary"><?php echo e($orden->numero); ?></span>
                    </h4>
                    <p class="text-muted small mt-1 mb-0">Esta orden se encuentra en estado <strong><?php echo e($orden->estado === 'pre_compra' ? 'Borrador (Pre-Compra)' : 'Aprobada'); ?></strong>.</p>
                </div>

                <div class="card-body p-4 bg-white">
                    <form method="POST" action="<?php echo e(route('compras.update', $orden)); ?>" id="formEditCompra">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PUT'); ?>
                        
                        <!-- Alerta Saldo Disponible -->
                        <?php if($cajaAbierta): ?>
                            <div class="alert alert-light border shadow-sm rounded-4 align-items-center mb-4 d-flex">
                                <i class="bi bi-wallet2 fs-4 text-success me-3"></i>
                                <div>
                                    <h6 class="mb-0 fw-bold">Saldo Disponible en Caja: <?php echo e($moneda); ?> <?php echo e(number_format($saldoCaja, 2)); ?></h6>
                                    <small class="text-muted">El costo total estimado no puede superar este monto.</small>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-danger border-0 shadow-sm rounded-4 align-items-center mb-4 d-flex">
                                <i class="bi bi-exclamation-triangle-fill fs-4 text-danger me-3"></i>
                                <div>
                                    <h6 class="mb-0 fw-bold">Caja Cerrada</h6>
                                    <small class="text-muted">No podrá guardar cambios porque el turno de caja se encuentra cerrado.</small>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Cabecera de la Orden -->
                        <div class="card border border-light-subtle shadow-sm rounded-4 mb-4 bg-light bg-opacity-50">
                            <div class="card-body p-4 row g-4">
                                <div class="col-md-6">
                                    <label class="form-label fw-bold small text-muted text-uppercase" style="letter-spacing:0.05em">Proveedor Seleccionado</label>
                                    <select name="proveedor_id" id="selectProveedor" class="form-select border-light-subtle rounded-3">
                                        <option value="">Ningún proveedor específico...</option>
                                        <?php $__currentLoopData = $proveedores; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $prov): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($prov->id); ?>" <?php echo e($orden->proveedor_id == $prov->id ? 'selected' : ''); ?>>
                                                <?php echo e($prov->razon_social); ?> - <?php echo e(ucfirst($prov->tipo)); ?>

                                            </option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-bold small text-muted text-uppercase" style="letter-spacing:0.05em">Notas Adicionales</label>
                                    <input type="text" name="notas" class="form-control border-light-subtle rounded-3" value="<?php echo e(old('notas', $orden->notas)); ?>" placeholder="Ej. Urgente entregar antes de mediodía...">
                                </div>
                            </div>
                        </div>

                        <!-- Detalle de Ítems -->
                        <div class="card border border-light-subtle shadow-sm rounded-4 mb-4">
                            <div class="card-header bg-white border-bottom-0 pt-4 px-4 d-flex justify-content-between align-items-center">
                                <h6 class="fw-bold mb-0 text-dark text-uppercase"><i class="bi bi-list-check me-2 text-warning"></i>Lista de Insumos</h6>
                                <button type="button" class="btn btn-sm btn-outline-primary rounded-pill fw-bold" onclick="addInsumoRow()">
                                    <i class="bi bi-plus-lg me-1"></i> Agregar Insumo
                                </button>
                            </div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle mb-0" id="itemsTable">
                                        <thead class="bg-light">
                                            <tr>
                                                <th class="ps-4 text-muted small py-3 text-uppercase" style="width: 45%;">Insumo Requerido</th>
                                                <th class="text-muted small py-3 text-uppercase" style="width: 20%;">Cantidad</th>
                                                <th class="text-muted small py-3 text-uppercase" style="width: 20%;">Costo Unit. Ref (<?php echo e($moneda); ?> )</th>
                                                <th class="text-end text-muted small py-3 text-uppercase" style="width: 10%;">Subtotal</th>
                                                <th class="pe-4 text-end text-muted small py-3" style="width: 5%;"></th>
                                            </tr>
                                        </thead>
                                        <tbody class="border-top-0" id="itemsBody">
                                            <?php $__currentLoopData = $orden->items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <tr class="item-row">
                                                    <td class="ps-4 py-3">
                                                        <select name="items[<?php echo e($index); ?>][insumo_id]" class="form-select form-select-sm insumo-select" required>
                                                            <option value="">Buscar insumo...</option>
                                                            <?php $__currentLoopData = $insumos; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $insumo): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                <option value="<?php echo e($insumo->id); ?>" 
                                                                    data-unidad="<?php echo e($insumo->unidad_compra ?? $insumo->unidad_uso); ?>" 
                                                                    data-costo="<?php echo e($insumo->costo_unitario); ?>"
                                                                    <?php echo e($item->insumo_id == $insumo->id ? 'selected' : ''); ?>>
                                                                    <?php echo e($insumo->nombre); ?>

                                                                </option>
                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                        </select>
                                                        <div class="small text-muted mt-1 ms-1 row-unidad">Unidad Métrica: <?php echo e($item->insumo->unidad_compra ?? $item->insumo->unidad_uso ?? 'U.'); ?></div>
                                                    </td>
                                                    <td class="py-3">
                                                        <div class="input-group input-group-sm">
                                                            <input type="number" name="items[<?php echo e($index); ?>][cantidad]" class="form-control input-cant" required step="0.001" min="0.001" value="<?php echo e($item->cantidad_solicitada); ?>" oninput="calculateRow(this)">
                                                            <span class="input-group-text bg-light text-muted fw-bold span-unidad"><?php echo e(substr($item->insumo->unidad_compra ?? $item->insumo->unidad_uso ?? 'U.', 0, 3)); ?>.</span>
                                                        </div>
                                                    </td>
                                                    <td class="py-3">
                                                        <div class="input-group input-group-sm">
                                                            <span class="input-group-text bg-light text-muted"><?php echo e($moneda); ?> </span>
                                                            <input type="number" name="items[<?php echo e($index); ?>][precio_est]" class="form-control input-costo" required step="0.01" min="0" value="<?php echo e($item->precio_unitario_estimado); ?>" oninput="calculateRow(this)">
                                                        </div>
                                                    </td>
                                                    <td class="text-end fw-bold text-dark row-subtotal py-3">
                                                        <?php echo e($moneda); ?> <?php echo e(number_format($item->cantidad_solicitada * $item->precio_unitario_estimado, 2)); ?>

                                                    </td>
                                                    <td class="pe-4 text-end py-3">
                                                        <button type="button" class="btn btn-sm btn-light border text-danger rounded-circle btn-remove" onclick="removeInsumoRow(this)" title="Eliminar fila">
                                                            <i class="bi bi-trash-fill"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </tbody>
                                        <tfoot class="bg-dark text-white border-top">
                                            <tr>
                                                <td colspan="3" class="text-end fw-bold py-3 text-uppercase" style="letter-spacing: 0.05em; font-size:0.85rem">Costo Total Estimado:</td>
                                                <td class="text-end fw-bold fs-5 text-warning py-3" id="granTotal"><?php echo e($moneda); ?> <?php echo e(number_format($orden->total_estimado, 2)); ?></td>
                                                <td></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- Acciones -->
                        <div class="d-flex justify-content-end gap-3 pt-3 border-top mt-4">
                            <a href="<?php echo e(route('compras.show', $orden)); ?>" class="btn btn-light rounded-pill border fw-bold px-4 shadow-sm text-secondary">
                                Cancelar y Volver
                            </a>
                            <button type="submit" class="btn btn-primary rounded-pill fw-bold shadow-sm px-4">
                                <i class="bi bi-save2-fill me-2"></i> Guardar Cambios
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php $__env->startPush('styles'); ?>
    <style>
        .ts-control { border-radius: 0.375rem; padding: 0.6rem 0.75rem; border-color: #dee2e6; }
        .ts-control.form-select-sm { padding: 0.3rem 0.6rem; }
    </style>
    <?php $__env->stopPush(); ?>

    <?php $__env->startPush('scripts'); ?>
    <script>
        const insumosData = <?php echo json_encode($insumos, 15, 512) ?>;
        // Empezamos con el numero de items que ya existen
        let rowCount = <?php echo e(max(1, $orden->items->count())); ?>;

        document.addEventListener('DOMContentLoaded', function() {
            // Proveedor
            new TomSelect("#selectProveedor", {
                create: false,
                maxItems: 1,
                maxOptions: 3,
                dropdownParent: "body",
                sortField: { field: "text", direction: "asc" },
                placeholder: "Ningún proveedor específico..."
            });

            // Inicializar TomSelect en todos los selects existentes (Items)
            document.querySelectorAll('.insumo-select').forEach((el) => {
                initInsumoSelect(el);
            });
            
            updateRemoveButtons();
            calculateTotal();
        });

        function initInsumoSelect(selectElement) {
            new TomSelect(selectElement, {
                create: false,
                sortField: { field: "text", direction: "asc" },
                placeholder: "Buscar insumo...",
                onChange: function() {
                    updateRowStats(selectElement);
                }
            });
        }

        function addInsumoRow() {
            const tbody = document.getElementById('itemsBody');
            
            let optionsHtml = '<option value="">Buscar insumo...</option>';
            insumosData.forEach(insumo => {
                let unidad = insumo.unidad_compra || insumo.unidad_uso;
                optionsHtml += `<option value="${insumo.id}" data-unidad="${unidad}" data-costo="${insumo.costo_unitario || 0}">${insumo.nombre}</option>`;
            });

            const html = `
                <tr class="item-row">
                    <td class="ps-4 py-3">
                        <select name="items[${rowCount}][insumo_id]" class="form-select form-select-sm insumo-select" required>
                            ${optionsHtml}
                        </select>
                        <div class="small text-muted mt-1 ms-1 row-unidad">Seleccione insumo</div>
                    </td>
                    <td class="py-3">
                        <div class="input-group input-group-sm">
                            <input type="number" name="items[${rowCount}][cantidad]" class="form-control input-cant" required step="0.001" min="0.001" value="1" oninput="calculateRow(this)">
                            <span class="input-group-text bg-light text-muted fw-bold span-unidad">U.</span>
                        </div>
                    </td>
                    <td class="py-3">
                        <div class="input-group input-group-sm">
                            <span class="input-group-text bg-light text-muted"><?php echo e($moneda); ?> </span>
                            <input type="number" name="items[${rowCount}][precio_est]" class="form-control input-costo" required step="0.01" min="0" value="0.00" oninput="calculateRow(this)">
                        </div>
                    </td>
                    <td class="text-end fw-bold text-dark row-subtotal py-3"><?php echo e($moneda); ?> 0.00</td>
                    <td class="pe-4 text-end py-3">
                        <button type="button" class="btn btn-sm btn-light border text-danger rounded-circle btn-remove" onclick="removeInsumoRow(this)" title="Eliminar fila">
                            <i class="bi bi-trash-fill"></i>
                        </button>
                    </td>
                </tr>
            `;
            
            tbody.insertAdjacentHTML('beforeend', html);
            
            const newRow = tbody.lastElementChild;
            const newSelect = newRow.querySelector('.insumo-select');
            initInsumoSelect(newSelect);
            
            rowCount++;
            updateRemoveButtons();
            calculateTotal();
        }

        function removeInsumoRow(btn) {
            const tbody = document.getElementById('itemsBody');
            if(tbody.querySelectorAll('.item-row').length > 1) {
                btn.closest('.item-row').remove();
                updateRemoveButtons();
                calculateTotal();
            }
        }

        function updateRemoveButtons() {
            const rows = document.querySelectorAll('.item-row');
            const btns = document.querySelectorAll('.btn-remove');
            if(rows.length === 1) {
                if(btns[0]) btns[0].setAttribute('disabled', 'disabled');
            } else {
                btns.forEach(b => b.removeAttribute('disabled'));
            }
        }

        function updateRowStats(selectEl) {
            const row = selectEl.closest('.item-row');
            const option = selectEl.options[selectEl.selectedIndex];
            
            if(option && option.value !== "") {
                const unidad = option.getAttribute('data-unidad') || 'U.';
                let costo = option.getAttribute('data-costo') || 0;
                
                row.querySelector('.row-unidad').innerText = `Unidad Métrica: <?php echo e($moneda); ?>{unidad}`;
                row.querySelector('.span-unidad').innerText = unidad.substring(0, 3) + '.';
                
                if (costo) {
                    row.querySelector('.input-costo').value = parseFloat(costo).toFixed(2);
                }
            } else {
                row.querySelector('.row-unidad').innerText = "Seleccione insumo";
                row.querySelector('.span-unidad').innerText = "U.";
                row.querySelector('.input-costo').value = "0.00";
            }
            
            calculateRow(selectEl);
        }

        function calculateRow(el) {
            const row = el.closest('.item-row');
            const cant = parseFloat(row.querySelector('.input-cant').value) || 0;
            const costo = parseFloat(row.querySelector('.input-costo').value) || 0;
            
            const subtotal = cant * costo;
            row.querySelector('.row-subtotal').innerText = 'S/' + subtotal.toFixed(2);
            
            calculateTotal();
        }

        function calculateTotal() {
            const rows = document.querySelectorAll('.item-row');
            let granTotal = 0;
            
            rows.forEach(row => {
                const cant = parseFloat(row.querySelector('.input-cant').value) || 0;
                const costo = parseFloat(row.querySelector('.input-costo').value) || 0;
                granTotal += (cant * costo);
            });
            
            document.getElementById('granTotal').innerText = 'S/' + granTotal.toFixed(2);
        }
    </script>
    <?php $__env->stopPush(); ?>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php /**PATH C:\laragon\www\gastrog\resources\views/compras/edit.blade.php ENDPATH**/ ?>