const fs = require('fs');

try {
    let indexHtml = fs.readFileSync('index.html', 'utf8');

    // Remove the Paid Now container completely from sales
    indexHtml = indexHtml.replace(
        /<div id="sales-payment-now-container"[\s\S]*?<\/select>\s*<\/div>\s*<\/div>/g,
        ''
    );
    // Same for purchases
    indexHtml = indexHtml.replace(
        /<div id="purchases-payment-now-container"[\s\S]*?<\/select>\s*<\/div>\s*<\/div>/g,
        ''
    );

    fs.writeFileSync('index.html', indexHtml, 'utf8');

    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');

    // Revert the resolveContactAccount to return ONLY generic accounts
    const newResolver = `
window.resolveContactAccount = async function(contactId, type) {
    let genericName = (type === 'sales' || type === 'receipt') ? 'حسابات العملاء' : 'حسابات الموردين';
    let accountType = (type === 'sales' || type === 'receipt') ? 'assets' : 'liabilities';
    let keywords = (type === 'sales' || type === 'receipt') ? ['عملاء', 'عميل'] : ['موردين', 'مورد'];
    
    // 1. Find generic account
    let genericAcc = currentAccounts.find(a => keywords.some(k => a.name.includes(k)));
    if (genericAcc) return genericAcc;
    
    // 2. Auto-create GENERIC account if missing
    try {
        const newAcc = {
            code: Date.now().toString().slice(-6),
            name: genericName,
            type: accountType,
            parent_id: null,
            balance: 0
        };
        const addedId = await window.DB.add('accounts', newAcc);
        newAcc.id = addedId;
        currentAccounts.push(newAcc);
        if (window.loadData) window.loadData(false);
        return newAcc;
    } catch (e) {
        console.error("Failed to auto-create generic account", e);
        return null;
    }
};
`;
    appFinalJs = appFinalJs.replace(/window\.resolveContactAccount = async function[\s\S]*?catch \(e\) \{\s*console\.error\("Failed to auto-create contact account", e\);\s*return genericAcc;\s*\}\s*\};\s*/, newResolver);

    // Remove auto payment processing from save buttons
    appFinalJs = appFinalJs.replace(/if\(status === 'posted'\) \{\s*await window\.processInvoicePayment\(obj, 'sales'\);\s*await generateSalesJournal\(obj\);\s*\}/g, `if(status === 'posted') { await generateSalesJournal(obj); }`);
    appFinalJs = appFinalJs.replace(/if\(status === 'posted'\) \{\s*await window\.processInvoicePayment\(obj, 'purchases'\);\s*await generatePurchasesJournal\(obj\);\s*\}/g, `if(status === 'posted') { await generatePurchasesJournal(obj); }`);

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');

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

    console.log('Reverted specific customer accounts and removed Paid Now fields.');
} catch (e) {
    console.error('Error patching:', e);
}
