
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.slice().reverse().forEach(sc => {
        const proj = currentProjects.find(p => p.id === parseInt(sc.project_id));
        const subc = currentContacts.find(c => c.id === parseInt(sc.subcontractor_id));
        const tr = document.createElement('tr');
        
        // هنا تم توحيد قراءة الإجمالي لحل المشكلة
        let totalVal = parseFloat(sc.total_value) || parseFloat(sc.total) || 0;
        if(totalVal === 0 && sc.boq_items) {
             totalVal = sc.boq_items.reduce((s, b) => s + ((b.qty||0)*(b.price||0)), 0);
        }

        tr.innerHTML = `
            <td>${sc.contract_number || ('#' + sc.id)}</td>
            <td>${sc.date || ''}</td>
            <td>${proj ? proj.name : '-'}</td>
            <td>${subc ? subc.name : '-'}</td>
            <td style="color:var(--primary); font-weight:bold;">${totalVal.toLocaleString('en-US')} ج.م</td>
            <td>
                <button class="action-btn btn-edit" onclick="openSubcontractModal(${sc.id})">✏️ تعديل/عرض</button>
                ${currentUser && currentUser.role === 'مدير عام' ? `<button class="action-btn btn-delete" 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} (${c.type || ''})</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 activeView = document.querySelector('.view.active, [id^="view-"].active');
    if (!activeView) return;
    const table = activeView.querySelector('table');
    if (!table) return;
    const tbody = table.querySelector('tbody') || table.appendChild(document.createElement('tbody'));
    tbody.innerHTML = '';

    
    currentSubcontractAbstracts.slice().reverse().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('en-US')}</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 => String(a.id) === String(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 || '';
            if (window.setMultiSelectValues) window.setMultiSelectValues('ab-intended-approver', ab.intended_approver || '');
            else if (document.getElementById('ab-intended-approver')) document.getElementById('ab-intended-approver').value = ab.intended_approver || '';

        const btnSignAb = document.getElementById('btn-sign-ab');
        if (btnSignAb) {
            const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
            const currentName = currentUser.name || currentUser.username;
            if (ab.intended_approver && ab.intended_approver.includes(currentName) && !(ab.paper_approved_by || '').includes(currentName)) {
                btnSignAb.style.display = 'inline-block';
            } else {
                btnSignAb.style.display = 'none';
            }
        }

            
            document.getElementById('ab-advance-payment').value = ab.advance_payment !== undefined && ab.advance_payment !== null && ab.advance_payment !== '' ? ab.advance_payment : 0;
            document.getElementById('ab-tax-percent').value = ab.tax_percent !== undefined && ab.tax_percent !== null && ab.tax_percent !== '' ? ab.tax_percent : 1;
            document.getElementById('ab-retention-percent').value = ab.retention_percent !== undefined && ab.retention_percent !== null && ab.retention_percent !== '' ? ab.retention_percent : 5;
            document.getElementById('ab-other-deductions').value = ab.other_deductions !== undefined && ab.other_deductions !== null && ab.other_deductions !== '' ? ab.other_deductions : 0;

          const sigContainer = document.getElementById('subcontract-signatures-container');
          const sigList = document.getElementById('subcontract-signatures-list');
          if (sigContainer && sigList) {
              if (ab.paper_approved_by) {
                  sigContainer.style.display = 'block';
                  sigList.innerHTML = ab.paper_approved_by;
              } else {
                  sigContainer.style.display = 'none';
                  sigList.innerHTML = '';
              }
          }
            
            document.getElementById('ab-items-tbody').innerHTML = '';
            const cid = ab.contract_id;
            const contract = currentSubcontracts.find(c => String(c.id) === String(cid));
            
            if (contract) {
                const prevAbs = currentSubcontractAbstracts.filter(a => a.contract_id == cid && a.id !== ab.id);
                const contractItems = contract.items || contract.boq_items || [];
                
                contractItems.forEach((item, index) => {
                    let prevQty = 0;
                    let currentQty = 0;
                    
                    if (ab.items && ab.items[index]) {
                        // If abstract was saved previously, restore the current_qty
                        currentQty = ab.items[index].current_qty || 0;
                    }
                    
                    prevAbs.forEach(pa => {
                        const pItems = pa.items || pa.boq_lines;
                        if(pItems && pItems[index]) prevQty += pItems[index].current_qty || pItems[index].curr_qty || 0;
                    });
                    
                    addAbItemRow({
                        name: item.name,
                        unit: item.unit,
                        total_qty: item.qty,
                        price: item.price,
                        prev_qty: prevQty,
                        current_qty: currentQty
                    }, index);
                });
            } else if(ab.items && ab.items.length > 0) {
                // Fallback if contract is somehow deleted
                ab.items.forEach((item, index) => addAbItemRow(item, index));
            }
        }
    } else {
        const sigContainer = document.getElementById('subcontract-signatures-container');
        const sigList = document.getElementById('subcontract-signatures-list');
        if (sigContainer && sigList) {
            sigContainer.style.display = 'none';
            sigList.innerHTML = '';
        }
        
        document.getElementById('ab-contract-id').value = '';
        document.getElementById('ab-abstract-number').value = 'SUB-' + (currentSubcontractAbstracts.length > 0 ? Math.max(...currentSubcontractAbstracts.map(a => a.id)) + 1 : 1).toString().padStart(4, '0');
        document.getElementById('ab-date').value = new Date().toISOString().split('T')[0];
        document.getElementById('ab-period').value = '';
        if (window.setMultiSelectValues) window.setMultiSelectValues('ab-intended-approver', '');
        else if (document.getElementById('ab-intended-approver')) document.getElementById('ab-intended-approver').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;
    }
    
    calculateSubcontractAbstractTotals();

    // Toggle save button visibility based on status
    const btnSaveAb = document.querySelector('button[onclick="saveAbstract()"]') || document.querySelector('button[onclick="window.saveAbstract()"]');
    if (btnSaveAb) {
        if (id) {
            const ab = currentSubcontractAbstracts.find(a => String(a.id) === String(id));
            if (ab && (ab.status === 'approved' || ab.status === 'paid')) {
                btnSaveAb.style.display = 'none';
            } else {
                btnSaveAb.style.display = 'inline-block';
            }
        } else {
            btnSaveAb.style.display = 'inline-block';
        }
    }

    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 || '-';

        const contractAbstracts = (currentSubcontractAbstracts || []).filter(a => String(a.contract_id) === String(cid));
        let maxNum = 0;
        contractAbstracts.forEach(a => {
            let num = parseInt(String(a.abstract_number).replace(/[^\d]/g, '')) || 0;
            if(num > maxNum) maxNum = num;
        });
        const nextId = maxNum + 1;
        if(document.getElementById('ab-abstract-number')) document.getElementById('ab-abstract-number').value = 'جاري ' + nextId;

        
        // 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));
        
        const contractItems = contract.items || contract.boq_items;
        if(contractItems) {
            contractItems.forEach((item, index) => {
                let prevQty = 0;
                prevAbs.forEach(pa => {
                    const pItems = pa.items || pa.boq_lines;
                    if(pItems && pItems[index]) prevQty += pItems[index].current_qty || pItems[index].curr_qty || 0;
                });
                
                addAbItemRow({
                    name: item.name,
                    unit: item.unit,
                    total_qty: item.qty,
                    price: item.price,
                    prev_qty: prevQty,
                    current_qty: 0
                }, index);
            });
        }
    }
    calculateSubcontractAbstractTotals();
};

window.addAbItemRow = function(item = null, index = 0) {
    const tbody = document.getElementById('ab-items-tbody');
    const row = document.createElement('tr');
    
    let price = item ? (parseFloat(item.price) || 0) : 0;
    let totalQty = item ? (parseFloat(item.total_qty || item.qty) || 0) : 0;
    let prevQty = item ? (parseFloat(item.prev_qty) || 0) : 0;
    let currentQty = item ? (parseFloat(item.current_qty) || 0) : 0;
    
    let totalCurrentQty = prevQty + currentQty;
    
    row.innerHTML = `
        <td style="text-align:center;">${index + 1}</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><input type="number" class="ab-item-total-qty" value="${totalQty}" readonly style="width:100%; border:none; background:transparent; color:#fff; text-align:center;"></td>
        <td><span class="ab-item-total-val">${totalQty * price}</span></td>
        <td><span class="ab-item-prev-qty">${prevQty}</span></td>
        <td><input type="number" class="ab-item-curr-qty" value="${currentQty}" step="0.01" oninput="calculateSubcontractAbstractTotals()" style="width:100%; text-align:center;"></td>
        <td><span class="ab-item-accum-qty">${totalCurrentQty}</span></td>
        <td><span class="ab-item-prev-val">${prevQty * price}</span></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-val">${totalCurrentQty * price}</span></td>
    `;
    tbody.appendChild(row);
};

window.calculateSubcontractAbstractTotals = function() {
    let totalGross = 0;
    let prevGross = 0;
    let currGross = 0;
    
    document.querySelectorAll('#ab-items-tbody tr').forEach((row, index) => {
        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;
        
        console.log(`Calc row ${index}: price=${price}, prevQty=${prevQty}, currQty=${currQty}`);
        
        if (row.querySelector('.ab-item-curr-val')) row.querySelector('.ab-item-curr-val').innerText = (currQty * price).toLocaleString('en-US');
        if (row.querySelector('.ab-item-accum-qty')) row.querySelector('.ab-item-accum-qty').innerText = (prevQty + currQty).toLocaleString('en-US');
        if (row.querySelector('.ab-item-accum-val')) row.querySelector('.ab-item-accum-val').innerText = ((prevQty + currQty) * price).toLocaleString('en-US');
        
        totalGross += (prevQty + currQty) * price;
        prevGross += prevQty * price;
        currGross += currQty * price;
    });
    
    console.log(`Totals: total=${totalGross}, prev=${prevGross}, curr=${currGross}`);


    document.getElementById('ab-total-works').innerText = totalGross.toLocaleString('en-US');
    document.getElementById('ab-prev-works').innerText = prevGross.toLocaleString('en-US');
    document.getElementById('ab-current-works').innerText = currGross.toLocaleString('en-US');
    
    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.toLocaleString('en-US');
    document.getElementById('ab-retention-value').innerText = retVal.toLocaleString('en-US');
    
    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.toLocaleString('en-US');
    
    const net = currGross - totalDed;
    document.getElementById('ab-net-value').innerText = net.toLocaleString('en-US');
};

window.renderAbstracts = async function() {
    const tbody = document.getElementById('abstracts-tbody');
    if(!tbody) return;
    
    // جلب البيانات الأساسية
    const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
    const projects = await window.DB.getAll('projects') || [];
    const subcontracts = await window.DB.getAll('subcontracts') || [];
    const contacts = await window.DB.getAll('contacts') || [];
    
    tbody.innerHTML = '';
    
    abstracts.slice().reverse().forEach(ab => {
        const sc = subcontracts.find(s => String(s.id) === String(ab.contract_id)) || {};
        const proj = projects.find(p => String(p.id) === String(ab.project_id || sc.project_id)) || {};
        const subc = contacts.find(c => String(c.id) === String(ab.subcontractor_id || sc.subcontractor_id)) || {};
        
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${ab.abstract_number || ab.id}</td>
            <td>${subc.name || '-'}</td>
            <td>${proj.name || '-'}</td>
            <td>${sc.contract_number || '-'}</td>
            <td>${ab.date || '-'}</td>
            <td>${ab.period || '-'}</td>
            <td style="font-weight:bold; color:var(--success);">${(parseFloat(ab.net_value)||0).toLocaleString('ar-EG')}</td>
            <td style="font-weight:bold; color:var(--primary);">${(parseFloat(ab.advance_payment)||0).toLocaleString('ar-EG')}</td>
            <td style="font-weight:bold; color:var(--danger);">${(parseFloat(ab.net_value) - parseFloat(ab.advance_payment) || 0).toLocaleString('ar-EG')}</td>
            <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>
        `;
        tbody.appendChild(tr);
    });
};

window.saveAbstract = async function() {
    try {
        const getVal = (id) => document.getElementById(id)?.value || '';
        const getNum = (id) => parseFloat(document.getElementById(id)?.value || 0) || 0;
        const getNumText = (id) => parseFloat((document.getElementById(id)?.innerText || '0').replace(/,/g, '')) || 0;
        const contractId = getNum('ab-contract-id');
        
        if(!contractId) { alert('يجب اختيار العقد'); return; }
        
        const editId = document.getElementById('abstract-id')?.value;
        const existingAb = editId ? currentSubcontractAbstracts.find(a => String(a.id) === String(editId)) : null;

        const obj = {
            contract_id: contractId,
            abstract_number: getVal('ab-abstract-number'),
            date: getVal('ab-date'),
            period: getVal('ab-period'),
            
            gross_value: getNumText('ab-current-works'),
            curr_works: getNumText('ab-current-works'),
            net_value: getNumText('ab-net-value'),
            
            tax_percent: getNum('ab-tax-percent'),
            tax_value: getNumText('ab-tax-value'),
            
            retention_percent: getNum('ab-retention-percent'),
            retention_value: getNumText('ab-retention-value'),
            
            advance_payment: getNum('ab-advance-payment'),
            other_deductions: getNum('ab-other-deductions'),
            intended_approver: (window.getMultiSelectValues ? window.getMultiSelectValues('ab-intended-approver') : (document.getElementById('ab-intended-approver')?.value || '')) || (existingAb?.intended_approver || ''),
            
            status: existingAb ? existingAb.status : 'draft',
            paper_approved_by: existingAb ? existingAb.paper_approved_by : undefined,
            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')?.value || row.querySelector('.ab-item-total-qty')?.innerText || '0').replace(/,/g,'')) || 0,
                prev_qty: parseFloat((row.querySelector('.ab-item-prev-qty')?.innerText || '0').replace(/,/g,'')) || 0,
                current_qty: parseFloat(row.querySelector('.ab-item-curr-qty')?.value) || 0
            }))
        };
        
        if(editId) { obj.id = parseInt(editId); await window.DB.update('subcontract_abstracts', obj); }
        else {
            obj.id = await window.DB.add('subcontract_abstracts', obj);
        }
        
        if (window.sendApproverNotifications && obj.intended_approver) {
            await window.sendApproverNotifications(obj.intended_approver, '', 'لديك مستخلص باطن يحتاج إلى اعتمادك', 'openAbstractModal(' + (obj.id || "''") + ')');
        }
        
        currentSubcontractAbstracts = await window.DB.getAll('subcontract_abstracts') || [];
        alert('تم الحفظ');
        window.renderAbstracts();
        window.closeAbstractModal();
    } catch(e) { alert('خطأ: ' + e.message); }
};

window.deleteAbstract = async function(id) {
    if(!confirm('حذف المستخلص؟')) return;
    await window.DB.remove('subcontract_abstracts', id);
    window.renderAbstracts();
};

window.approveAbstract = async function(id) {
    if(confirm('هل أنت متأكد من اعتماد هذا المستخلص؟ (سيتم توليد قيد تلقائياً)')) {
        const a = currentSubcontractAbstracts.find(x => String(x.id) === String(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) {
                await window.generateSubcontractAbstractJournal(a);
                alert('تم الاعتماد وتوليد القيد بنجاح!');
            }

            currentSubcontractAbstracts = await window.DB.getAll('subcontract_abstracts') || [];
            renderAbstracts();
        }
    }
};

window.payAbstract = function(id, suggestedAmount = null) {
    const a = typeof currentSubcontractAbstracts !== 'undefined' ? currentSubcontractAbstracts.find(x => String(x.id) === String(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;



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.curr_works) || 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;
    const otherDed = parseFloat(a.other_deductions) || 0;
    
    // Debit Costs (Gross)
    if(gross > 0) rows.push({ account_id: costAcc.id, debit: gross, credit: 0, project_id: cont.project_id });
    
    // Supplier (Net)
    if(net > 0) {
        rows.push({ account_id: supAcc.id, debit: 0, credit: net, project_id: cont.project_id, contact_id: cont.subcontractor_id });
    } else if (net < 0) {
        rows.push({ account_id: supAcc.id, debit: Math.abs(net), credit: 0, project_id: cont.project_id, contact_id: cont.subcontractor_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, contact_id: cont.subcontractor_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, contact_id: cont.subcontractor_id });
    }

    // Credit Other Deductions
    if(otherDed > 0) {
        const otherAcc = await window.resolveSystemAccount('استقطاعات متنوعة من مقاولي الباطن', ['إيرادات', 'أخرى'], 'revenues');
        rows.push({ account_id: otherAcc.id, debit: 0, credit: otherDed, project_id: cont.project_id, contact_id: cont.subcontractor_id });
    }
    
    let totDebit = 0;
    let totCredit = 0;
    rows.forEach(r => { totDebit += r.debit; totCredit += r.credit; });
    
    // Auto-balance if floating point diff
    if (Math.abs(totDebit - totCredit) > 0.001) {
        const diff = totDebit - totCredit;
        if (diff > 0) {
            rows.push({ account_id: costAcc.id, debit: 0, credit: diff, project_id: cont.project_id });
        } else {
            rows.push({ account_id: costAcc.id, debit: Math.abs(diff), credit: 0, 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: Math.max(totDebit, totCredit),
        rows: rows
    };
    
    await window.DB.add('journal_entries', journalObj);
};


window.signAbstract = async function() {
    const id = document.getElementById('abstract-id').value;
    if(!id) return;
    
    if(!confirm("هل أنت متأكد من توقيع هذا المستخلص كمعتمد؟")) return;
    
    const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
    const ab = abstracts.find(a => String(a.id) === String(id));
    if(!ab) return;
    
    const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
    const cName = currentUser.name || currentUser.username;
    
    const dtNow = new Date().toLocaleString('ar-EG', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: true });
    const signedName = cName + ' - ' + dtNow;
    if (!ab.paper_approved_by) {
        ab.paper_approved_by = signedName;
    } else if (!(ab.paper_approved_by || '').split(',').some(s=>s.trim().startsWith(cName))) {
        ab.paper_approved_by += '<br>' + signedName;
    }
    
    await window.DB.update('subcontract_abstracts', ab);
    currentSubcontractAbstracts = await window.DB.getAll('subcontract_abstracts') || [];
    
    document.getElementById('btn-sign-ab').style.display = 'none';
      const sigContainer = document.getElementById('subcontract-signatures-container');
      const sigList = document.getElementById('subcontract-signatures-list');
      if (sigContainer && sigList) {
          sigContainer.style.display = 'block';
          sigList.innerHTML = ab.paper_approved_by;
      }
    alert("تم التوقيع بنجاح!");
};
