/* 
   Módulo de Gestión de Proveedores y Compras
   Gestión de proveedores, órdenes de compra y cuentas por pagar.
*/

const Suppliers = {
    suppliers: [],
    purchase_orders: [],

    init() {
        this.loadData();
    },

    async loadData() {
        this.suppliers = await window.Storage.get('suppliers') || [];
        this.purchase_orders = await window.Storage.get('purchase_orders') || [];
        this.render();
    },

    // 22032026 Renderizado Estilo Premium
    render() {
        const container = document.getElementById('module-render');
        
        const totalSuppliers = this.suppliers.length;
        const pendingPOs = this.purchase_orders.filter(po => po.status === 'pending');
        const totalPayables = pendingPOs.reduce((sum, po) => sum + po.total, 0);

        container.innerHTML = `
            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm rounded-4 p-3 h-100 bg-white border-bottom border-primary border-4">
                        <div class="d-flex align-items-center mb-2">
                            <div class="bg-primary bg-opacity-10 rounded-3 d-flex align-items-center justify-content-center me-3 text-primary" style="width: 45px; height: 45px;">
                                <i class="bi bi-truck fs-5"></i>
                            </div>
                            <span class="text-muted small fw-bold text-uppercase ls-1">Proveedores</span>
                        </div>
                        <h3 class="fw-bold mb-0 text-dark">${totalSuppliers} Activos</h3>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm rounded-4 p-3 h-100 bg-white border-bottom border-warning border-4">
                        <div class="d-flex align-items-center mb-2">
                            <div class="bg-warning bg-opacity-10 rounded-3 d-flex align-items-center justify-content-center me-3 text-warning" style="width: 45px; height: 45px;">
                                <i class="bi bi-clock-history fs-5"></i>
                            </div>
                            <span class="text-muted small fw-bold text-uppercase ls-1">Órdenes Pendientes</span>
                        </div>
                        <h3 class="fw-bold mb-0 text-dark">${pendingPOs.length} Por Surtir</h3>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm rounded-4 p-3 h-100 text-white" style="background: linear-gradient(135deg, #dc3545 0%, #e05e6b 100%)">
                        <div class="d-flex align-items-center mb-2">
                            <div class="bg-white bg-opacity-25 rounded-3 d-flex align-items-center justify-content-center me-3 text-white" style="width: 45px; height: 45px;">
                                <i class="bi bi-currency-dollar fs-5"></i>
                            </div>
                            <span class="opacity-75 small fw-bold text-uppercase ls-1">Cuentas por Pagar</span>
                        </div>
                        <h3 class="fw-bold mb-0 text-white">$${totalPayables.toFixed(2)}</h3>
                    </div>
                </div>
            </div>

            <div class="row g-4">
                <!-- Columna de Proveedores -->
                <div class="col-lg-5">
                    <div class="card border-0 shadow-sm rounded-4 overflow-hidden h-100">
                        <div class="card-header bg-white border-0 p-4">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="fw-bold mb-0">Directorio de Proveedores</h5>
                                    <small class="text-muted">Contactos y empresas</small>
                                </div>
                                <button class="btn btn-light rounded-pill px-3 fw-bold border shadow-sm" onclick="Suppliers.showAddSupplierModal()">
                                    <i class="bi bi-plus-lg text-primary"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive" style="max-height: 500px;">
                                <table class="table table-hover align-middle mb-0">
                                    <thead class="bg-light sticky-top">
                                        <tr>
                                            <th class="ps-4 py-3 fw-bold small text-muted">EMPRESA</th>
                                            <th class="fw-bold small text-muted">TELÉFONO</th>
                                            <th class="text-end pe-4 fw-bold small text-muted">ACCIONES</th>
                                        </tr>
                                    </thead>
                                    <tbody id="suppliers-table-body">${this.renderSuppliersRows()}</tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Columna de Órdenes de Compra -->
                <div class="col-lg-7">
                    <div class="card border-0 shadow-sm rounded-4 overflow-hidden h-100">
                        <div class="card-header bg-white border-0 p-4">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="fw-bold mb-0">Órdenes de Compra</h5>
                                    <small class="text-muted">Pedidos pendientes y surtidos</small>
                                </div>
                                <button class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" onclick="Suppliers.showAddPOModal()">
                                    <i class="bi bi-plus-lg me-1 text-white"></i> NUEVA ORDEN
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive" style="max-height: 500px;">
                                <table class="table table-hover align-middle mb-0">
                                    <thead class="bg-light sticky-top">
                                        <tr>
                                            <th class="ps-4 py-3 fw-bold small text-muted">FECHA ESPERADA</th>
                                            <th class="fw-bold small text-muted">PROVEEDOR</th>
                                            <th class="fw-bold small text-muted text-center">TOTAL</th>
                                            <th class="fw-bold small text-muted text-center">ESTADO</th>
                                            <th class="text-end pe-4 fw-bold small text-muted">ACCIONES</th>
                                        </tr>
                                    </thead>
                                    <tbody id="po-table-body">${this.renderPORows()}</tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    },

    renderSuppliersRows() {
        if (this.suppliers.length === 0) return `<tr><td colspan="3" class="text-center py-5 opacity-50"><i class="bi bi-inbox display-6 d-block mb-3"></i> Sin proveedores registrados.</td></tr>`;
        
        return this.suppliers.map(s => `
            <tr>
                <td class="ps-4">
                    <div class="fw-bold text-dark">${s.name}</div>
                    <small class="text-muted">${s.contact_name || 'Sin contacto'}</small>
                </td>
                <td><span class="badge border bg-white text-secondary rounded-pill px-2 fw-normal">${s.phone}</span></td>
                <td class="text-end pe-4">
                    <button class="btn btn-icon btn-light border rounded-circle me-1" onclick="Suppliers.showAddSupplierModal('${s.id}')" title="Editar"><i class="bi bi-pencil-square"></i></button>
                    <button class="btn btn-icon btn-outline-danger border rounded-circle" onclick="Suppliers.deleteSupplier('${s.id}')" title="Eliminar"><i class="bi bi-trash"></i></button>
                </td>
            </tr>
        `).join('');
    },

    renderPORows() {
        if (this.purchase_orders.length === 0) return `<tr><td colspan="5" class="text-center py-5 opacity-50"><i class="bi bi-receipt display-6 d-block mb-3"></i> No hay órdenes de compra activas.</td></tr>`;
        
        // Ordenar: pendientes primero, luego surtidas
        const sortedPOs = [...this.purchase_orders].sort((a,b) => (a.status === 'pending' ? -1 : 1));

        return sortedPOs.map(po => {
            const supplier = this.suppliers.find(s => s.id === po.supplier_id);
            const supName = supplier ? supplier.name : 'Proveedor Desconocido';
            
            return `
            <tr>
                <td class="ps-4">
                    <div class="fw-bold text-dark small">${new Date(po.expected_date).toLocaleDateString()}</div>
                </td>
                <td>
                    <div class="fw-bold text-dark mb-0">${supName}</div>
                    <small class="text-muted">${po.items.length} artículos</small>
                </td>
                <td class="text-center">
                    <span class="fw-bold text-primary">$${po.total.toFixed(2)}</span>
                </td>
                <td class="text-center">
                    ${po.status === 'pending' 
                        ? '<span class="badge bg-warning text-dark rounded-pill px-3 py-2 fw-bold"><i class="bi bi-clock"></i> Pendiente</span>'
                        : '<span class="badge bg-success text-white rounded-pill px-3 py-2 fw-bold"><i class="bi bi-check-circle"></i> Surtido</span>'
                    }
                </td>
                <td class="text-end pe-4">
                    ${po.status === 'pending' ? `
                        <button class="btn btn-success btn-sm rounded-pill fw-bold shadow-sm me-1" onclick="Suppliers.surtirPO('${po.id}')" title="Surtir e Ingresar a Inventario"><i class="bi bi-box-arrow-in-down"></i> Surtir</button>
                        <button class="btn btn-icon btn-light border rounded-circle me-1" onclick="Suppliers.showAddPOModal('${po.id}')" title="Editar Cantidades/Precios"><i class="bi bi-pencil-square"></i></button>
                    ` : `
                        <button class="btn btn-icon btn-light border rounded-circle me-1" onclick="Suppliers.showAddPOModal('${po.id}', true)" title="Ver Detalles"><i class="bi bi-eye"></i></button>
                    `}
                    <button class="btn btn-icon btn-outline-danger border rounded-circle" onclick="Suppliers.deletePO('${po.id}')" title="Eliminar"><i class="bi bi-trash"></i></button>
                </td>
            </tr>
        `}).join('');
    },

    // --- MÉTODOS DE PROVEEDORES ---

    showAddSupplierModal(id = null) {
        let s = id ? this.suppliers.find(x => x.id === id) : null;
        
        let modalEl = document.getElementById('sup-form-modal');
        if (!modalEl) {
            modalEl = document.createElement('div');
            modalEl.id = 'sup-form-modal';
            modalEl.className = 'modal fade shadow';
            document.body.appendChild(modalEl);
        }

        modalEl.innerHTML = `
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-0 shadow-lg rounded-4">
                    <div class="modal-header bg-primary text-white border-0 py-3 rounded-top-4">
                        <h5 class="modal-title fw-bold"><i class="bi ${s ? 'bi-pencil-square' : 'bi-plus-circle'} me-2"></i> ${s ? 'EDITAR' : 'NUEVO'} PROVEEDOR</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" id="close-sup-modal"></button>
                    </div>
                    <div class="modal-body p-4">
                        <input type="hidden" id="sup-id" value="${s ? s.id : ''}">
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-muted">NOMBRE DE LA EMPRESA</label>
                            <input type="text" class="form-control bg-light border-0 py-2" id="sup-name" value="${s ? s.name : ''}" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-muted">NOMBRE DEL CONTACTO</label>
                            <input type="text" class="form-control bg-light border-0 py-2" id="sup-contact" value="${s ? (s.contact_name||'') : ''}">
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-muted">TELÉFONO</label>
                            <input type="tel" class="form-control bg-light border-0 py-2" id="sup-phone" value="${s ? s.phone : ''}" required>
                        </div>
                    </div>
                    <div class="modal-footer border-0 p-4 pt-0">
                        <button type="button" class="btn btn-light rounded-pill px-4" data-bs-dismiss="modal">CANCELAR</button>
                        <button type="button" class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" onclick="Suppliers.saveSupplier()">GUARDAR</button>
                    </div>
                </div>
            </div>
        `;

        bootstrap.Modal.getOrCreateInstance(modalEl).show();
    },

    async saveSupplier() {
        const id = document.getElementById('sup-id').value;
        const name = document.getElementById('sup-name').value;
        const contact = document.getElementById('sup-contact').value;
        const phone = document.getElementById('sup-phone').value;

        if (!name || !phone) return window.App?.showToast('Empresa y Teléfono son obligatorios.', 'warning');

        if (id) {
            const idx = this.suppliers.findIndex(x => x.id === id);
            this.suppliers[idx] = { ...this.suppliers[idx], name, contact_name: contact, phone };
            window.App?.logAction('SUPPLIER_UPDATE', `Proveedor actualizado: ${name}`);
        } else {
            this.suppliers.push({ id: 'SUP-' + Date.now(), name, contact_name: contact, phone });
            window.App?.logAction('SUPPLIER_ADD', `Proveedor registrado: ${name}`);
        }

        await window.Storage.save('suppliers', this.suppliers);
        
        const btnRef = document.getElementById('close-sup-modal');
        if (btnRef) btnRef.click(); 

        this.render();
        window.App?.showToast('✅ Proveedor guardado correctamente.');
    },

    async deleteSupplier(id) {
        if (confirm('¿Eliminar este proveedor de forma permanente?')) {
            this.suppliers = this.suppliers.filter(x => x.id !== id);
            await window.Storage.delete('suppliers', id);
            this.render();
            window.App?.showToast('Proveedor eliminado', 'danger');
        }
    },

    // --- MÉTODOS DE ÓRDENES DE COMPRA (PO) ---

    async showAddPOModal(id = null, isReadOnly = false) {
        if (this.suppliers.length === 0) {
            return window.App?.showToast('⚠️ Debes registrar al menos un proveedor primero.', 'warning');
        }

        // Cargar inventario para autocompletado
        this.currentInventory = await window.Storage.get('inventory') || [];

        let po = id ? this.purchase_orders.find(x => x.id === id) : null;
        let today = new Date().toISOString().split('T')[0];

        let modalEl = document.getElementById('po-form-modal');
        if (!modalEl) {
            modalEl = document.createElement('div');
            modalEl.id = 'po-form-modal';
            modalEl.className = 'modal fade shadow';
            document.body.appendChild(modalEl);
        }

        // Recuperar items o usar vacío
        let itemsArr = po ? po.items : [{ sku: '', name: '', qty: 1, unit: 'pza', cost: 0 }];

        const renderItemRows = (items) => {
            return items.map((it, i) => `
                <div class="row g-2 mb-2 po-item-row" data-index="${i}">
                    <div class="col-2"><input type="text" class="form-control small py-1 bg-light border-0 po-sku" placeholder="SKU" value="${it.sku}" list="po-sku-list" onchange="Suppliers.autofillPORow(this)" ${isReadOnly ? 'disabled' : ''}></div>
                    <div class="col-4"><input type="text" class="form-control small py-1 bg-light border-0 po-name" placeholder="Producto" value="${it.name}" list="po-name-list" onchange="Suppliers.autofillPORow(this)" ${isReadOnly ? 'disabled' : ''}></div>
                    <div class="col-2"><input type="number" class="form-control small py-1 bg-light border-0 po-qty" placeholder="Cant." value="${it.qty}" onchange="Suppliers.recalcPO()" ${isReadOnly ? 'disabled' : ''}></div>
                    <div class="col-2"><input type="text" class="form-control small py-1 bg-light border-0 po-unit" placeholder="Ej: pza" value="${it.unit || 'pza'}" ${isReadOnly ? 'disabled' : ''}></div>
                    <div class="col-2"><input type="number" class="form-control small py-1 bg-light border-0 po-cost" placeholder="$0.00" value="${it.cost}" onchange="Suppliers.recalcPO()" ${isReadOnly ? 'disabled' : ''}></div>
                </div>
            `).join('');
        };

        modalEl.innerHTML = `
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content border-0 shadow-lg rounded-4">
                    <div class="modal-header bg-primary text-white border-0 py-3 rounded-top-4">
                        <h5 class="modal-title fw-bold"><i class="bi ${isReadOnly ? 'bi-eye' : (po ? 'bi-pencil-square' : 'bi-plus-circle')} me-2"></i> ${isReadOnly ? 'DETALLE' : (po ? 'EDITAR' : 'NUEVA')} ORDEN DE COMPRA</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" id="close-po-modal"></button>
                    </div>
                    <div class="modal-body p-4">
                        <input type="hidden" id="po-id" value="${po ? po.id : ''}">
                        
                        <div class="row g-3 mb-4">
                            <div class="col-md-6">
                                <label class="form-label small fw-bold text-muted">PROVEEDOR</label>
                                <select class="form-select bg-light border-0 py-2" id="po-supplier" ${isReadOnly ? 'disabled' : ''}>
                                    ${this.suppliers.map(s => `<option value="${s.id}" ${po && po.supplier_id === s.id ? 'selected' : ''}>${s.name}</option>`).join('')}
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small fw-bold text-muted">FECHA ESPERADA DE LLEGADA</label>
                                <input type="date" class="form-control bg-light border-0 py-2" id="po-date" value="${po ? po.expected_date : today}" ${isReadOnly ? 'disabled' : ''}>
                            </div>
                        </div>

                        <div class="mb-4 bg-white p-3 rounded-4 border border-primary border-dashed text-center" style="border-style: dashed !important;">
                            <label class="form-label small fw-bold text-primary mb-2"><i class="bi bi-barcode me-1"></i> ESCANEAR PRODUCTO PARA AGREGAR</label>
                            <input type="text" class="form-control form-control-lg border-0 bg-light text-center fw-bold font-monospace" id="po-scanner-input" placeholder="Escanea código de barras..." ${isReadOnly ? 'disabled' : ''} onkeypress="if(event.key==='Enter'){ Suppliers.handleBarcodeScan(this.value); this.value=''; }">
                        </div>

                        <datalist id="po-sku-list">
                            ${this.currentInventory.map(inv => `<option value="${inv.sku}">${inv.name}</option>`).join('')}
                        </datalist>
                        <datalist id="po-name-list">
                            ${this.currentInventory.map(inv => `<option value="${inv.name}">${inv.sku}</option>`).join('')}
                        </datalist>

                        <h6 class="fw-bold mb-3">Artículos del Pedido</h6>
                        <div class="p-3 bg-light rounded-3 mb-3 border">
                            <div class="row g-2 mb-2">
                                <div class="col-2"><small class="fw-bold text-muted">SKU</small></div>
                                <div class="col-4"><small class="fw-bold text-muted">PRODUCTO</small></div>
                                <div class="col-2"><small class="fw-bold text-muted">CANTIDAD</small></div>
                                <div class="col-2"><small class="fw-bold text-muted">UNIDAD</small></div>
                                <div class="col-2"><small class="fw-bold text-muted">COSTO</small></div>
                            </div>
                            <div id="po-items-container">
                                ${renderItemRows(itemsArr)}
                            </div>
                            ${!isReadOnly ? `<button class="btn btn-sm btn-outline-primary mt-2 fw-bold" onclick="Suppliers.addPORow()"><i class="bi bi-plus"></i> Agregar Fila</button>` : ''}
                        </div>
                        
                        <div class="text-end">
                            <h4 class="fw-bold text-dark mb-0">Total: $<span id="po-total-display">${po ? po.total.toFixed(2) : '0.00'}</span></h4>
                        </div>
                    </div>
                    <div class="modal-footer border-0 p-4 pt-0">
                        <button type="button" class="btn btn-light rounded-pill px-4" data-bs-dismiss="modal">${isReadOnly ? 'CERRAR' : 'CANCELAR'}</button>
                        ${!isReadOnly ? `<button type="button" class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" onclick="Suppliers.savePO()">GUARDAR ORDEN</button>` : ''}
                    </div>
                </div>
            </div>
        `;

        bootstrap.Modal.getOrCreateInstance(modalEl).show();
    },

    handleBarcodeScan(sku) {
        const product = this.currentInventory.find(i => i.sku === sku);
        if (product) {
            // Si ya existe en la lista, aumentar cantidad
            let existingRow = null;
            document.querySelectorAll('.po-item-row').forEach(row => {
                if (row.querySelector('.po-sku').value === sku) existingRow = row;
            });

            if (existingRow) {
                const qtyInput = existingRow.querySelector('.po-qty');
                qtyInput.value = (parseFloat(qtyInput.value) || 0) + 1;
                this.recalcPO();
                window.App?.showToast(`➕ +1 ${product.name}`);
            } else {
                // Agregar nueva fila
                const container = document.getElementById('po-items-container');
                // Limpiar la fila vacía inicial si solo hay una y está vacía
                if (container.children.length === 1) {
                    const firstRow = container.children[0];
                    if (!firstRow.querySelector('.po-sku').value && !firstRow.querySelector('.po-name').value) {
                        container.innerHTML = '';
                    }
                }

                this.addPORow();
                const lastRow = container.lastElementChild;
                lastRow.querySelector('.po-sku').value = product.sku;
                lastRow.querySelector('.po-name').value = product.name;
                lastRow.querySelector('.po-unit').value = product.unit_measure || 'pza';
                lastRow.querySelector('.po-cost').value = product.cost_price || 0;
                this.recalcPO();
                window.App?.showToast(`📦 Añadido: ${product.name}`);
            }
        } else {
            window.App?.showToast('⚠️ Producto no encontrado en inventario.', 'danger');
        }
    },

    addPORow() {
        const container = document.getElementById('po-items-container');
        const index = container.children.length;
        const row = document.createElement('div');
        row.className = 'row g-2 mb-2 po-item-row';
        row.setAttribute('data-index', index);
        row.innerHTML = `
            <div class="col-2"><input type="text" class="form-control small py-1 bg-white border-0 shadow-sm po-sku" placeholder="SKU" list="po-sku-list" onchange="Suppliers.autofillPORow(this)"></div>
            <div class="col-4"><input type="text" class="form-control small py-1 bg-white border-0 shadow-sm po-name" placeholder="Producto" list="po-name-list" onchange="Suppliers.autofillPORow(this)"></div>
            <div class="col-2"><input type="number" class="form-control small py-1 bg-white border-0 shadow-sm po-qty" placeholder="Cant." value="1" onchange="Suppliers.recalcPO()"></div>
            <div class="col-2"><input type="text" class="form-control small py-1 bg-white border-0 shadow-sm po-unit" placeholder="Ej: pza" value="pza"></div>
            <div class="col-2"><input type="number" class="form-control small py-1 bg-white border-0 shadow-sm po-cost" placeholder="$0.00" value="0" onchange="Suppliers.recalcPO()"></div>
        `;
        container.appendChild(row);
    },

    autofillPORow(input) {
        const row = input.closest('.po-item-row');
        const skuInput = row.querySelector('.po-sku');
        const nameInput = row.querySelector('.po-name');
        const unitInput = row.querySelector('.po-unit');
        const costInput = row.querySelector('.po-cost');

        let found = null;
        if (input.classList.contains('po-sku') && input.value) {
            found = this.currentInventory.find(i => i.sku === input.value);
            if (found) nameInput.value = found.name;
        } else if (input.classList.contains('po-name') && input.value) {
            found = this.currentInventory.find(i => i.name === input.value);
            if (found) skuInput.value = found.sku;
        }

        if (found) {
            if (!unitInput.value || unitInput.value === 'pza') unitInput.value = found.unit_measure || 'pza';
            if (parseFloat(costInput.value) === 0 && found.cost_price) {
                costInput.value = found.cost_price;
            } else if (parseFloat(costInput.value) === 0) {
                costInput.value = (found.unit_price * 0.7).toFixed(2); // Costo aproximado
            }
            this.recalcPO();
        }
    },

    recalcPO() {
        let total = 0;
        document.querySelectorAll('.po-item-row').forEach(row => {
            const qty = parseFloat(row.querySelector('.po-qty').value) || 0;
            const cost = parseFloat(row.querySelector('.po-cost').value) || 0;
            total += (qty * cost);
        });
        document.getElementById('po-total-display').innerText = total.toFixed(2);
    },

    async savePO() {
        const id = document.getElementById('po-id').value;
        const supplier_id = document.getElementById('po-supplier').value;
        const expected_date = document.getElementById('po-date').value;
        
        let items = [];
        let total = 0;
        document.querySelectorAll('.po-item-row').forEach(row => {
            const sku = row.querySelector('.po-sku').value.trim();
            const name = row.querySelector('.po-name').value.trim();
            const qty = parseFloat(row.querySelector('.po-qty').value) || 0;
            const unit = row.querySelector('.po-unit').value.trim() || 'pza';
            const cost = parseFloat(row.querySelector('.po-cost').value) || 0;
            
            if (name && qty > 0) {
                items.push({ sku, name, qty, unit, cost });
                total += (qty * cost);
            }
        });

        if (items.length === 0) return window.App?.showToast('Agrega al menos un artículo válido.', 'warning');

        if (id) {
            const idx = this.purchase_orders.findIndex(x => x.id === id);
            this.purchase_orders[idx] = { ...this.purchase_orders[idx], supplier_id, expected_date, items, total };
            window.App?.logAction('PO_UPDATE', `Orden de compra actualizada: $${total}`);
        } else {
            this.purchase_orders.push({
                id: 'PO-' + Date.now(),
                supplier_id,
                expected_date,
                status: 'pending',
                items,
                total
            });
            window.App?.logAction('PO_ADD', `Nueva orden de compra generada: $${total}`);
        }

        await window.Storage.save('purchase_orders', this.purchase_orders);
        
        const btnRef = document.getElementById('close-po-modal');
        if (btnRef) btnRef.click(); 

        this.render();
        window.App?.showToast('✅ Orden de compra guardada.');
    },

    async surtirPO(id) {
        if (!confirm('¿Deseas marcar esta orden como SURTIDA y enviar los productos al inventario?')) return;

        const po = this.purchase_orders.find(x => x.id === id);
        if (!po || po.status !== 'pending') return;

        // Recuperar Inventario
        let inventory = await window.Storage.get('inventory') || [];
        
        // Agregar stock a inventario existente, o crearlo nuevo si no existe.
        po.items.forEach(poItem => {
            // Busca por SKU (o nombre si no hay SKU)
            let existingItem = inventory.find(inv => 
                (inv.sku && poItem.sku && inv.sku === poItem.sku) || 
                (inv.name.toLowerCase() === poItem.name.toLowerCase())
            );

            if (existingItem) {
                let currentQty = parseFloat(existingItem.stock_quantity || 0);
                let currentCost = parseFloat(existingItem.cost_price || 0);
                let addedQty = parseFloat(poItem.qty || 0);
                let addedCost = parseFloat(poItem.cost || 0);
                
                let totalQty = currentQty + addedQty;
                
                if (totalQty > 0) {
                    existingItem.cost_price = ((currentQty * currentCost) + (addedQty * addedCost)) / totalQty;
                } else {
                    existingItem.cost_price = addedCost;
                }
                
                existingItem.stock_quantity = totalQty;
            } else {
                inventory.push({
                    id: 'P' + Date.now() + Math.floor(Math.random()*100),
                    name: poItem.name,
                    sku: poItem.sku || 'PROV-SN',
                    category: 'Proveedor',
                    unit_price: 0, // Se asigna manualmente en inventarios
                    cost_price: parseFloat(poItem.cost), // Precio que viene directo de la orden
                    stock_quantity: parseFloat(poItem.qty),
                    min_stock: 5,
                    unit_measure: poItem.unit || 'pza'
                });
            }
        });

        // Registrar Gasto en Finanzas si es posible
        let fin_records = await window.Storage.get('financial_records') || [];
        fin_records.unshift({
            id: 'F-' + Date.now(),
            type: 'expense',
            description: `Pago a proveedor (Orden ${po.id})`,
            category: 'Insumos',
            amount: po.total,
            timestamp: new Date().toISOString()
        });

        po.status = 'completed';

        // Guardar todo
        await window.Storage.save('inventory', inventory);
        await window.Storage.save('financial_records', fin_records);
        await window.Storage.save('purchase_orders', this.purchase_orders);
        
        window.App?.logAction('PO_COMPLETED', `Orden surtida: ${po.id}. Insumos pasados a inventario.`);
        this.render();
        window.App?.showToast('🎉 Orden surtida. Stock actualizado y gasto registrado.', 'success');
    },

    async deletePO(id) {
        if (confirm('¿Eliminar esta orden de compra?')) {
            this.purchase_orders = this.purchase_orders.filter(x => x.id !== id);
            await window.Storage.delete('purchase_orders', id);
            this.render();
            window.App?.showToast('Orden eliminada', 'danger');
        }
    }
};

window.Suppliers = Suppliers;
