const fs = require('fs');
let code = fs.readFileSync('app_final.js', 'utf8');

const targetStr = `
                <td>
                    <button class="btn btn-sm btn-primary" onclick="editAbstract(\${abs.id})">تعديل</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteAbstract(\${abs.id})">حذف</button>
                </td>`;

const replaceStr = `
                <td>
                    <button class="btn btn-sm btn-primary" onclick="editAbstract(\${abs.id})">تعديل</button>
                    \${abs.status === 'draft' ? \`<button class="btn btn-sm btn-success" onclick="approveAbstractWithJournal(\${abs.id})">اعتماد</button>\` : ''}
                    \${abs.status === 'approved' ? \`<button class="btn btn-sm btn-info" onclick="paySubcontractAbstract(\${abs.id}, \${net - paid}, \${abs.contract_id})">سداد</button>\` : ''}
                    <button class="btn btn-sm btn-danger" onclick="deleteAbstract(\${abs.id})">حذف</button>
                </td>`;

if(code.includes(targetStr)) {
    code = code.replace(targetStr, replaceStr);
}

if (!code.includes('window.approveAbstractWithJournal')) {
    code += `
window.approveAbstractWithJournal = async function(id) {
    if(confirm('هل أنت متأكد من اعتماد هذا المستخلص؟ (سيتم توليد قيد استحقاق للمقاول)')) {
        const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
        const a = abstracts.find(x => x.id === id);
        if(a) {
            a.status = 'approved';
            await window.DB.update('subcontract_abstracts', a);
            
            // Generate Journal Entry
            const subcontracts = await window.DB.getAll('subcontracts') || [];
            const cont = subcontracts.find(c => c.id == a.contract_id);
            if (cont) {
                const journalEntry = {
                    date: new Date().toISOString().split('T')[0],
                    reference: 'SUB-ABS-' + a.abstract_number,
                    description: 'استحقاق مستخلص مقاول باطن رقم ' + a.abstract_number,
                    lines: [
                        { account_name: 'تكاليف مقاولي الباطن', debit: a.net_value, credit: 0 },
                        { account_name: 'دائنو مقاولي الباطن', debit: 0, credit: a.net_value, contact_id: cont.subcontractor_id }
                    ],
                    total: a.net_value
                };
                await window.DB.add('journal_entries', journalEntry);
                alert('تم اعتماد المستخلص وتوليد القيد بنجاح!');
            }
            if (typeof window.renderAbstracts === 'function') window.renderAbstracts();
        }
    }
};

window.paySubcontractAbstract = function(abstractId, remainingAmount, contractId) {
    if (typeof window.openVoucherModal === 'function') {
        window.openVoucherModal('payment');
        setTimeout(() => {
            if(document.getElementById('voucher-linked-invoice')) document.getElementById('voucher-linked-invoice').value = 'sca-' + abstractId;
            if(document.getElementById('voucher-amount')) document.getElementById('voucher-amount').value = remainingAmount;
            if(document.getElementById('voucher-status')) document.getElementById('voucher-status').value = 'posted';
            
            const sc = typeof currentSubcontracts !== 'undefined' ? currentSubcontracts.find(s => String(s.id) === String(contractId)) : undefined;
            const a = typeof currentSubcontractAbstracts !== 'undefined' ? currentSubcontractAbstracts.find(x => String(x.id) === String(abstractId)) : undefined;
            
            let subcName = '';
            if (sc) {
                if (document.getElementById('voucher-contact')) {
                    document.getElementById('voucher-contact').value = sc.subcontractor_id;
                }
                const subc = typeof currentContacts !== 'undefined' ? currentContacts.find(c => String(c.id) === String(sc.subcontractor_id)) : undefined;
                if(subc) subcName = subc.name;
            }
            
            // تعيين رقم المستند والبيان
            if (a) {
                if(document.getElementById('voucher-doc-no')) {
                    document.getElementById('voucher-doc-no').value = a.abstract_number || ('مستخلص ' + a.id);
                }
                if(document.getElementById('voucher-notes')) {
                    const scNumber = sc ? (sc.contract_number || sc.id) : contractId;
                    document.getElementById('voucher-notes').value = "سداد مستخلص مقاول باطن رقم (" + (a.abstract_number || a.id) + ") " + (subcName ? "للمقاول: " + subcName : "") + " - عقد رقم: " + scNumber;
                }
            } else {
                if(document.getElementById('voucher-notes')) document.getElementById('voucher-notes').value = "سداد مستخلص مقاول باطن رقم " + abstractId;
            }
        }, 150);
    } else {
        alert('يرجى سداد المبلغ من شاشة سندات الصرف وربطها بالمستخلص.');
    }
};
`;
}

fs.writeFileSync('app_final.js', code, 'utf8');
console.log('Patched app_final.js for Subcontract Abstracts UI and Journal');
