const fs = require('fs');

// 1. Fix app_final.js to prevent Client Abstracts from crashing
let app = fs.readFileSync('app_final.js', 'utf8');
app = app.replace(
    "document.getElementById('client-abstract-form').reset();",
    "const form = document.getElementById('client-abstract-form'); if(form) form.reset();"
);
fs.writeFileSync('app_final.js', app, 'utf8');

// 2. Rewrite subcontracts.js completely to use the exact correct HTML IDs
const subcontractsJS = `
let currentSubcontracts = [];
let currentSubcontractAbstracts = [];

// Load data
window.addEventListener('load', async () => {
    setTimeout(async () => {
        try {
            currentSubcontracts = await window.DB.getAll('subcontracts') || [];
            currentSubcontractAbstracts = await window.DB.getAll('subcontract_abstracts') || [];
            if(document.getElementById('view-subcontracts') && document.getElementById('view-subcontracts').classList.contains('active')) {
                window.renderSubcontracts();
            }
            if(document.getElementById('view-subcontract-abstracts') && document.getElementById('view-subcontract-abstracts').classList.contains('active')) {
                window.renderAbstracts();
            }
        } catch(e) { console.error(e); }
    }, 1000);
});

// Menu
document.addEventListener('click', (e) => {
    if(e.target.closest('li') && e.target.closest('li').dataset.view === 'subcontracts') window.renderSubcontracts();
    if(e.target.closest('li') && e.target.closest('li').dataset.view === 'subcontract-abstracts') window.renderAbstracts();
});

// ----------------------------------------------------
// SUBCONTRACTS (عقود مقاولي الباطن)
// ----------------------------------------------------
window.renderSubcontracts = function() {
    const tbody = document.getElementById('subcontracts-tbody');
    if(!tbody) return;
    tbody.innerHTML = '';
    currentSubcontracts.forEach(sc => {
        const proj = currentProjects.find(p => p.id === parseInt(sc.project_id))?.name || '-';
        const subc = currentContacts.find(c => c.id === parseInt(sc.subcontractor_id))?.name || '-';
        const val = parseFloat(sc.total_value) || 0;
        let tr = document.createElement('tr');
        tr.innerHTML = \`
            <td>\${sc.contract_number || '-'}</td>
            <td>\${proj}</td>
            <td>\${subc}</td>
            <td>\${sc.date || '-'}</td>
            <td style="color:var(--primary); font-weight:bold;">\${val.toLocaleString('ar-EG')}</td>
            <td>
                <button class="action-btn btn-edit" onclick="openSubcontractModal(\${sc.id})">تعديل</button>
                <button class="action-btn btn-danger" onclick="deleteSubcontract(\${sc.id})">حذف</button>
            </td>
        \`;
        tbody.appendChild(tr);
    });
};

window.openSubcontractModal = function(id = null) {
    document.getElementById('subcontract-modal-title').innerText = id ? 'تعديل عقد مقاول باطن' : 'عقد مقاول باطن جديد';
    document.getElementById('subcontract-id').value = id || '';
    
    document.getElementById('sc-project-id').innerHTML = '<option value="">اختر المشروع...</option>' + currentProjects.map(p => \`<option value="\${p.id}">\${p.name}</option>\`).join('');
    document.getElementById('sc-subcontractor-id').innerHTML = '<option value="">اختر المقاول...</option>' + currentContacts.map(c => \`<option value="\${c.id}">\${c.name}</option>\`).join('');
    
    const tbody = document.getElementById('sc-items-tbody');
    tbody.innerHTML = '';

    if (id) {
        const sc = currentSubcontracts.find(s => s.id === id);
        if(sc) {
            document.getElementById('sc-project-id').value = sc.project_id || '';
            document.getElementById('sc-subcontractor-id').value = sc.subcontractor_id || '';
            document.getElementById('sc-contract-number').value = sc.contract_number || '';
            document.getElementById('sc-date').value = sc.date || new Date().toISOString().split('T')[0];
            document.getElementById('sc-notes').value = sc.notes || '';
            document.getElementById('sc-total-value').innerText = sc.total_value || 0;
            
            if(sc.items && sc.items.length > 0) {
                sc.items.forEach(item => addScItemRow(item));
            } else {
                addScItemRow();
            }
        }
    } else {
        document.getElementById('sc-project-id').value = '';
        document.getElementById('sc-subcontractor-id').value = '';
        document.getElementById('sc-contract-number').value = '';
        document.getElementById('sc-date').value = new Date().toISOString().split('T')[0];
        document.getElementById('sc-notes').value = '';
        document.getElementById('sc-total-value').innerText = 0;
        addScItemRow();
    }
    
    document.getElementById('subcontract-modal').classList.add('active');
};

window.closeSubcontractModal = function() {
    document.getElementById('subcontract-modal').classList.remove('active');
};

window.onSubcontractProjectChange = function() {
    // optional filter
};

window.addScItemRow = function(item = null) {
    const tbody = document.getElementById('sc-items-tbody');
    const tr = document.createElement('tr');
    tr.innerHTML = \`
        <td><button class="action-btn btn-danger" onclick="this.closest('tr').remove(); calcScTotal();"><i class="fas fa-trash"></i></button></td>
        <td><input type="text" class="sc-item-name" value="\${item ? item.name : ''}" style="width:100%;"></td>
        <td><input type="text" class="sc-item-unit" value="\${item ? item.unit : ''}" style="width:100%;"></td>
        <td><input type="number" class="sc-item-qty" value="\${item ? item.qty : 0}" oninput="calcScTotal()" style="width:100%;"></td>
        <td><input type="number" class="sc-item-price" value="\${item ? item.price : 0}" oninput="calcScTotal()" style="width:100%;"></td>
        <td><span class="sc-item-total" style="font-weight:bold;">\${item ? (item.qty * item.price) : 0}</span></td>
        <td><input type="text" class="sc-item-notes" value="\${item ? item.notes : ''}" style="width:100%;"></td>
    \`;
    tbody.appendChild(tr);
};

window.calcScTotal = function() {
    let total = 0;
    const rows = document.querySelectorAll('#sc-items-tbody tr');
    rows.forEach(row => {
        const qty = parseFloat(row.querySelector('.sc-item-qty').value) || 0;
        const price = parseFloat(row.querySelector('.sc-item-price').value) || 0;
        const lineTotal = qty * price;
        row.querySelector('.sc-item-total').innerText = lineTotal;
        total += lineTotal;
    });
    document.getElementById('sc-total-value').innerText = total;
};

window.saveSubcontract = async function() {
    try {
        const idStr = document.getElementById('subcontract-id').value;
        const items = [];
        document.querySelectorAll('#sc-items-tbody tr').forEach(row => {
            items.push({
                name: row.querySelector('.sc-item-name').value,
                unit: row.querySelector('.sc-item-unit').value,
                qty: parseFloat(row.querySelector('.sc-item-qty').value) || 0,
                price: parseFloat(row.querySelector('.sc-item-price').value) || 0,
                notes: row.querySelector('.sc-item-notes').value
            });
        });
        
        const obj = {
            project_id: document.getElementById('sc-project-id').value,
            subcontractor_id: document.getElementById('sc-subcontractor-id').value,
            contract_number: document.getElementById('sc-contract-number').value,
            date: document.getElementById('sc-date').value,
            notes: document.getElementById('sc-notes').value,
            total_value: parseFloat(document.getElementById('sc-total-value').innerText) || 0,
            items: items
        };
        
        if(!obj.project_id || !obj.subcontractor_id || !obj.contract_number) {
            alert('يجب إدخال المشروع والمقاول ورقم العقد'); return;
        }
        
        if (idStr) {
            obj.id = parseInt(idStr);
            await window.DB.update('subcontracts', obj);
        } else {
            await window.DB.add('subcontracts', obj);
        }
        currentSubcontracts = await window.DB.getAll('subcontracts') || [];
        closeSubcontractModal();
        renderSubcontracts();
        alert('تم الحفظ بنجاح');
    } catch(e) { alert('خطأ: ' + e.message); }
};

window.deleteSubcontract = async function(id) {
    if(confirm('هل أنت متأكد من حذف العقد؟')) {
        await window.DB.remove('subcontracts', id);
        currentSubcontracts = await window.DB.getAll('subcontracts') || [];
        renderSubcontracts();
    }
};

// ----------------------------------------------------
// ABSTRACTS (مستخلصات مقاولي الباطن)
// ----------------------------------------------------
window.renderAbstracts = function() {
    const tbody = document.getElementById('subcontract-abstracts-tbody');
    if(!tbody) return;
    tbody.innerHTML = '';
    
    currentSubcontractAbstracts.forEach(ab => {
        const sc = currentSubcontracts.find(s => s.id === parseInt(ab.contract_id));
        const subc = sc ? currentContacts.find(c => c.id === parseInt(sc.subcontractor_id))?.name || '-' : '-';
        const proj = sc ? currentProjects.find(p => p.id === parseInt(sc.project_id))?.name || '-' : '-';
        const net = parseFloat(ab.net_value) || 0;
        const cnum = sc ? sc.contract_number : '-';
        
        let actions = '';
        if(ab.status === 'approved') {
            actions = \`<button class="action-btn btn-success" onclick="payAbstract(\${ab.id})">سند صرف</button>\`;
        } else {
            actions = \`
                <button class="action-btn btn-success" onclick="approveAbstract(\${ab.id})">اعتماد</button>
                <button class="action-btn btn-edit" onclick="openAbstractModal(\${ab.id})">تعديل</button>
                <button class="action-btn btn-danger" onclick="deleteAbstract(\${ab.id})">حذف</button>
            \`;
        }
        
        let tr = document.createElement('tr');
        tr.innerHTML = \`
            <td>\${ab.abstract_number}</td>
            <td>\${cnum}</td>
            <td>\${subc}</td>
            <td>\${proj}</td>
            <td style="color:var(--primary); font-weight:bold;">\${net.toLocaleString('ar-EG')}</td>
            <td><span class="status-badge \${ab.status==='approved'?'status-posted':'status-draft'}">\${ab.status==='approved'?'معتمد':'مسودة'}</span></td>
            <td>\${actions}</td>
        \`;
        tbody.appendChild(tr);
    });
};

window.openAbstractModal = function(id = null) {
    document.getElementById('abstract-modal-title').innerText = id ? 'تعديل مستخلص مقاول' : 'مستخلص مقاول باطن جديد';
    document.getElementById('abstract-id').value = id || '';
    
    document.getElementById('ab-contract-id').innerHTML = '<option value="">اختر العقد...</option>' + currentSubcontracts.map(c => \`<option value="\${c.id}">\${c.contract_number} (\${currentContacts.find(x=>x.id==c.subcontractor_id)?.name})</option>\`).join('');
    
    const tbody = document.getElementById('ab-items-tbody');
    tbody.innerHTML = '';
    
    if(id) {
        const ab = currentSubcontractAbstracts.find(a => a.id === id);
        if(ab) {
            document.getElementById('ab-contract-id').value = ab.contract_id || '';
            document.getElementById('ab-abstract-number').value = ab.abstract_number || '';
            document.getElementById('ab-date').value = ab.date || new Date().toISOString().split('T')[0];
            document.getElementById('ab-period').value = ab.period || '';
            
            document.getElementById('ab-advance-payment').value = ab.advance_payment || 0;
            document.getElementById('ab-tax-percent').value = ab.tax_percent || 1;
            document.getElementById('ab-retention-percent').value = ab.retention_percent || 5;
            document.getElementById('ab-other-deductions').value = ab.other_deductions || 0;
            
            if(ab.items) ab.items.forEach(item => addAbItemRow(item));
        }
    } else {
        document.getElementById('ab-contract-id').value = '';
        document.getElementById('ab-abstract-number').value = '';
        document.getElementById('ab-date').value = new Date().toISOString().split('T')[0];
        document.getElementById('ab-period').value = '';
        
        document.getElementById('ab-advance-payment').value = 0;
        document.getElementById('ab-tax-percent').value = 1;
        document.getElementById('ab-retention-percent').value = 5;
        document.getElementById('ab-other-deductions').value = 0;
    }
    
    calculateAbstractTotals();
    document.getElementById('abstract-modal').classList.add('active');
};

window.closeAbstractModal = function() {
    document.getElementById('abstract-modal').classList.remove('active');
};

window.onAbstractContractChange = function() {
    const cid = document.getElementById('ab-contract-id').value;
    const tbody = document.getElementById('ab-items-tbody');
    tbody.innerHTML = '';
    
    if(!cid) return;
    
    const contract = currentSubcontracts.find(c => c.id == cid);
    if(contract) {
        document.getElementById('ab-display-project').innerText = currentProjects.find(p => p.id == contract.project_id)?.name || '-';
        document.getElementById('ab-display-subcontractor').innerText = currentContacts.find(c => c.id == contract.subcontractor_id)?.name || '-';
        
        // Find previous abstracts for this contract to calc prev qty
        const prevAbs = currentSubcontractAbstracts.filter(a => a.contract_id == cid && a.id !== parseInt(document.getElementById('abstract-id').value || 0));
        
        if(contract.items) {
            contract.items.forEach((item, index) => {
                let prevQty = 0;
                prevAbs.forEach(pa => {
                    if(pa.items && pa.items[index]) prevQty += pa.items[index].current_qty || 0;
                });
                
                addAbItemRow({
                    name: item.name,
                    unit: item.unit,
                    total_qty: item.qty,
                    price: item.price,
                    prev_qty: prevQty,
                    current_qty: 0
                });
            });
        }
    }
    calculateAbstractTotals();
};

window.addAbItemRow = function(item = null) {
    const tbody = document.getElementById('ab-items-tbody');
    const tr = document.createElement('tr');
    
    const price = item ? item.price : 0;
    const totalQty = item ? item.total_qty : 0;
    const prevQty = item ? item.prev_qty : 0;
    const currentQty = item ? item.current_qty : 0;
    const totalCurrentQty = prevQty + currentQty;
    
    tr.innerHTML = \`
        <td><i class="fas fa-check" style="color:var(--success);"></i></td>
        <td><input type="text" class="ab-item-name" value="\${item ? item.name : ''}" readonly style="width:100%; border:none; background:transparent; color:#fff;"></td>
        <td><input type="text" class="ab-item-unit" value="\${item ? item.unit : ''}" readonly style="width:100%; border:none; background:transparent; color:#fff; text-align:center;"></td>
        <td><input type="number" class="ab-item-price" value="\${price}" readonly style="width:100%; border:none; background:transparent; color:#fff; text-align:center;"></td>
        <td><span class="ab-item-total-qty">\${totalQty}</span></td>
        <td><span class="ab-item-total-val">\${totalQty * price}</span></td>
        <td><span class="ab-item-prev-qty">\${prevQty}</span></td>
        <td><span class="ab-item-prev-val">\${prevQty * price}</span></td>
        <td><input type="number" class="ab-item-curr-qty" value="\${currentQty}" oninput="calculateAbstractTotals()" style="width:100%; text-align:center;"></td>
        <td><span class="ab-item-curr-val" style="color:var(--primary); font-weight:bold;">\${currentQty * price}</span></td>
        <td><span class="ab-item-accum-qty">\${totalCurrentQty}</span></td>
        <td><span class="ab-item-accum-val">\${totalCurrentQty * price}</span></td>
    \`;
    tbody.appendChild(tr);
};

window.calculateAbstractTotals = function() {
    let totalGross = 0;
    let prevGross = 0;
    let currGross = 0;
    
    document.querySelectorAll('#ab-items-tbody tr').forEach(row => {
        const price = parseFloat(row.querySelector('.ab-item-price').value) || 0;
        const prevQty = parseFloat(row.querySelector('.ab-item-prev-qty').innerText) || 0;
        const currQty = parseFloat(row.querySelector('.ab-item-curr-qty').value) || 0;
        
        row.querySelector('.ab-item-curr-val').innerText = (currQty * price).toFixed(2);
        row.querySelector('.ab-item-accum-qty').innerText = (prevQty + currQty).toFixed(2);
        row.querySelector('.ab-item-accum-val').innerText = ((prevQty + currQty) * price).toFixed(2);
        
        totalGross += (prevQty + currQty) * price;
        prevGross += prevQty * price;
        currGross += currQty * price;
    });
    
    document.getElementById('ab-total-works').innerText = totalGross.toFixed(2);
    document.getElementById('ab-prev-works').innerText = prevGross.toFixed(2);
    document.getElementById('ab-current-works').innerText = currGross.toFixed(2);
    
    const taxP = parseFloat(document.getElementById('ab-tax-percent').value) || 0;
    const retP = parseFloat(document.getElementById('ab-retention-percent').value) || 0;
    
    const taxVal = currGross * (taxP / 100);
    const retVal = currGross * (retP / 100);
    
    document.getElementById('ab-tax-value').innerText = taxVal.toFixed(2);
    document.getElementById('ab-retention-value').innerText = retVal.toFixed(2);
    
    const adv = parseFloat(document.getElementById('ab-advance-payment').value) || 0;
    const oth = parseFloat(document.getElementById('ab-other-deductions').value) || 0;
    
    const totalDed = taxVal + retVal + adv + oth;
    document.getElementById('ab-total-deductions').innerText = totalDed.toFixed(2);
    
    const net = currGross - totalDed;
    document.getElementById('ab-net-value').innerText = net.toFixed(2);
};

window.saveAbstract = async function() {
    try {
        const idStr = document.getElementById('abstract-id').value;
        const items = [];
        document.querySelectorAll('#ab-items-tbody tr').forEach(row => {
            items.push({
                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
            });
        });
        
        const obj = {
            contract_id: document.getElementById('ab-contract-id').value,
            abstract_number: document.getElementById('ab-abstract-number').value,
            date: document.getElementById('ab-date').value,
            period: document.getElementById('ab-period').value,
            advance_payment: parseFloat(document.getElementById('ab-advance-payment').value) || 0,
            tax_percent: parseFloat(document.getElementById('ab-tax-percent').value) || 0,
            retention_percent: parseFloat(document.getElementById('ab-retention-percent').value) || 0,
            other_deductions: parseFloat(document.getElementById('ab-other-deductions').value) || 0,
            net_value: parseFloat(document.getElementById('ab-net-value').innerText) || 0,
            status: 'draft',
            items: items
        };
        
        if(!obj.contract_id || !obj.abstract_number) {
            alert('يجب إدخال العقد ورقم المستخلص'); return;
        }
        
        if(idStr) {
            obj.id = parseInt(idStr);
            const exist = currentSubcontractAbstracts.find(a => a.id === obj.id);
            if(exist && exist.status === 'approved') {
                alert('مستخلص معتمد لا يمكن تعديله'); return;
            }
            if(exist) obj.status = exist.status;
            await window.DB.update('subcontract_abstracts', obj);
        } else {
            await window.DB.add('subcontract_abstracts', obj);
        }
        
        currentSubcontractAbstracts = await window.DB.getAll('subcontract_abstracts') || [];
        closeAbstractModal();
        renderAbstracts();
        alert('تم الحفظ بنجاح');
    } catch(e) { alert('خطأ: ' + e.message); }
};

window.deleteAbstract = async function(id) {
    if(confirm('هل أنت متأكد من حذف المستخلص؟')) {
        await window.DB.remove('subcontract_abstracts', id);
        currentSubcontractAbstracts = await window.DB.getAll('subcontract_abstracts') || [];
        renderAbstracts();
    }
};

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);
            currentSubcontractAbstracts = await window.DB.getAll('subcontract_abstracts') || [];
            renderAbstracts();
        }
    }
};

window.payAbstract = function(id, suggestedAmount = null) {
    const a = typeof currentSubcontractAbstracts !== 'undefined' ? currentSubcontractAbstracts.find(x => x.id === id) : undefined;
    if (!a) return;
    
    if (suggestedAmount === null) {
        const linkedVouchers = typeof allInvoices !== 'undefined' ? allInvoices.filter(v => (v.type === 'receipt' || v.type === 'payment') && v.linked_invoice_id == 'sca-' + id && v.status === 'posted') : [];
        let totalPaid = 0;
        linkedVouchers.forEach(v => totalPaid += parseFloat(v.amount) || 0);
        let remaining = (parseFloat(a.net_value) || 0) - totalPaid;
        // fix floating point errors
        remaining = Math.round(remaining * 100) / 100;
        suggestedAmount = Math.max(0, remaining);
    }
    
    window.openVoucherModal('payment');
    
    setTimeout(() => {
        if(document.getElementById('voucher-linked-invoice')) document.getElementById('voucher-linked-invoice').value = 'sca-' + a.id;
        if(document.getElementById('voucher-amount')) document.getElementById('voucher-amount').value = suggestedAmount;
        if(document.getElementById('voucher-status')) document.getElementById('voucher-status').value = 'posted';
        
        const sc = typeof currentSubcontracts !== 'undefined' ? currentSubcontracts.find(s => String(s.id) === String(a.contract_id)) : 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(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) : a.contract_id;
            document.getElementById('voucher-notes').value = "سداد مستخلص مقاول باطن رقم (" + (a.abstract_number || a.id) + ") " + (subcName ? "للمقاول: " + subcName : "") + " - عقد رقم: " + scNumber;
        }
    }, 150);
};

window.saveAbstractModalGlobal = window.saveAbstract;
window.saveSubcontractModalGlobal = window.saveSubcontract;

`;

fs.writeFileSync('subcontracts.js', subcontractsJS, 'utf8');
console.log("Rewrote subcontracts.js");
