const fs = require('fs');

// 1. App Final - Modify refreshContactStatement
let appFinal = fs.readFileSync('app_final.js', 'utf8');
const searchStr = `  // Gather Invoices (Sales, Purchases, Returns)
  allInvoices.forEach(inv => {`;

const abstractsLogic = `
  // Gather Client Abstracts
  if (typeof currentClientAbstracts !== 'undefined') {
      currentClientAbstracts.forEach(ab => {
          if (ab.status === 'approved' && ab.client_name) {
             const proj = (typeof currentProjects !== 'undefined') ? currentProjects.find(p => String(p.id) === String(ab.project_id)) : null;
             const isMatch = (proj && String(proj.client) === c.name) || String(ab.client_name) === c.name || (proj && String(proj.contact_id) === String(contactId));
             if (isMatch) {
                 const gross = parseFloat(ab.gross_value) || 0;
                 const net = parseFloat(ab.net_value) || 0;
                 const tax = parseFloat(ab.tax_value) || 0;
                 const ret = parseFloat(ab.retention_value) || 0;
                 const advance = parseFloat(ab.advance_payment) || 0;
                 
                 // 1. Gross Debt
                 records.push({ date: ab.date, type: 'مستخلص إيراد رقم ' + (ab.abstract_number||ab.id), ref: '#' + ab.id, notes: 'إجمالي الأعمال للمستخلص', debit: gross, credit: 0 });
                 
                 // 2. Deductions (Credits reducing the debt)
                 if(tax > 0) records.push({ date: ab.date, type: 'استقطاع ضرائب', ref: '#' + ab.id, notes: 'ضرائب مستخلص إيراد', debit: 0, credit: tax });
                 if(ret > 0) records.push({ date: ab.date, type: 'استقطاع ضمان أعمال', ref: '#' + ab.id, notes: 'ضمان أعمال مستخلص إيراد', debit: 0, credit: ret });
                 if(advance > 0) records.push({ date: ab.date, type: 'استنزاف دفعة مقدمة', ref: '#' + ab.id, notes: 'خصم دفعات مقدمة من المستخلص', debit: 0, credit: advance });
                 
                 // The balance change is now exactly Net Amount!
             }
          }
      });
  }

  // Gather Subcontract Abstracts
  if (typeof currentSubcontractAbstracts !== 'undefined') {
      currentSubcontractAbstracts.forEach(ab => {
          if (ab.status === 'approved') {
              const cont = (typeof currentSubcontracts !== 'undefined') ? currentSubcontracts.find(c => String(c.id) === String(ab.contract_id)) : null;
              if (cont && String(cont.subcontractor_id) === String(contactId)) {
                 const gross = parseFloat(ab.gross_value) || 0;
                 const net = parseFloat(ab.net_value) || 0;
                 const ret = parseFloat(ab.retention_value) || 0;
                 const tax = parseFloat(ab.tax_value) || 0;
                 const advance = parseFloat(ab.advance_payment) || 0;
                 
                 // 1. Gross Credit (We owe them)
                 records.push({ date: ab.date, type: 'مستخلص مقاول باطن رقم ' + (ab.abstract_number||ab.id), ref: '#' + ab.id, notes: 'إجمالي مستخلص مقاول الباطن', debit: 0, credit: gross });
                 
                 // 2. Deductions (Debits reducing our debt to them)
                 if(tax > 0) records.push({ date: ab.date, type: 'خصم ضرائب', ref: '#' + ab.id, notes: 'ضرائب مخصومة من المستخلص', debit: tax, credit: 0 });
                 if(ret > 0) records.push({ date: ab.date, type: 'خصم تأمينات/ضمان', ref: '#' + ab.id, notes: 'ضمان أعمال مخصوم من المستخلص', debit: ret, credit: 0 });
                 if(advance > 0) records.push({ date: ab.date, type: 'خصم دفعة مقدمة', ref: '#' + ab.id, notes: 'دفعة مقدمة مخصومة', debit: advance, credit: 0 });
              }
          }
      });
  }
`;

if(appFinal.indexOf('// Gather Client Abstracts') === -1) {
    appFinal = appFinal.replace(searchStr, abstractsLogic + '\n' + searchStr);
    fs.writeFileSync('app_final.js', appFinal, 'utf8');
}

// 2. Contractors Module - generateClientAbstractJournal
let contMod = fs.readFileSync('contractors_module.js', 'utf8');

const clientJournalLogic = `
window.generateClientAbstractJournal = async function(ab) {
    if(!ab || !window.resolveContactAccount || !window.resolveSystemAccount) return;
    
    const proj = (typeof currentProjects !== 'undefined') ? currentProjects.find(p => String(p.id) === String(ab.project_id)) : null;
    const clientName = proj ? proj.client : ab.client_name;
    const contact = (typeof currentContacts !== 'undefined') ? currentContacts.find(c => c.name === clientName) : null;
    
    const clientAcc = contact ? await window.resolveContactAccount(contact.id, 'sales') : await window.resolveSystemAccount('حسابات العملاء', ['أصول'], 'assets');
    const revAcc = await window.resolveSystemAccount('إيرادات مستخلصات', ['إيرادات'], 'revenues');
    
    let rows = [];
    const gross = parseFloat(ab.gross_value) || 0;
    const net = parseFloat(ab.net_value) || 0;
    const tax = parseFloat(ab.tax_value) || 0;
    const ret = parseFloat(ab.retention_value) || 0;
    const advance = parseFloat(ab.advance_payment) || 0;
    
    // Debit Client
    if(net > 0) rows.push({ account_id: clientAcc.id, debit: net, credit: 0, project_id: ab.project_id });
    
    // Debit Taxes
    if(tax > 0) {
        const taxAcc = await window.resolveSystemAccount('ضرائب خصم من المنبع', ['أصول', 'ضرائب'], 'assets');
        rows.push({ account_id: taxAcc.id, debit: tax, credit: 0, project_id: ab.project_id });
    }
    
    // Debit Retention
    if(ret > 0) {
        const retAcc = await window.resolveSystemAccount('تأمينات ضمان أعمال', ['أصول', 'تأمينات'], 'assets');
        rows.push({ account_id: retAcc.id, debit: ret, credit: 0, project_id: ab.project_id });
    }
    
    // Debit Advance
    if(advance > 0) {
        const advAcc = await window.resolveSystemAccount('دفعات مقدمة من العملاء', ['خصوم'], 'liabilities');
        rows.push({ account_id: advAcc.id, debit: advance, credit: 0, project_id: ab.project_id });
    }
    
    // Credit Revenue
    if(gross > 0) rows.push({ account_id: revAcc.id, debit: 0, credit: gross, project_id: ab.project_id });
    
    const journalObj = {
        date: ab.date || new Date().toISOString().split('T')[0],
        reference: 'CAB-' + (ab.abstract_number || ab.id),
        desc: 'استحقاق مستخلص إيراد رقم ' + (ab.abstract_number || ab.id) + ' لمشروع ' + (proj ? proj.name : ''),
        status: 'posted',
        created_by: 'النظام',
        total: gross,
        rows: rows
    };
    
    await window.DB.add('journal_entries', journalObj);
};
`;

if (contMod.indexOf('window.generateClientAbstractJournal') === -1) {
    contMod += '\n' + clientJournalLogic;
    contMod = contMod.replace(/ab\.status = 'approved';\s*await window\.DB\.update\('client_abstracts', ab\);/g, "ab.status = 'approved';\n            await window.DB.update('client_abstracts', ab);\n            await window.generateClientAbstractJournal(ab);");
    fs.writeFileSync('contractors_module.js', contMod, 'utf8');
}

// 3. Subcontracts Module - fix approveAbstract
let subMod = fs.readFileSync('subcontracts.js', 'utf8');

const subJournalLogic = `
window.generateSubcontractAbstractJournal = async function(a) {
    if(!a || !window.resolveContactAccount || !window.resolveSystemAccount) return;
    
    const cont = currentSubcontracts.find(c => c.id == a.contract_id);
    if (!cont) return;
    
    const supAcc = await window.resolveContactAccount(cont.subcontractor_id, 'purchases');
    const costAcc = await window.resolveSystemAccount('تكاليف مقاولي الباطن', ['مصروفات', 'تكاليف'], 'expenses');
    
    let rows = [];
    const gross = parseFloat(a.gross_value) || 0;
    const net = parseFloat(a.net_value) || 0;
    const tax = parseFloat(a.tax_value) || 0;
    const ret = parseFloat(a.retention_value) || 0;
    const advance = parseFloat(a.advance_payment) || 0;
    
    // Debit Costs (Gross)
    if(gross > 0) rows.push({ account_id: costAcc.id, debit: gross, credit: 0, project_id: cont.project_id });
    
    // Credit Supplier (Net)
    if(net > 0) rows.push({ account_id: supAcc.id, debit: 0, credit: net, project_id: cont.project_id });
    
    // Credit Taxes
    if(tax > 0) {
        const taxAcc = await window.resolveSystemAccount('ضرائب خصم لحساب المصلحة', ['خصوم', 'ضرائب'], 'liabilities');
        rows.push({ account_id: taxAcc.id, debit: 0, credit: tax, project_id: cont.project_id });
    }
    
    // Credit Retention
    if(ret > 0) {
        const retAcc = await window.resolveSystemAccount('تأمينات محتجزة لمقاولي الباطن', ['خصوم', 'تأمينات'], 'liabilities');
        rows.push({ account_id: retAcc.id, debit: 0, credit: ret, project_id: cont.project_id });
    }
    
    // Credit Advance
    if(advance > 0) {
        const advAcc = await window.resolveSystemAccount('دفعات مقدمة لمقاولي الباطن', ['أصول', 'دفعات'], 'assets');
        rows.push({ account_id: advAcc.id, debit: 0, credit: advance, project_id: cont.project_id });
    }
    
    const journalObj = {
        date: a.date || new Date().toISOString().split('T')[0],
        reference: 'SAB-' + (a.abstract_number || a.id),
        desc: 'استحقاق مستخلص مقاول باطن رقم ' + (a.abstract_number || a.id),
        status: 'posted',
        created_by: 'النظام',
        total: gross,
        rows: rows
    };
    
    await window.DB.add('journal_entries', journalObj);
};
`;

const oldApprove = `const journalEntry = {
                    date: new Date().toISOString().split('T')[0],
                    reference: 'SUB-ABS-' + a.abstract_number,
                    description: 'استحقاق مستخلص مقاول باطن رقم ' + a.abstract_number,
                    lines: [
                        { account_name: 'تكاليف مقاولي الباطن', debit: parseFloat(a.net_value)||0, credit: 0 },
                        { account_name: 'دائنو مقاولي الباطن', debit: 0, credit: parseFloat(a.net_value)||0, contact_id: cont.subcontractor_id }
                    ],
                    total: parseFloat(a.net_value)||0
                };
                await window.DB.add('journal_entries', journalEntry);`;

if(subMod.indexOf('window.generateSubcontractAbstractJournal') === -1) {
    subMod += '\n' + subJournalLogic;
    subMod = subMod.replace(oldApprove, "await window.generateSubcontractAbstractJournal(a);");
    fs.writeFileSync('subcontracts.js', subMod, 'utf8');
}

let indexHtml = fs.readFileSync('index.html', 'utf8');
indexHtml = indexHtml.replace(/v=20260610p/g, 'v=20260610q');
fs.writeFileSync('index.html', indexHtml, 'utf8');

console.log('Fixed accounting for abstracts');
