const fs = require('fs');

try {
    let vrJs = fs.readFileSync('vouchers_returns.js', 'utf8');

    // Add global arrays if missing
    if (!vrJs.includes('window.currentSalesReturnLines = [];')) {
        vrJs = 'window.currentSalesReturnLines = [];\nwindow.currentPurchasesReturnLines = [];\n' + vrJs;
    }

    // 1. ADD loadSalesForReturn and populateSalesReturnFromInvoice
    const extraFunctions = `
window.loadSalesForReturn = function() {
    const contactId = document.getElementById('sales-returns-contact').value;
    const invSelect = document.getElementById('sales-returns-original-invoice');
    if(!invSelect) return;
    invSelect.innerHTML = '<option value="">-- اختر الفاتورة الأصلية --</option>';
    if (!contactId) return;

    const invoices = (window.allInvoices || []).filter(inv => inv.type === 'sales' && inv.contact_id == contactId && inv.status === 'posted');
    
    invoices.forEach(inv => {
        invSelect.innerHTML += \`<option value="\${inv.id}">فاتورة مبيعات #\${inv.id} - \${new Date(inv.date).toLocaleDateString('ar-EG')} - \${inv.total?.toLocaleString('en-US') || 0} ج.م</option>\`;
    });
};

window.populateSalesReturnFromInvoice = function() {
    const invId = document.getElementById('sales-returns-original-invoice').value;
    if (!invId) {
        window.currentSalesReturnLines = [];
        if(typeof window.renderSalesReturnsLines === 'function') window.renderSalesReturnsLines();
        return;
    }

    const invoice = (window.allInvoices || []).find(inv => inv.id == invId);
    if (!invoice) return;

    if (invoice.from_warehouse_id) {
        const whSelect = document.getElementById('sales-returns-warehouse');
        if(whSelect) whSelect.value = invoice.from_warehouse_id;
    }
    if (invoice.project_id) {
        const projSelect = document.getElementById('sales-returns-project');
        if(projSelect) projSelect.value = invoice.project_id;
    }

    window.currentSalesReturnLines = JSON.parse(JSON.stringify(invoice.items || []));
    if(typeof window.renderSalesReturnsLines === 'function') window.renderSalesReturnsLines();
};

window.loadPurchasesForReturn = function() {
    const contactId = document.getElementById('purchases-returns-contact').value;
    const invSelect = document.getElementById('purchases-returns-original-invoice');
    if(!invSelect) return;
    invSelect.innerHTML = '<option value="">-- اختر الفاتورة الأصلية --</option>';
    if (!contactId) return;

    const invoices = (window.allInvoices || []).filter(inv => inv.type === 'purchases' && inv.contact_id == contactId && inv.status === 'posted');
    
    invoices.forEach(inv => {
        invSelect.innerHTML += \`<option value="\${inv.id}">فاتورة مشتريات #\${inv.id} - \${new Date(inv.date).toLocaleDateString('ar-EG')} - \${inv.total?.toLocaleString('en-US') || 0} ج.م</option>\`;
    });
};

window.populatePurchasesReturnFromInvoice = function() {
    const invId = document.getElementById('purchases-returns-original-invoice').value;
    if (!invId) {
        window.currentPurchasesReturnLines = [];
        if(typeof window.renderPurchasesReturnsLines === 'function') window.renderPurchasesReturnsLines();
        return;
    }

    const invoice = (window.allInvoices || []).find(inv => inv.id == invId);
    if (!invoice) return;

    if (invoice.to_warehouse_id) {
        const whSelect = document.getElementById('purchases-returns-warehouse');
        if(whSelect) whSelect.value = invoice.to_warehouse_id;
    }
    if (invoice.project_id) {
        const projSelect = document.getElementById('purchases-returns-project');
        if(projSelect) projSelect.value = invoice.project_id;
    }

    window.currentPurchasesReturnLines = JSON.parse(JSON.stringify(invoice.items || []));
    if(typeof window.renderPurchasesReturnsLines === 'function') window.renderPurchasesReturnsLines();
};

window.renderSalesReturnsLines = function() {
    const tbody = document.getElementById('sales-returns-lines-tbody');
    if(!tbody) return;
    tbody.innerHTML = '';
    let total = 0;
    (window.currentSalesReturnLines || []).forEach((line, idx) => {
        const lineTotalBeforeDiscount = (line.qty * line.price);
        let lineDiscountValue = parseFloat(line.discount) || 0;
        if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }
        const lineTotal = lineTotalBeforeDiscount - lineDiscountValue;
        total += lineTotal;
        
        tbody.innerHTML += \`<tr>
            <td>\${line.item_name || (window.currentItems?.find(i=>i.id==line.item_id)?.name || '')}</td>
            <td><input type="number" min="0" step="0.01" value="\${line.qty}" onchange="updateSalesReturnQty(\${idx}, this.value)" style="width:60px;"></td>
            <td>\${line.price}</td>
            <td>\${line.discountType === 'percent' ? line.discount + '%' : lineDiscountValue}</td>
            <td>\${lineTotal.toLocaleString('en-US')}</td>
            <td><button class="action-btn btn-delete" onclick="deleteSalesReturnLine(\${idx})">حذف</button></td>
        </tr>\`;
    });
    
    const totalEl = document.getElementById('sales-returns-total');
    if(totalEl) totalEl.value = total.toFixed(2);
};

window.updateSalesReturnQty = function(idx, newQty) {
    window.currentSalesReturnLines[idx].qty = parseFloat(newQty) || 0;
    window.renderSalesReturnsLines();
};

window.deleteSalesReturnLine = function(idx) {
    window.currentSalesReturnLines.splice(idx, 1);
    window.renderSalesReturnsLines();
};

window.renderPurchasesReturnsLines = function() {
    const tbody = document.getElementById('purchases-returns-lines-tbody');
    if(!tbody) return;
    tbody.innerHTML = '';
    let total = 0;
    (window.currentPurchasesReturnLines || []).forEach((line, idx) => {
        const lineTotalBeforeDiscount = (line.qty * line.price);
        let lineDiscountValue = parseFloat(line.discount) || 0;
        if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }
        const lineTotal = lineTotalBeforeDiscount - lineDiscountValue;
        total += lineTotal;
        
        tbody.innerHTML += \`<tr>
            <td>\${line.item_name || (window.currentItems?.find(i=>i.id==line.item_id)?.name || '')}</td>
            <td><input type="number" min="0" step="0.01" value="\${line.qty}" onchange="updatePurchasesReturnQty(\${idx}, this.value)" style="width:60px;"></td>
            <td>\${line.price}</td>
            <td>\${line.discountType === 'percent' ? line.discount + '%' : lineDiscountValue}</td>
            <td>\${lineTotal.toLocaleString('en-US')}</td>
            <td><button class="action-btn btn-delete" onclick="deletePurchasesReturnLine(\${idx})">حذف</button></td>
        </tr>\`;
    });
    
    const totalEl = document.getElementById('purchases-returns-total');
    if(totalEl) totalEl.value = total.toFixed(2);
};

window.updatePurchasesReturnQty = function(idx, newQty) {
    window.currentPurchasesReturnLines[idx].qty = parseFloat(newQty) || 0;
    window.renderPurchasesReturnsLines();
};

window.deletePurchasesReturnLine = function(idx) {
    window.currentPurchasesReturnLines.splice(idx, 1);
    window.renderPurchasesReturnsLines();
};
\n`;

    if(!vrJs.includes('window.loadSalesForReturn')) {
        vrJs += extraFunctions;
    }

    // UPDATE EDIT FUNCTIONS
    vrJs = vrJs.replace(
        /window\.editSalesReturn = function\(id\) \{[\s\S]*?document\.getElementById\('sales-returns-modal'\)\.classList\.add\('active'\);\s*\};/m,
        `window.editSalesReturn = function(id) {
    const r = allInvoices.find(v => v.id === id);
    if(!r) return;
    document.getElementById('sales-returns-modal-title').innerText = 'عرض / تعديل مرتجع مبيعات';
    document.getElementById('edit-sales-returns-id').value = r.id;
    document.getElementById('sales-returns-date').value = r.date.slice(0, 16);
    document.getElementById('sales-returns-doc-no').value = r.doc_no || '';
    
    const contactSelect = document.getElementById('sales-returns-contact');
    contactSelect.innerHTML = '<option value="">-- اختر العميل --</option>';
    currentContacts.forEach(c => {
        contactSelect.innerHTML += \`<option value="\${c.id}" \${c.id == r.contact_id ? 'selected' : ''}>\${c.name}</option>\`;
    });
    window.loadSalesForReturn();
    
    setTimeout(() => {
       const invSel = document.getElementById('sales-returns-original-invoice');
       if(invSel) invSel.value = r.linked_invoice_id || '';
    }, 100);

    const treasurySelect = document.getElementById('sales-returns-treasury');
    treasurySelect.innerHTML = '<option value="">-- آجل --</option>';
    currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('بنك') || a.name.includes('نقد')).forEach(a => {
        treasurySelect.innerHTML += \`<option value="\${a.id}" \${a.id == r.treasury_account_id ? 'selected' : ''}>\${a.name}</option>\`;
    });

    document.getElementById('sales-returns-notes').value = r.notes || '';
    document.getElementById('sales-returns-status').value = r.status || 'draft';
    
    if (r.status === 'posted') {
        document.getElementById('btn-save-sales-returns').style.display = 'none';
    } else {
        document.getElementById('btn-save-sales-returns').style.display = 'inline-block';
    }
    
    window.currentSalesReturnLines = r.items ? JSON.parse(JSON.stringify(r.items)) : [];
    window.renderSalesReturnsLines();

    document.getElementById('sales-returns-modal').classList.add('active');
};`
    );

    vrJs = vrJs.replace(
        /window\.editPurchasesReturn = function\(id\) \{[\s\S]*?document\.getElementById\('purchases-returns-modal'\)\.classList\.add\('active'\);\s*\};/m,
        `window.editPurchasesReturn = function(id) {
    const r = allInvoices.find(v => v.id === id);
    if(!r) return;
    document.getElementById('purchases-returns-modal-title').innerText = 'عرض / تعديل مرتجع مشتريات';
    document.getElementById('edit-purchases-returns-id').value = r.id;
    document.getElementById('purchases-returns-date').value = r.date.slice(0, 16);
    document.getElementById('purchases-returns-doc-no').value = r.doc_no || '';
    
    const contactSelect = document.getElementById('purchases-returns-contact');
    contactSelect.innerHTML = '<option value="">-- اختر المورد --</option>';
    currentContacts.forEach(c => {
        contactSelect.innerHTML += \`<option value="\${c.id}" \${c.id == r.contact_id ? 'selected' : ''}>\${c.name}</option>\`;
    });
    window.loadPurchasesForReturn();

    setTimeout(() => {
       const invSel = document.getElementById('purchases-returns-original-invoice');
       if(invSel) invSel.value = r.linked_invoice_id || '';
    }, 100);

    const treasurySelect = document.getElementById('purchases-returns-treasury');
    treasurySelect.innerHTML = '<option value="">-- آجل --</option>';
    currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('بنك') || a.name.includes('نقد')).forEach(a => {
        treasurySelect.innerHTML += \`<option value="\${a.id}" \${a.id == r.treasury_account_id ? 'selected' : ''}>\${a.name}</option>\`;
    });

    document.getElementById('purchases-returns-notes').value = r.notes || '';
    document.getElementById('purchases-returns-status').value = r.status || 'draft';
    
    if (r.status === 'posted') {
        document.getElementById('btn-save-purchases-returns').style.display = 'none';
    } else {
        document.getElementById('btn-save-purchases-returns').style.display = 'inline-block';
    }
    
    window.currentPurchasesReturnLines = r.items ? JSON.parse(JSON.stringify(r.items)) : [];
    window.renderPurchasesReturnsLines();

    document.getElementById('purchases-returns-modal').classList.add('active');
};`
    );

    // UPDATE SAVE LOGIC FOR SALES RETURNS
    vrJs = vrJs.replace(
        /const r = \{\s*type: 'sales_return',[\s\S]*?created_by: currentUser \? currentUser\.username : 'غير معروف'\s*\};/m,
        `const origInv = document.getElementById('sales-returns-original-invoice')?.value;
        const whId = document.getElementById('sales-returns-warehouse')?.value;
        const projId = document.getElementById('sales-returns-project')?.value;
        
        let netTotal = 0;
        (window.currentSalesReturnLines || []).forEach(line => {
            const tot = (line.qty * line.price);
            let d = parseFloat(line.discount) || 0;
            if(line.discountType === 'percent') d = tot * (d/100);
            netTotal += (tot - d);
        });
        // Override total amount with calculated amount to be exact
        const finalAmount = netTotal > 0 ? netTotal : amount;
        
        const r = {
          type: 'sales_return',
          date: date,
          doc_no: docNo,
          contact_id: parseInt(contactId),
          treasury_account_id: treasuryId ? parseInt(treasuryId) : null,
          from_warehouse_id: whId ? parseInt(whId) : null,
          project_id: projId ? parseInt(projId) : null,
          linked_invoice_id: origInv ? parseInt(origInv) : null,
          total_amount: finalAmount,
          notes: notes,
          status: status,
          items: window.currentSalesReturnLines || [],
          created_by: currentUser ? currentUser.username : 'غير معروف'
        };`
    );

    // UPDATE SAVE LOGIC FOR PURCHASES RETURNS
    vrJs = vrJs.replace(
        /const r = \{\s*type: 'purchases_return',[\s\S]*?created_by: currentUser \? currentUser\.username : 'غير معروف'\s*\};/m,
        `const origInv = document.getElementById('purchases-returns-original-invoice')?.value;
        const whId = document.getElementById('purchases-returns-warehouse')?.value;
        const projId = document.getElementById('purchases-returns-project')?.value;

        let netTotal = 0;
        (window.currentPurchasesReturnLines || []).forEach(line => {
            const tot = (line.qty * line.price);
            let d = parseFloat(line.discount) || 0;
            if(line.discountType === 'percent') d = tot * (d/100);
            netTotal += (tot - d);
        });
        const finalAmount = netTotal > 0 ? netTotal : amount;
        
        const r = {
          type: 'purchases_return',
          date: date,
          doc_no: docNo,
          contact_id: parseInt(contactId),
          treasury_account_id: treasuryId ? parseInt(treasuryId) : null,
          to_warehouse_id: whId ? parseInt(whId) : null,
          project_id: projId ? parseInt(projId) : null,
          linked_invoice_id: origInv ? parseInt(origInv) : null,
          total_amount: finalAmount,
          notes: notes,
          status: status,
          items: window.currentPurchasesReturnLines || [],
          created_by: currentUser ? currentUser.username : 'غير معروف'
        };`
    );

    fs.writeFileSync('vouchers_returns.js', vrJs, 'utf8');
    
    // Add call to clear items on open return modal
    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');
    
    // We update HTML index to ensure onchange exists
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    
    if(!indexHtml.includes('onchange="loadSalesForReturn()"')) {
        indexHtml = indexHtml.replace(/id="sales-returns-contact"/g, 'id="sales-returns-contact" onchange="loadSalesForReturn()"');
    }
    if(!indexHtml.includes('onchange="loadPurchasesForReturn()"')) {
        indexHtml = indexHtml.replace(/id="purchases-returns-contact"/g, 'id="purchases-returns-contact" onchange="loadPurchasesForReturn()"');
    }

    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/vouchers_returns\.js\?v=\d+/g, 'vouchers_returns.js?v=' + timestamp);
    fs.writeFileSync('index.html', indexHtml, 'utf8');

    console.log('Returns logic updated successfully.');
} catch (e) {
    console.error('Error patching returns logic:', e);
}
