const fs = require('fs');

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

// 1. Fix the Delete Button and "Send to Store" button
const newSalesLogic = `      let actions = \`<button class="action-btn btn-view" onclick="openSalesModal(\${inv.id})">👁️ عرض/تعديل</button>\`;
      if(currentUser && (currentUser.role === 'مدير عام' || currentUser.role.includes('مدير') || currentUser.username === 'admin')) {
         actions += \`<button class="action-btn btn-delete" onclick="deleteInvoice(\${inv.id})">🗑️ حذف</button>\`;
      }
      if(inv.status === 'draft') {
         actions += \`<button class="action-btn" style="background:var(--accent); margin-right:5px;" onclick="sendInvoiceToStore(\${inv.id})">📤 إرسال للمخزن</button>\`;
      }
      if(inv.status === 'posted') {
         actions += \` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = \${inv.id}; openVoucherModal('receipt', \${inv.id}, \${inv.contact_id}); }">سداد 💵</button>\`;
      }

      tbody.innerHTML += \`<tr>`;

const newPurchasesLogic = `      let actions = \`<button class="action-btn btn-view" onclick="openPurchasesModal(\${inv.id})">👁️ عرض/تعديل</button>\`;
      if(currentUser && (currentUser.role === 'مدير عام' || currentUser.role.includes('مدير') || currentUser.username === 'admin')) {
         actions += \`<button class="action-btn btn-delete" onclick="deleteInvoice(\${inv.id})">🗑️ حذف</button>\`;
      }
      if(inv.status === 'draft') {
         actions += \`<button class="action-btn" style="background:var(--accent); margin-right:5px;" onclick="sendInvoiceToStore(\${inv.id})">📤 إرسال للمخزن</button>\`;
      }
      if(inv.status === 'posted') {
         actions += \` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = \${inv.id}; openVoucherModal('payment', \${inv.id}, \${inv.contact_id}); }">سداد 💵</button>\`;
      }

      tbody.innerHTML += \`<tr>`;

spJs = spJs.replace(
    /let actions = `<button class="action-btn btn-view" onclick="openSalesModal\(\$\{inv\.id\}\)">👁️ عرض\/تعديل<\/button>`;[\s\S]*?tbody\.innerHTML \+= `<tr>/,
    newSalesLogic
);

spJs = spJs.replace(
    /let actions = `<button class="action-btn btn-view" onclick="openPurchasesModal\(\$\{inv\.id\}\)">👁️ عرض\/تعديل<\/button>`;[\s\S]*?tbody\.innerHTML \+= `<tr>/,
    newPurchasesLogic
);

// 2. Completely rewrite generateSalesJournal and generatePurchasesJournal
const generateSalesStr = `async function generateSalesJournal(invoice) {
    const existingJ = currentJournals.find(j => j.reference === \`فاتورة مبيعات #\${invoice.id}\`);
    if(existingJ) return; 
    
    let clientAcc = currentAccounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل'));
    let salesAcc = currentAccounts.find(a => a.name === 'إيرادات المبيعات' || a.name === 'إيرادات مبيعات');
    let invAcc = currentAccounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
    let cogsAcc = currentAccounts.find(a => a.name === 'تكلفة البضاعة المباعة');
    
    // Resolve missing accounts safely
    if (typeof window.resolveSystemAccount === 'function') {
        if(!clientAcc) clientAcc = await window.resolveSystemAccount('العملاء', ['أصول متداولة', 'الأصول'], 'assets');
        if(!salesAcc) salesAcc = await window.resolveSystemAccount('إيرادات المبيعات', ['الإيرادات', 'إيرادات'], 'revenues');
        if(!invAcc) invAcc = await window.resolveSystemAccount('مخزون البضاعة', ['أصول متداولة', 'الأصول'], 'assets');
        if(!cogsAcc) cogsAcc = await window.resolveSystemAccount('تكلفة البضاعة المباعة', ['المصروفات', 'مصروفات'], 'expenses');
    }

    let discountAcc = currentAccounts.find(a => a.name === 'خصم مسموح به' || a.name === 'الخصم المسموح به');
    if(!discountAcc && typeof window.resolveSystemAccount === 'function') {
        discountAcc = await window.resolveSystemAccount('الخصم المسموح به', ['المصروفات', 'مصروفات'], 'expenses');
    }

    if(!clientAcc || !salesAcc) {
       alert('تحذير: لا يمكن توليد قيد آلي لأنه لم يتم العثور على حساب "العملاء" أو "إيرادات المبيعات" في دليل الحسابات.');
       return;
    }
    
    // Calculate total discount and COGS
    let totalDiscount = 0;
    let totalCogs = 0;
    (invoice.items || []).forEach(line => {
        const tot = (line.qty * line.price);
        let disc = 0;
        const isPercent = line.discount_type === 'percent' || !line.discount_type;
        if (isPercent) {
            disc = tot * ((line.discount||0) / 100);
        } else {
            disc = line.discount || 0;
        }
        if (disc > tot) disc = tot;
        totalDiscount += disc;

        if(typeof window.balancesCache !== 'undefined') {
            let b = window.balancesCache[line.item_id];
            let avgCost = b ? b.avgCost : 0;
            totalCogs += (line.qty * avgCost);
        }
    });

    const netTotal = invoice.total; // The client pays the net amount
    const grossTotal = netTotal + totalDiscount;

    let totalDebit = 0;

    const journal = {
      id: Date.now() + Math.floor(Math.random()*1000),
      date: invoice.date.split('T')[0],
      reference: \`فاتورة مبيعات #\${invoice.id}\`,
      desc: \`قيد آلي لفاتورة المبيعات رقم \${invoice.id}\`,
      status: 'posted',
      created_by: 'النظام',
      total: 0, // will calculate below
      rows: []
    };

    // Client Debit (Net)
    journal.rows.push({ account_id: clientAcc.id, debit: netTotal, credit: 0, project_id: invoice.project_id });
    totalDebit += netTotal;

    // Discount Debit
    if (totalDiscount > 0 && discountAcc) {
        journal.rows.push({ account_id: discountAcc.id, debit: totalDiscount, credit: 0, project_id: invoice.project_id });
        totalDebit += totalDiscount;
    }

    // Sales Credit (Gross)
    journal.rows.push({ account_id: salesAcc.id, debit: 0, credit: grossTotal, project_id: invoice.project_id });

    // COGS
    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 });
        totalDebit += totalCogs;
    }

    journal.total = totalDebit;
    await window.DB.add('journal_entries', journal);
}`;

spJs = spJs.replace(/async function generateSalesJournal\(invoice\) \{[\s\S]*?await window\.DB\.add\('journal_entries', journal\);\s*\}/, generateSalesStr);


// Now same for Purchases
const generatePurchasesStr = `async function generatePurchasesJournal(invoice) {
    const existingJ = currentJournals.find(j => j.reference === \`فاتورة مشتريات #\${invoice.id}\`);
    if(existingJ) return; // already posted
    
    let supplierAcc = currentAccounts.find(a => a.name.includes('موردين') || a.name.includes('مورد'));
    let invAcc = currentAccounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
    let discountAcc = currentAccounts.find(a => a.name === 'خصم مكتسب' || a.name === 'الخصم المكتسب');

    if (typeof window.resolveSystemAccount === 'function') {
        if(!supplierAcc) supplierAcc = await window.resolveSystemAccount('الموردين', ['التزامات', 'خصوم'], 'liabilities');
        if(!invAcc) invAcc = await window.resolveSystemAccount('مخزون البضاعة', ['أصول متداولة', 'الأصول'], 'assets');
        if(!discountAcc) discountAcc = await window.resolveSystemAccount('الخصم المكتسب', ['الإيرادات', 'إيرادات'], 'revenues');
    }
    
    if(!supplierAcc || !invAcc) {
       alert('تحذير: لا يمكن توليد قيد آلي لأنه لم يتم العثور على حساب "الموردين" أو "المخزون" في دليل الحسابات.');
       return;
    }

    let totalDiscount = 0;
    (invoice.items || []).forEach(line => {
        const tot = (line.qty * line.price);
        let disc = 0;
        const isPercent = line.discount_type === 'percent' || !line.discount_type;
        if (isPercent) {
            disc = tot * ((line.discount||0) / 100);
        } else {
            disc = line.discount || 0;
        }
        if (disc > tot) disc = tot;
        totalDiscount += disc;
    });

    const netTotal = invoice.total;
    const grossTotal = netTotal + totalDiscount;
    let totalDebit = 0;

    const journal = {
      id: Date.now() + Math.floor(Math.random()*1000),
      date: invoice.date.split('T')[0],
      reference: \`فاتورة مشتريات #\${invoice.id}\`,
      desc: \`قيد آلي لفاتورة المشتريات رقم \${invoice.id}\`,
      status: 'posted',
      created_by: 'النظام',
      total: 0,
      rows: []
    };

    // Inventory Debit (Gross cost before discount, because discount reduces liability, wait... actually discount reduces inventory cost typically, or is treated as income)
    // Here we treat it as separate income 'Discount Received'
    journal.rows.push({ account_id: invAcc.id, debit: grossTotal, credit: 0, project_id: invoice.project_id });
    totalDebit += grossTotal;

    // Supplier Credit (Net)
    journal.rows.push({ account_id: supplierAcc.id, debit: 0, credit: netTotal, project_id: invoice.project_id });

    // Discount Received Credit
    if (totalDiscount > 0 && discountAcc) {
        journal.rows.push({ account_id: discountAcc.id, debit: 0, credit: totalDiscount, project_id: invoice.project_id });
    }

    journal.total = totalDebit;
    await window.DB.add('journal_entries', journal);
}`;

spJs = spJs.replace(/async function generatePurchasesJournal\(invoice\) \{[\s\S]*?await window\.DB\.add\('journal_entries', journal\);\s*\}/, generatePurchasesStr);

fs.writeFileSync('d:/برنامج مخازن/sales_purchases_module.js', spJs, '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('Fixed buttons, discount, and COGS.');
