const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');

    // 1. Patch btn-approve-storekeeper to recalculate total
    js = js.replace(/(\(inv\.items\s*\|\|\s*\[\]\)\.forEach\(\(it,\s*idx\)\s*=>\s*\{[\s\S]*?it\.qty\s*=\s*actQty;[\s\S]*?\}\);)/,
        `let newTotal = 0;
  $1
  (inv.items || []).forEach(it => { newTotal += (it.qty * (it.price || 0)); });
  inv.total = newTotal;
  inv.total_amount = newTotal;`);

    // 2. Patch generatePurchasesJournal to handle is_from_settlement
    const journalSearch = `const supplierAcc = currentAccounts.find(a => a.name.includes('مورد'));
  const invAcc = currentAccounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
  
  if(!supplierAcc || !invAcc) {`;
    
    const journalReplace = `const supplierAcc = currentAccounts.find(a => a.name.includes('مورد'));
  const invAcc = currentAccounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
  
  let creditAccountId = supplierAcc ? supplierAcc.id : null;
  if (invoice.is_from_settlement && invoice.custody_account_id) {
      creditAccountId = invoice.custody_account_id;
  }
  
  if(!creditAccountId || !invAcc) {`;

    js = js.replace(journalSearch, journalReplace);
    js = js.replace(/account_id:\s*supplierAcc\.id/g, "account_id: creditAccountId");


    // 3. Patch approveSettlement
    const approveStart = js.indexOf('window.approveSettlement = async function(id) {');
    const approveEnd = js.indexOf('window.deleteSettlement = async function(id) {');
    
    const newApproveLogic = `window.approveSettlement = async function(id) {
    if (!confirm('هل أنت متأكد من اعتماد هذه التسوية؟ للمصروفات سيتم عمل قيد، وللمخزون سيتم إرساله لاعتماد أمين المخزن.')) return;
    
    const s = allInvoices.find(i => i.id === id);
    if (!s || s.status !== 'pending') return;
    
    try {
        let expensesTotal = 0;
        const journalLines = [];
        const inventoryByWarehouse = {};
        
        // Loop over items and separate logic
        for (let it of s.items) {
            const lineTotal = it.qty * it.price;
            
            if (it.item_type === 'expense') {
                expensesTotal += lineTotal;
                const expAccId = await ensureExpenseAccountExists(it.expense_name);
                journalLines.push({ account_id: expAccId, debit: lineTotal, credit: 0, notes: 'تسوية مصروفات لعهدة رقم ' + s.id, project_id: it.project_id });
            } else if (it.item_type === 'inventory') {
                const whId = it.warehouse_id || s.warehouse_id;
                if (!inventoryByWarehouse[whId]) inventoryByWarehouse[whId] = [];
                inventoryByWarehouse[whId].push(it);
            }
        }
        
        // If there are expenses, create a direct Journal Entry
        if (expensesTotal > 0 && journalLines.length > 0) {
            journalLines.push({ account_id: s.custody_account_id, debit: 0, credit: expensesTotal, notes: 'منصرف تسوية عهدة رقم ' + s.id });
            const je = {
                date: s.date,
                description: 'اعتماد مصروفات تسوية عهدة رقم ' + s.id,
                lines: journalLines,
                user: currentUser.username,
                type: 'settlement',
                ref_id: s.id
            };
            await window.DB.add('journal_entries', je);
        }

        // For inventory items, create "purchases" invoices pending storekeeper approval
        for (let whId in inventoryByWarehouse) {
            const items = inventoryByWarehouse[whId];
            let invTotal = 0;
            items.forEach(it => invTotal += (it.qty * it.price));
            
            const whName = currentWarehouses.find(w => w.id == whId)?.name || '';
            const custodyName = currentAccounts.find(a => a.id == s.custody_account_id)?.name || 'العهدة';

            const newInv = {
                type: 'purchases',
                date: new Date().toISOString(),
                user: currentUser.username,
                contact_name: custodyName, // Show custody as supplier visually
                to_warehouse_id: parseInt(whId),
                to_warehouse_name: whName,
                status: 'pending_store',
                is_from_settlement: true,
                custody_account_id: s.custody_account_id,
                settlement_ref: s.id,
                total: invTotal,
                total_amount: invTotal,
                items: items,
                notes: 'تلقائي من تسوية عهدة رقم ' + s.id
            };
            
            const newInvId = await window.DB.add('transactions', newInv);
            if (typeof window.sendInvoiceToStore === 'function') {
                await window.sendInvoiceToStore(newInvId);
            }
        }
        
        // Update settlement status
        s.status = 'posted';
        await window.DB.update('transactions', s);
        
        alert('تم اعتماد التسوية! تم توليد قيود المصروفات وإرسال بنود المخزون لأمين المخزن.');
        await loadData();
        if (typeof renderSettlements === 'function') renderSettlements();
        
    } catch(e) {
        alert("خطأ أثناء الاعتماد: " + e.message);
    }
}

`;
    
    js = js.substring(0, approveStart) + newApproveLogic + js.substring(approveEnd);
    
    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Successfully patched workflow for settlements + storekeepers!');
}

// Cache buster
if (fs.existsSync('index.html')) {
    let html = fs.readFileSync('index.html', 'utf8');
    html = html.replace(/v=\d+/g, 'v=' + Date.now());
    fs.writeFileSync('index.html', html, 'utf8');
}
