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

// 1. Add Auto-numbering to openAbstractModal
code = code.replace(
    /document\.getElementById\('ab-abstract-number'\)\.value = '';/g,
    `document.getElementById('ab-abstract-number').value = 'SUB-' + (currentSubcontractAbstracts.length > 0 ? Math.max(...currentSubcontractAbstracts.map(a => a.id)) + 1 : 1).toString().padStart(4, '0');`
);

// 2. Fix saveAbstract null issues and correct abstract-id
code = code.replace(
    /const editId = document\.getElementById\('edit-abstract-id'\)\?\.value;/g,
    `const editId = document.getElementById('abstract-id')?.value;`
);

code = code.replace(
    /items: window\.currentAbstractItems \|\| \[\]/g,
    `items: Array.from(document.querySelectorAll('#ab-items-tbody tr')).map(row => ({
                name: row.querySelector('.ab-item-name')?.value || '',
                unit: row.querySelector('.ab-item-unit')?.value || '',
                price: parseFloat(row.querySelector('.ab-item-price')?.value) || 0,
                total_qty: parseFloat(row.querySelector('.ab-item-total-qty')?.innerText) || 0,
                prev_qty: parseFloat(row.querySelector('.ab-item-prev-qty')?.innerText) || 0,
                current_qty: parseFloat(row.querySelector('.ab-item-curr-qty')?.value) || 0
            }))`
);

// 3. Add Approve & Pay buttons to renderAbstracts
const trHtmlSearch = `            <td><span class="status-badge">\${ab.status === 'approved' ? 'معتمد' : 'مسودة'}</span></td>
            <td>
                <button class="action-btn" onclick="openAbstractModal(\${ab.id})">✏️</button>
                <button class="action-btn" onclick="window.deleteAbstract(\${ab.id})">🗑️</button>
            </td>`;

const trHtmlReplace = `            <td><span class="status-badge">\${ab.status === 'paid' ? 'مدفوع' : (ab.status === 'approved' ? 'معتمد' : 'مسودة')}</span></td>
            <td>
                <button class="action-btn" onclick="openAbstractModal(\${ab.id})" title="تعديل">✏️</button>
                \${ab.status === 'draft' ? \`<button class="action-btn" onclick="window.approveAbstract(\${ab.id})" style="background:#28a745;" title="اعتماد">✅</button>\` : ''}
                \${ab.status === 'approved' ? \`<button class="action-btn" onclick="window.paySubcontractAbstract(\${ab.id}, \${parseFloat(ab.net_value) - parseFloat(ab.advance_payment)}, \${ab.contract_id})" style="background:#17a2b8;" title="سداد">💳</button>\` : ''}
                <button class="action-btn" onclick="window.deleteAbstract(\${ab.id})" title="حذف">🗑️</button>
            </td>`;

if (code.includes(trHtmlSearch)) {
    code = code.replace(trHtmlSearch, trHtmlReplace);
}

// 4. Update approveAbstract to add Journal Entry
code = code.replace(
    /window\.approveAbstract = async function\(id\) \{([\s\S]*?)a\.status = 'approved';\s*await window\.DB\.update\('subcontract_abstracts', a\);/g,
    `window.approveAbstract = async function(id) {
    if(confirm('هل أنت متأكد من اعتماد هذا المستخلص؟ (سيتم توليد قيد استحقاق)')) {
        const a = currentSubcontractAbstracts.find(x => x.id === id);
        if(a) {
            a.status = 'approved';
            await window.DB.update('subcontract_abstracts', a);
            
            const cont = currentSubcontracts.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: 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);
                alert('تم الاعتماد وتوليد القيد بنجاح!');
            }
`
);

fs.writeFileSync('subcontracts.js', code, 'utf8');
console.log('Patched subcontracts.js for Auto-num, null safety, buttons and journal entry');
