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

<?php $__env->startSection('content'); ?>
    <?php
        $productosJs = $productos->map(function ($producto) {
            return [
                'id' => (int) $producto->id,
                'nombre' => $producto->nombre,
                'sku' => $producto->sku,
            ];
        })->values()->all();
    ?>

    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
            <h1 class="h4 mb-0">Ordenes de compra</h1>
            <div class="d-flex gap-2 flex-wrap">
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(has_permission('compras.ver')): ?>
                    <a href="<?php echo e(route('compras.index')); ?>" class="btn btn-outline-primary">Ver compras</a>
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                <a href="<?php echo e(route('dashboard')); ?>" class="btn btn-outline-secondary">Volver al dashboard</a>
            </div>
        </div>

        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($errors->any()): ?>
            <div class="alert alert-danger">
                <?php echo e($errors->first()); ?>

            </div>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body">
                <h2 class="h6 mb-3">Crear orden de compra</h2>

                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($proveedores->isEmpty()): ?>
                    <div class="alert alert-warning mb-0">
                        No hay proveedores activos para la empresa seleccionada.
                    </div>
                <?php elseif($productos->isEmpty()): ?>
                    <div class="alert alert-warning mb-0">
                        No hay productos activos para generar una orden de compra.
                    </div>
                <?php else: ?>
                    <form action="<?php echo e(route('compras.ordenes.store')); ?>" method="POST" id="orden-form">
                        <?php echo csrf_field(); ?>

                        <div class="row g-3">
                            <div class="col-12 col-md-4">
                                <label class="form-label" for="proveedor_id">Proveedor</label>
                                <select class="form-select" id="proveedor_id" name="proveedor_id" required>
                                    <option value="">Selecciona proveedor</option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $proveedores; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $proveedor): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                        <option value="<?php echo e($proveedor->id); ?>"><?php echo e($proveedor->nombre); ?></option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                </select>
                            </div>
                            <div class="col-12 col-md-4">
                                <label class="form-label" for="sucursal_id">Sucursal</label>
                                <select class="form-select" id="sucursal_id" name="sucursal_id">
                                    <option value="">Sucursal activa actual</option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $sucursales; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $sucursal): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                                        <option value="<?php echo e($sucursal->id); ?>" <?php if((int) $tenantSucursalId === (int) $sucursal->id): echo 'selected'; endif; ?>>
                                            <?php echo e($sucursal->nombre); ?>

                                        </option>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                </select>
                            </div>
                            <div class="col-12 col-md-4">
                                <label class="form-label" for="fecha">Fecha</label>
                                <input class="form-control" id="fecha" name="fecha" type="datetime-local" value="<?php echo e(now()->format('Y-m-d\TH:i')); ?>" required>
                            </div>
                            <div class="col-12">
                                <label class="form-label" for="observacion">Observacion</label>
                                <textarea class="form-control" id="observacion" name="observacion" rows="2"></textarea>
                            </div>
                        </div>

                        <hr class="my-4">

                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h3 class="h6 mb-0">Lineas</h3>
                            <button type="button" class="btn btn-sm btn-outline-primary" id="agregar-linea">Agregar linea</button>
                        </div>

                        <div id="lineas-wrapper" class="d-grid gap-3"></div>

                        <div class="mt-4">
                            <button class="btn btn-primary">Guardar orden</button>
                        </div>
                    </form>
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            </div>
        </div>

        <div class="card border-0 shadow-sm">
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Numero</th>
                            <th>Fecha</th>
                            <th>Proveedor</th>
                            <th>Sucursal</th>
                            <th>Total</th>
                            <th>Estado</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__empty_1 = true; $__currentLoopData = $ordenes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $orden): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                            <tr>
                                <td><?php echo e($orden->numero); ?></td>
                                <td><?php echo e(optional($orden->fecha)->format('Y-m-d H:i') ?: 'N/A'); ?></td>
                                <td><?php echo e($orden->proveedor?->nombre ?? 'N/A'); ?></td>
                                <td><?php echo e($orden->sucursal?->nombre ?? 'General'); ?></td>
                                <td><?php echo e(number_format((float) $orden->total, 2)); ?></td>
                                <td class="text-capitalize"><?php echo e($orden->estado); ?></td>
                                <td class="text-end">
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(has_permission('compras.recibir') && $orden->estado !== 'anulada'): ?>
                                        <a href="<?php echo e(route('compras.ordenes.receive', $orden)); ?>" class="btn btn-sm btn-outline-success">Recibir</a>
                                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </td>
                            </tr>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                            <tr>
                                <td colspan="7" class="text-center py-4">No hay ordenes registradas.</td>
                            </tr>
                        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="mt-3">
            <?php echo e($ordenes->links()); ?>

        </div>
    </div>

    <script>
        (() => {
            const productos = <?php echo json_encode($productosJs, 15, 512) ?>;

            const wrapper = document.getElementById('lineas-wrapper');
            const addButton = document.getElementById('agregar-linea');

            if (!wrapper || !addButton || !productos.length) {
                return;
            }

            let lineIndex = 0;

            const buildProductoOptions = () => {
                return ['<option value="">Selecciona producto</option>']
                    .concat(productos.map((producto) => {
                        const label = producto.sku ? `${producto.nombre} (${producto.sku})` : producto.nombre;
                        return `<option value="${producto.id}">${label}</option>`;
                    }))
                    .join('');
            };

            const addLine = () => {
                const container = document.createElement('div');
                container.className = 'border rounded p-3';
                container.innerHTML = `
                    <div class="row g-2 align-items-end">
                        <div class="col-12 col-md-4">
                            <label class="form-label">Producto</label>
                            <select class="form-select" name="lineas[${lineIndex}][producto_id]" required>
                                ${buildProductoOptions()}
                            </select>
                        </div>
                        <div class="col-6 col-md-2">
                            <label class="form-label">Cantidad</label>
                            <input class="form-control" type="number" step="0.01" min="0.01" name="lineas[${lineIndex}][cantidad]" required>
                        </div>
                        <div class="col-6 col-md-2">
                            <label class="form-label">Costo unit.</label>
                            <input class="form-control" type="number" step="0.01" min="0" name="lineas[${lineIndex}][costo_unitario]" required>
                        </div>
                        <div class="col-6 col-md-2">
                            <label class="form-label">Impuesto</label>
                            <input class="form-control" type="number" step="0.01" min="0" name="lineas[${lineIndex}][impuesto]" value="0">
                        </div>
                        <div class="col-6 col-md-2">
                            <button type="button" class="btn btn-outline-danger w-100 quitar-linea">Quitar</button>
                        </div>
                    </div>
                `;

                container.querySelector('.quitar-linea')?.addEventListener('click', () => {
                    container.remove();
                });

                wrapper.appendChild(container);
                lineIndex += 1;
            };

            addButton.addEventListener('click', addLine);
            addLine();
        })();
    </script>
<?php $__env->stopSection(); ?>

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