<x-app-layout>
    <x-slot name="title">
        Órdenes de Compra
    </x-slot>

    <!-- Filtros y Acciones -->
    <div class="card mb-4 border-0 shadow-sm rounded-4">
        <div class="card-body p-4">
            <div class="row g-3 align-items-center justify-content-between">
                <div class="col-md-8">
                    <form method="GET" action="{{ route('compras.index') }}" class="d-flex flex-wrap gap-2">
                        <select name="estado" class="form-select" style="max-width: 220px;">
                            <option value="">Todos los estados</option>
                            <option value="pre_compra" {{ request('estado') === 'pre_compra' ? 'selected' : '' }}>Pre-compra</option>
                            <option value="aprobada" {{ request('estado') === 'aprobada' ? 'selected' : '' }}>Aprobada</option>
                            <option value="en_camino" {{ request('estado') === 'en_camino' ? 'selected' : '' }}>En Camino</option>
                            <option value="recibida" {{ request('estado') === 'recibida' ? 'selected' : '' }}>Recibida</option>
                            <option value="cancelada" {{ request('estado') === 'cancelada' ? 'selected' : '' }}>Cancelada</option>
                        </select>

                        <button type="submit" class="btn btn-outline-secondary rounded-pill">
                            <i class="bi bi-funnel-fill"></i> Filtrar
                        </button>

                        @if(request('estado'))
                            <a href="{{ route('compras.index') }}" class="btn btn-light rounded-pill border">Limpiar</a>
                        @endif
                    </form>
                </div>
                <div class="col-md-4 text-md-end mt-3 mt-md-0 d-flex justify-content-md-end gap-2">
                    @if($cajaAbierta)
                        <button type="button" class="btn btn-primary rounded-pill fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#createCompraModal">
                            <i class="bi bi-plus-circle-fill me-1"></i> Nueva Orden
                        </button>
                    @else
                        <button type="button" class="btn btn-secondary rounded-pill fw-bold shadow-sm" disabled title="Debe aperturar un turno de Caja para realizar compras">
                            <i class="bi bi-lock-fill me-1"></i> Nueva Orden (Caja Cerrada)
                        </button>
                    @endif
                </div>
            </div>
        </div>
    </div>

    @if(!$cajaAbierta)
        <div class="alert alert-warning border-0 shadow-sm rounded-4 d-flex align-items-center" role="alert">
            <i class="bi bi-exclamation-triangle-fill fs-4 text-warning me-3"></i>
            <div>
                <strong>¡Atención! Caja Cerrada.</strong> No se pueden crear nuevas Órdenes de Compra hasta que se aperture un turno de Caja en esta sucursal.
            </div>
        </div>
    @else
        <div class="alert alert-info border-0 shadow-sm rounded-4 d-flex align-items-center mb-4" role="alert">
            <i class="bi bi-info-circle-fill fs-4 text-info me-3"></i>
            <div>
                <strong>Caja Abierta:</strong> Saldo actual disponible para compras: <strong>{{ $moneda }}{{ number_format($saldoCaja, 2) }}</strong>.
            </div>
        </div>
    @endif

    <!-- Tabla de Órdenes -->
    <div class="card border-0 shadow-sm rounded-4">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4 py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">N° Orden</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Proveedor</th>
                            <th class="py-3 text-center text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Estado</th>
                            <th class="py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Estimado</th>
                            <th class="py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Real</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Solicitado por</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Fecha</th>
                            <th class="pe-4 py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Acciones</th>
                        </tr>
                    </thead>
                    <tbody class="border-top-0">
                        @forelse ($ordenes as $orden)
                            <tr>
                                <td class="ps-4 py-3">
                                    <span class="fw-bold text-dark d-block mb-1">{{ $orden->numero }}</span>
                                    <div class="d-flex flex-column gap-1">
                                        <div class="small text-muted fst-italic text-truncate" style="max-width: 220px;" title="{{ $orden->notas }}">
                                            <i class="bi bi-info-circle me-1"></i> {{ $orden->notas ?: 'Sin notas descriptivas' }}
                                        </div>
                                        <div><span class="badge bg-light text-secondary border border-secondary border-opacity-25" style="font-size: 0.65rem;">{{ $orden->items->count() }} ítems</span></div>
                                    </div>
                                </td>
                                <td class="py-3">
                                    @if($orden->proveedor)
                                        <div class="d-flex align-items-center">
                                            <div class="rounded-circle bg-light d-flex align-items-center justify-content-center border me-2" style="width: 32px; height: 32px;">
                                                <i class="bi bi-truck text-secondary"></i>
                                            </div>
                                            <span class="fw-semibold text-dark">{{ $orden->proveedor->razon_social }}</span>
                                        </div>
                                    @else
                                        <span class="text-muted fst-italic">Sin asignar</span>
                                    @endif
                                </td>
                                <td class="py-3 text-center">
                                    @switch($orden->estado)
                                        @case('pre_compra')
                                            <span class="badge bg-secondary bg-opacity-10 text-secondary rounded-pill px-2">Pre-compra</span>
                                            @break
                                        @case('aprobada')
                                            <span class="badge bg-info bg-opacity-10 text-info rounded-pill px-2">Aprobada</span>
                                            @break
                                        @case('en_camino')
                                            <span class="badge bg-primary bg-opacity-10 text-primary rounded-pill px-2">En Camino</span>
                                            @break
                                        @case('recibida')
                                            <span class="badge bg-success bg-opacity-10 text-success rounded-pill px-2">Recibida</span>
                                            @break
                                        @case('cancelada')
                                            <span class="badge bg-danger bg-opacity-10 text-danger rounded-pill px-2">Cancelada</span>
                                            @break
                                    @endswitch
                                </td>
                                <td class="py-3 text-end fw-semibold text-dark">
                                    {{ $moneda }}{{ number_format($orden->total_estimado, 2) }}
                                </td>
                                <td class="py-3 text-end">
                                    @if($orden->total_real)
                                        <span class="fw-bold text-dark">{{ $moneda }}{{ number_format($orden->total_real, 2) }}</span>
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>
                                <td class="py-3">
                                    <span class="text-muted small">{{ $orden->solicitadoPor->name ?? '—' }}</span>
                                </td>
                                <td class="py-3">
                                    <span class="text-muted small">{{ $orden->created_at->format('d/m/Y') }}</span>
                                </td>
                                <td class="pe-4 py-3 text-end">
                                    <a href="{{ route('compras.show', $orden) }}" class="btn btn-sm btn-light border rounded-circle" title="Ver detalle">
                                        <i class="bi bi-eye text-primary"></i>
                                    </a>
                                    @if(in_array($orden->estado, ['pre_compra', 'aprobada']))
                                        <a href="{{ route('compras.edit', $orden) }}" class="btn btn-sm btn-light border rounded-circle mx-1" title="Editar orden">
                                            <i class="bi bi-pencil text-warning"></i>
                                        </a>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="8" class="text-center py-5 text-muted">
                                    <i class="bi bi-cart-x fs-1 d-block mb-3 text-light"></i>
                                    No hay órdenes de compra registradas aún.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            @if($ordenes->hasPages())
                <div class="p-3 border-top">
                    {{ $ordenes->links('pagination::bootstrap-5') }}
                </div>
            @endif
        </div>
    </div>
    </div>

    <!-- Modal Nueva Orden de Compra -->
    <div class="modal fade" id="createCompraModal" tabindex="-1" aria-labelledby="createCompraModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered">
            <div class="modal-content border-0 shadow-lg rounded-4">
                <div class="modal-header bg-light border-bottom-0 pb-0 rounded-top-4 pt-4 px-4">
                    <h5 class="modal-title fw-bold" id="createCompraModalLabel"><i class="bi bi-cart-plus-fill text-primary me-2"></i> Generar Orden de Compra</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4 bg-light">
                    <form method="POST" action="{{ route('compras.store') }}" id="formCompra">
                        @csrf
                        
                        <!-- Alerta Saldo Disponible Modal -->
                        @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: {{ $moneda }}{{ number_format($saldoCaja, 2) }}</h6>
                                    <small class="text-muted">El total estimado no puede superar este monto.</small>
                                </div>
                            </div>
                        @endif

                        <!-- Cabecera de la Orden -->
                        <div class="card border-0 shadow-sm rounded-4 mb-4">
                            <div class="card-body p-4 row g-3">
                                <div class="col-md-6">
                                    <label class="form-label fw-bold small text-muted">Proveedor Sugerido (Opcional)</label>
                                    <select name="proveedor_id" id="selectProveedor" class="form-select border-light-subtle rounded-3">
                                        <option value="">Selecciona un proveedor (opcional)...</option>
                                        @foreach($proveedores as $prov)
                                            <option value="{{ $prov->id }}">{{ $prov->razon_social }} - {{ $prov->tipo }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-bold small text-muted">Notas y Referencias</label>
                                    <input type="text" name="notas" class="form-control border-light-subtle rounded-3" placeholder="Ej. Entrega prioritaria, proveedor llamó, etc.">
                                </div>
                            </div>
                        </div>

                        <!-- Detalle de Ítems -->
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="fw-bold mb-0 text-dark"><i class="bi bi-list-check me-2"></i>Insumos a Comprar</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 border-0 shadow-sm rounded-4 mb-3">
                            <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" style="width: 45%;">Insumo (Uso)</th>
                                                <th class="text-muted small py-3" style="width: 20%;">Cantidad Estimada</th>
                                                <th class="text-muted small py-3" style="width: 20%;">Costo Unit. Ref ($)</th>
                                                <th class="text-end text-muted small py-3" 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">
                                            <!-- Primera fila (Obligatoria) -->
                                            <tr class="item-row">
                                                <td class="ps-4">
                                                    <select name="items[0][insumo_id]" id="firstInsumo" class="form-select form-select-sm insumo-select" required>
                                                        <option value="">Buscar insumo...</option>
                                                        @foreach($insumos as $insumo)
                                                            <option value="{{ $insumo->id }}" data-unidad="{{ $insumo->unidad_compra ?? $insumo->unidad_uso }}" data-costo="{{ $insumo->costo_unitario }}">
                                                                {{ $insumo->nombre }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                    <div class="small text-muted mt-1 ms-1 row-unidad">Seleccione insumo</div>
                                                </td>
                                                <td>
                                                    <div class="input-group input-group-sm">
                                                        <input type="number" name="items[0][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>
                                                    <div class="input-group input-group-sm">
                                                        <span class="input-group-text bg-light text-muted">$</span>
                                                        <input type="number" name="items[0][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">{{ $moneda }}0.00</td>
                                                <td class="pe-4 text-end">
                                                    <button type="button" class="btn btn-sm btn-light border text-danger rounded-circle btn-remove" onclick="removeInsumoRow(this)" disabled title="Debes tener al menos 1 insumo.">
                                                        <i class="bi bi-trash-fill"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        </tbody>
                                        <tfoot class="bg-light border-top">
                                            <tr>
                                                <td colspan="3" class="text-end fw-bold text-muted py-3">Total Estimado de la Orden:</td>
                                                <td class="text-end fw-bold fs-5 text-primary py-3" id="granTotal">{{ $moneda }}0.00</td>
                                                <td></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="text-end mt-4">
                            <button type="button" class="btn btn-light rounded-pill border fw-bold px-4 me-2 shadow-sm" data-bs-dismiss="modal">Cancelar</button>
                            <button type="submit" class="btn btn-primary rounded-pill fw-bold shadow-sm px-4">
                                <i class="bi bi-send-check me-1"></i> Generar Orden de Compra
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @push('styles')
    <style>
        .ts-control { border-radius: 0.375rem; padding: 0.5rem 0.75rem; border-color: #dee2e6; }
        .ts-control.form-select-sm { padding: 0.25rem 0.5rem; }
    </style>
    @endpush

    @push('scripts')
    <script>
        const insumosData = @json($insumos);
        let rowCount = 1;

        document.addEventListener('DOMContentLoaded', function() {
            // Inicializar TomSelect en el Proveedor
            new TomSelect("#selectProveedor", {
                create: false,
                sortField: { field: "text", direction: "asc" },
                placeholder: "Selecciona un proveedor (opcional)..."
            });

            // Inicializar TomSelect en la primera fila de insumo
            initInsumoSelect(document.getElementById('firstInsumo'));
        });

        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}">{{ $moneda }}{insumo.nombre}</option>`;
            });

            const html = `
                <tr class="item-row">
                    <td class="ps-4">
                        <select name="items[${rowCount}][insumo_id]" class="form-select form-select-sm insumo-select" required>
                            {{ $moneda }}{optionsHtml}
                        </select>
                        <div class="small text-muted mt-1 ms-1 row-unidad">Seleccione insumo</div>
                    </td>
                    <td>
                        <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>
                        <div class="input-group input-group-sm">
                            <span class="input-group-text bg-light text-muted">$</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">{{ $moneda }}0.00</td>
                    <td class="pe-4 text-end">
                        <button type="button" class="btn btn-sm btn-light border text-danger rounded-circle btn-remove" onclick="removeInsumoRow(this)" title="Eliminar insumo">
                            <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: {{ $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 = '$' + 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 = '$' + granTotal.toFixed(2);
        }
    </script>
    @endpush
</x-app-layout>
