const fs = require('fs');

let spJs = fs.readFileSync('d:/برنامج مخازن/sales_purchases_module.js', 'utf8');

// The replacement logic for COGS in generateSalesJournal
const cogsLogic = `    // Calculate COGS
    let totalCogs = 0;
    if(typeof window.balancesCache !== 'undefined') {
        (invoice.items || []).forEach(it => {
            let b = window.balancesCache[it.item_id];
            let avgCost = b ? b.avgCost : 0;
            totalCogs += (it.qty * avgCost);
        });
    }

    if (totalCogs > 0 && cogsAcc && invAcc) {
        journal.rows.push({ account_id: cogsAcc.id, debit: totalCogs, credit: 0, project_id: invoice.project_id });
        journal.rows.push({ account_id: invAcc.id, debit: 0, credit: totalCogs, project_id: invoice.project_id });
    }

    await window.DB.add('journal_entries', journal);`;

spJs = spJs.replace(/\/\/ If we want to add COGS and Inventory, we need cost calculation\. For now, Sales value\.[\s\S]*?await window\.DB\.add\('journal_entries', journal\);/, cogsLogic);

fs.writeFileSync('d:/برنامج مخازن/sales_purchases_module.js', spJs, 'utf8');

// Now also patch generateSalesReturnJournal in vouchers_returns.js
let vrJs = fs.readFileSync('d:/برنامج مخازن/vouchers_returns.js', 'utf8');
const returnCogsLogic = `      { account_id: salesReturnAcc.id, debit: invoice.total, credit: 0, project_id: invoice.project_id },
      { account_id: contact.account_id, debit: 0, credit: invoice.total, project_id: invoice.project_id }
    ];

    const cogsAcc = currentAccounts.find(a => a.name === 'تكلفة البضاعة المباعة');
    const invAcc = currentAccounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
    let totalCogs = 0;
    if(typeof window.balancesCache !== 'undefined') {
        (invoice.items || []).forEach(it => {
            let b = window.balancesCache[it.item_id];
            let avgCost = b ? b.avgCost : 0;
            totalCogs += (it.qty * avgCost);
        });
    }

    if (totalCogs > 0 && cogsAcc && invAcc) {
        journal.rows.push({ account_id: invAcc.id, debit: totalCogs, credit: 0, project_id: invoice.project_id });
        journal.rows.push({ account_id: cogsAcc.id, debit: 0, credit: totalCogs, project_id: invoice.project_id });
    }`;

vrJs = vrJs.replace(/\{\s*account_id:\s*salesReturnAcc\.id,[\s\S]*?credit:\s*invoice\.total, project_id:\s*invoice\.project_id\s*\}\s*\];/, returnCogsLogic);

fs.writeFileSync('d:/برنامج مخازن/vouchers_returns.js', vrJs, 'utf8');

let html = fs.readFileSync('d:/برنامج مخازن/index.html', 'utf8');
const version = Date.now().toString();
html = html.replace(/v=\d+/g, 'v=' + version);
fs.writeFileSync('d:/برنامج مخازن/index.html', html, 'utf8');

console.log('Added COGS to sales and returns journals.');
