
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>
                <button class="action-btn" onclick="window.printAbstractToPDF(${ab.id}, 'subcontract')" style="background:#e67e22; color:#fff; border:none; padding:4px 8px; border-radius:4px; font-weight:bold;" title="حفظ PDF / طباعة"><i class="fas fa-file-pdf"></i> حفظ PDF</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("تم التوقيع بنجاح!");
};

// ============================================
// UNIVERSAL ABSTRACT PDF EXPORT & PRINT
// ============================================
window.printAbstractToPDF = async function(id = null, type = 'subcontract') {
    try {
        let ab = null;
        let docTitle = 'مستخلص أعمال';
        let abNumber = '-';
        let partnerName = '-';
        let projectName = '-';
        let contractNumber = '-';
        let abDate = '-';
        let abPeriod = '-';
        let abStatus = 'معتمد';
        let notes = '';
        let items = [];
        let summaryData = {
            worksTitle: 'الإجماليات (جملة الأعمال)',
            deductionsTitle: 'الاستقطاعات من الجاري',
            netTitle: 'الصافي المستحق للمقاول',
            totalWorks: 0,
            prevWorks: 0,
            currWorks: 0,
            advance: 0,
            taxVal: 0,
            taxPct: 0,
            retentionVal: 0,
            retentionPct: 0,
            otherDed: 0,
            totalDed: 0,
            netValue: 0
        };

        let allProjects = [], allContacts = [], allSubcontracts = [], allClientContracts = [];
        try { allProjects = (await window.DB.getAll('projects')) || window.currentProjects || []; } catch(e) { allProjects = window.currentProjects || []; }
        try { allContacts = (await window.DB.getAll('contacts')) || window.currentContacts || []; } catch(e) { allContacts = window.currentContacts || []; }
        try { allSubcontracts = (await window.DB.getAll('subcontracts')) || window.currentSubcontracts || []; } catch(e) { allSubcontracts = window.currentSubcontracts || []; }
        try { allClientContracts = (await window.DB.getAll('client_contracts')) || window.currentClientContracts || []; } catch(e) { allClientContracts = window.currentClientContracts || []; }

        const getProjName = (pId) => (allProjects.find(p => String(p.id) === String(pId)) || {}).name || '-';
        const getContactName = (cId) => (allContacts.find(c => String(c.id) === String(cId)) || {}).name || '-';

        if (type === 'subcontract' || type === 'subcontract_modal') {
            docTitle = 'مستخلص أعمال مقاول باطن';
            summaryData.netTitle = 'الصافي المستحق للمقاول';
            if (id && id !== 'null' && type !== 'subcontract_modal') {
                const list = await window.DB?.getAll('subcontract_abstracts').catch(() => []);
                ab = (list || []).find(a => String(a.id) === String(id));
            }
            if (ab) {
                const sc = allSubcontracts.find(s => String(s.id) === String(ab.contract_id)) || {};
                abNumber = ab.abstract_number || ('#' + ab.id);
                partnerName = getContactName(ab.subcontractor_id || sc.subcontractor_id);
                projectName = getProjName(ab.project_id || sc.project_id);
                contractNumber = sc.contract_number || '-';
                abDate = ab.date || '-';
                abPeriod = ab.period || '-';
                abStatus = ab.status === 'paid' ? 'مدفوع بالكامل' : (ab.status === 'approved' ? 'معتمد' : 'مسودة');
                items = Array.isArray(ab.items) ? ab.items : [];
                
                summaryData.currWorks = parseFloat(ab.curr_works || ab.gross_value || 0) || items.reduce((s, it) => s + ((parseFloat(it.current_qty||it.curr_qty||0) * parseFloat(it.price||0))), 0);
                summaryData.prevWorks = items.reduce((s, it) => s + ((parseFloat(it.prev_qty||0) * parseFloat(it.price||0))), 0);
                summaryData.totalWorks = summaryData.prevWorks + summaryData.currWorks;
                summaryData.advance = parseFloat(ab.advance_payment || 0);
                summaryData.taxVal = parseFloat(ab.tax_value || 0);
                summaryData.taxPct = parseFloat(ab.tax_percent || 0);
                summaryData.retentionVal = parseFloat(ab.retention_value || 0);
                summaryData.retentionPct = parseFloat(ab.retention_percent || 0);
                summaryData.otherDed = parseFloat(ab.other_deductions || 0);
                summaryData.totalDed = parseFloat(ab.total_deductions !== undefined ? ab.total_deductions : (summaryData.advance + summaryData.taxVal + summaryData.retentionVal + summaryData.otherDed));
                summaryData.netValue = parseFloat(ab.net_value !== undefined ? ab.net_value : (summaryData.currWorks - summaryData.totalDed));
            } else {
                const cId = document.getElementById('ab-contract-id')?.value;
                const sc = allSubcontracts.find(s => String(s.id) === String(cId)) || {};
                abNumber = document.getElementById('ab-abstract-number')?.value || 'جديد';
                partnerName = getContactName(sc.subcontractor_id);
                projectName = getProjName(sc.project_id);
                contractNumber = sc.contract_number || '-';
                abDate = document.getElementById('ab-date')?.value || new Date().toISOString().slice(0,10);
                abPeriod = document.getElementById('ab-period')?.value || '-';
                abStatus = 'معاينة المستخلص الحالي';
                items = Array.from(document.querySelectorAll('#ab-items-tbody tr')).map(tr => ({
                    name: tr.querySelector('.ab-item-name')?.value || '',
                    unit: tr.querySelector('.ab-item-unit')?.value || '',
                    price: parseFloat(tr.querySelector('.ab-item-price')?.value || 0) || 0,
                    prev_qty: parseFloat(tr.querySelector('.ab-item-prev-qty')?.innerText || tr.querySelector('.ab-item-prev-qty')?.value || 0) || 0,
                    curr_qty: parseFloat(tr.querySelector('.ab-item-curr-qty')?.value || 0) || 0,
                    total_val: parseFloat((tr.querySelector('.ab-item-total-val')?.innerText || '0').replace(/,/g,'')) || 0
                }));
                
                summaryData.totalWorks = parseFloat((document.getElementById('ab-total-works')?.innerText || '0').replace(/,/g,'')) || 0;
                summaryData.prevWorks = parseFloat((document.getElementById('ab-prev-works')?.innerText || '0').replace(/,/g,'')) || 0;
                summaryData.currWorks = parseFloat((document.getElementById('ab-current-works')?.innerText || '0').replace(/,/g,'')) || 0;
                summaryData.advance = parseFloat((document.getElementById('ab-advance-payment')?.value || '0').replace(/,/g,'')) || 0;
                summaryData.taxVal = parseFloat((document.getElementById('ab-tax-value')?.innerText || '0').replace(/,/g,'')) || 0;
                summaryData.taxPct = parseFloat(document.getElementById('ab-tax-percent')?.value || 0);
                summaryData.retentionVal = parseFloat((document.getElementById('ab-retention-value')?.innerText || '0').replace(/,/g,'')) || 0;
                summaryData.retentionPct = parseFloat(document.getElementById('ab-retention-percent')?.value || 0);
                summaryData.otherDed = parseFloat((document.getElementById('ab-other-deductions')?.value || '0').replace(/,/g,'')) || 0;
                summaryData.totalDed = parseFloat((document.getElementById('ab-total-deductions')?.innerText || '0').replace(/,/g,'')) || (summaryData.advance + summaryData.taxVal + summaryData.retentionVal + summaryData.otherDed);
                summaryData.netValue = parseFloat((document.getElementById('ab-net-value')?.innerText || '0').replace(/,/g,'')) || 0;
            }
        } else if (type === 'client' || type === 'client_modal') {
            docTitle = 'مستخلص إيراد أعمال عميل';
            summaryData.worksTitle = 'إجماليات الأعمال (مستخلص جاري)';
            summaryData.netTitle = 'الصافي المستحق الصرف (إيراد)';
            if (id && id !== 'null' && type !== 'client_modal') {
                const list = await window.DB?.getAll('client_abstracts').catch(() => []);
                ab = (list || []).find(a => String(a.id) === String(id));
            } else if (type === 'client_modal') {
                const mId = document.getElementById('edit-client-abstract-id')?.value;
                if (mId) {
                    const list = await window.DB?.getAll('client_abstracts').catch(() => []);
                    ab = (list || []).find(a => String(a.id) === String(mId));
                }
            }
            if (ab && type !== 'client_modal') {
                abNumber = ab.abstract_number || ('#' + ab.id);
                partnerName = ab.client_name || '-';
                projectName = getProjName(ab.project_id);
                abDate = ab.date || '-';
                abPeriod = ab.period || '-';
                abStatus = ab.status === 'paid' ? 'محصل بالكامل' : (ab.status === 'approved' ? 'معتمد' : 'مسودة');
                items = Array.isArray(ab.items) ? ab.items : [];
                
                summaryData.totalWorks = parseFloat(ab.gross_value || ab.total_value || 0) || items.reduce((s, it) => s + ((parseFloat(it.prev_qty||0) + parseFloat(it.curr_qty||it.current_qty||0)) * parseFloat(it.price||0)), 0);
                summaryData.prevWorks = items.reduce((s, it) => s + ((parseFloat(it.prev_qty||0) * parseFloat(it.price||0))), 0);
                summaryData.currWorks = parseFloat(ab.current_value !== undefined ? ab.current_value : (summaryData.totalWorks - summaryData.prevWorks)) || 0;
                summaryData.advance = parseFloat(ab.advance_payment || 0);
                summaryData.taxVal = parseFloat(ab.tax_value || 0);
                summaryData.retentionVal = parseFloat(ab.retention_value || 0);
                summaryData.retentionPct = parseFloat(ab.retention_percent || 0);
                summaryData.otherDed = parseFloat(ab.other_deductions || 0);
                summaryData.totalDed = parseFloat(ab.total_deductions !== undefined ? ab.total_deductions : (summaryData.advance + summaryData.taxVal + summaryData.retentionVal + summaryData.otherDed));
                summaryData.netValue = parseFloat(ab.net_value !== undefined ? ab.net_value : (summaryData.currWorks - summaryData.totalDed));
            } else {
                abNumber = document.getElementById('client-abstract-number')?.value || (ab ? (ab.abstract_number || '#' + ab.id) : 'جديد');
                partnerName = document.getElementById('client-abstract-client-name')?.value || (ab ? ab.client_name : '-');
                const pId = document.getElementById('client-abstract-project')?.value || (ab ? ab.project_id : null);
                projectName = getProjName(pId);
                abDate = document.getElementById('client-abstract-date')?.value || (ab ? ab.date : new Date().toISOString().slice(0,10));
                abPeriod = document.getElementById('client-abstract-period')?.value || (ab ? ab.period : '-');
                abStatus = 'معاينة مستخلص عميل';
                items = Array.from(document.querySelectorAll('#client-abstract-items-tbody tr')).map(tr => ({
                    name: tr.cells[0]?.innerText || '',
                    unit: tr.cells[1]?.innerText || '',
                    price: parseFloat(tr.querySelector('.ca-item-price')?.value || 0) || 0,
                    prev_qty: parseFloat(tr.querySelector('.ca-item-prev-qty')?.value || 0) || 0,
                    curr_qty: parseFloat(tr.querySelector('.ca-item-curr-qty')?.value || 0) || 0,
                    total_val: parseFloat((tr.querySelector('.ca-item-curr-val')?.innerText || '0').replace(/,/g,'')) || 0
                }));
                if (items.length === 0 && ab && Array.isArray(ab.items)) items = ab.items;
                
                summaryData.totalWorks = parseFloat((document.getElementById('client-abstract-total-works')?.innerText || '0').replace(/,/g,'')) || (ab ? parseFloat(ab.gross_value||ab.total_value||0) : 0);
                summaryData.prevWorks = parseFloat((document.getElementById('client-abstract-prev-works')?.innerText || '0').replace(/,/g,'')) || 0;
                summaryData.currWorks = parseFloat((document.getElementById('client-abstract-current-works')?.innerText || '0').replace(/,/g,'')) || (ab ? parseFloat(ab.current_value||0) : 0);
                summaryData.advance = parseFloat((document.getElementById('client-abstract-advance-payment')?.value || '0').replace(/,/g,'')) || (ab ? parseFloat(ab.advance_payment||0) : 0);
                summaryData.taxVal = parseFloat((document.getElementById('client-abstract-tax-total-value')?.innerText || '0').replace(/,/g,'')) || (ab ? parseFloat(ab.tax_value||0) : 0);
                summaryData.retentionVal = parseFloat((document.getElementById('client-abstract-retention-value')?.innerText || '0').replace(/,/g,'')) || (ab ? parseFloat(ab.retention_value||0) : 0);
                summaryData.retentionPct = parseFloat(document.getElementById('client-abstract-retention-percent')?.value || 0) || (ab ? parseFloat(ab.retention_percent||0) : 0);
                summaryData.otherDed = parseFloat((document.getElementById('client-abstract-other-deductions')?.value || '0').replace(/,/g,'')) || (ab ? parseFloat(ab.other_deductions||0) : 0);
                summaryData.totalDed = parseFloat((document.getElementById('client-abstract-total-deductions')?.innerText || '0').replace(/,/g,'')) || (ab ? parseFloat(ab.total_deductions||0) : (summaryData.advance + summaryData.taxVal + summaryData.retentionVal + summaryData.otherDed));
                summaryData.netValue = parseFloat((document.getElementById('client-abstract-net-total')?.innerText || '0').replace(/,/g,'')) || (ab ? parseFloat(ab.net_value||0) : 0);
            }
        } else if (type === 'ca_new' || type === 'ca_new_modal') {
            docTitle = 'مستخلص عميل (عقد)';
            summaryData.worksTitle = 'قيمة الأعمال المنفذة';
            summaryData.netTitle = 'الصافي المستحق';
            if (id && id !== 'null' && type !== 'ca_new_modal') {
                const list = await window.DB?.getAll('client_abstracts_new').catch(() => []);
                ab = (list || []).find(a => String(a.id) === String(id));
            }
            if (ab) {
                const cc = allClientContracts.find(c => String(c.id) === String(ab.contract_id)) || {};
                abNumber = ab.abstract_number || ('#' + ab.id);
                partnerName = getContactName(ab.client_id || cc.client_id);
                projectName = getProjName(ab.project_id || cc.project_id);
                contractNumber = cc.contract_number || '-';
                abDate = ab.date || '-';
                abPeriod = '-';
                notes = ab.notes || '';
                summaryData.currWorks = parseFloat(ab.current_value || 0);
                summaryData.totalWorks = summaryData.currWorks;
                summaryData.retentionVal = parseFloat(ab.retention_value || 0);
                summaryData.retentionPct = parseFloat(ab.retention_percent || 0);
                summaryData.otherDed = parseFloat(ab.deduction_value || 0);
                summaryData.totalDed = summaryData.retentionVal + summaryData.otherDed;
                summaryData.netValue = parseFloat(ab.net_value || 0);
            } else {
                abNumber = document.getElementById('ca-new-number')?.value || 'جديد';
                abDate = document.getElementById('ca-new-date')?.value || new Date().toISOString().slice(0,10);
                summaryData.currWorks = parseFloat((document.getElementById('ca-new-current-value')?.value || '0').replace(/,/g,'')) || 0;
                summaryData.totalWorks = summaryData.currWorks;
                summaryData.netValue = parseFloat((document.getElementById('ca-new-net-value')?.innerText || '0').replace(/,/g,'')) || 0;
            }
        } else if (type === 'sa_new' || type === 'sa_new_modal') {
            docTitle = 'مستخلص مقاول باطن (عقد)';
            summaryData.worksTitle = 'قيمة الأعمال المنفذة';
            summaryData.netTitle = 'الصافي المستحق للمقاول';
            if (id && id !== 'null' && type !== 'sa_new_modal') {
                const list = await window.DB?.getAll('sub_abstracts').catch(() => []);
                ab = (list || []).find(a => String(a.id) === String(id));
            }
            if (ab) {
                const sc = allSubcontracts.find(s => String(s.id) === String(ab.contract_id)) || {};
                abNumber = ab.abstract_number || ('#' + ab.id);
                partnerName = getContactName(ab.subcontractor_id || sc.subcontractor_id);
                projectName = getProjName(ab.project_id || sc.project_id);
                contractNumber = sc.contract_number || '-';
                abDate = ab.date || '-';
                summaryData.currWorks = parseFloat(ab.current_value || 0);
                summaryData.totalWorks = summaryData.currWorks;
                summaryData.retentionVal = parseFloat(ab.retention_value || 0);
                summaryData.retentionPct = parseFloat(ab.retention_percent || 0);
                summaryData.otherDed = parseFloat(ab.deduction_value || 0);
                summaryData.totalDed = summaryData.retentionVal + summaryData.otherDed;
                summaryData.netValue = parseFloat(ab.net_value || 0);
            } else {
                abNumber = document.getElementById('sa-number')?.value || 'جديد';
                abDate = document.getElementById('sa-date')?.value || new Date().toISOString().slice(0,10);
                summaryData.currWorks = parseFloat((document.getElementById('sa-current-value')?.value || '0').replace(/,/g,'')) || 0;
                summaryData.totalWorks = summaryData.currWorks;
                summaryData.netValue = parseFloat((document.getElementById('sa-net-value')?.innerText || '0').replace(/,/g,'')) || 0;
            }
        }

        let itemsHtml = '';
        if (items && items.length > 0) {
            itemsHtml = `
                <table>
                    <thead>
                        <tr>
                            <th>م</th>
                            <th>البند / البيان</th>
                            <th>الوحدة</th>
                            <th>الفئة</th>
                            <th>الكمية السابقة</th>
                            <th>الكمية الحالية</th>
                            <th>إجمالي المنفذ</th>
                            <th>إجمالي القيمة</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${items.map((it, idx) => {
                            const prev = parseFloat(it.prev_qty || it.prev || 0) || 0;
                            const curr = parseFloat(it.current_qty || it.curr_qty || it.curr || 0) || 0;
                            const totQty = parseFloat(it.total_qty || (prev + curr)) || (prev + curr);
                            const price = parseFloat(it.price || 0) || 0;
                            const totVal = parseFloat(it.total_val || (totQty * price) || (curr * price)) || (curr * price || totQty * price);
                            return `
                                <tr>
                                    <td>${idx + 1}</td>
                                    <td style="text-align:right; font-weight:bold;">${it.name || '-'}</td>
                                    <td>${it.unit || '-'}</td>
                                    <td>${price.toLocaleString('ar-EG')}</td>
                                    <td>${prev.toLocaleString('ar-EG')}</td>
                                    <td style="color:#27ae60; font-weight:bold;">${curr.toLocaleString('ar-EG')}</td>
                                    <td>${totQty.toLocaleString('ar-EG')}</td>
                                    <td style="font-weight:bold;">${totVal.toLocaleString('ar-EG')} ج.م</td>
                                </tr>
                            `;
                        }).join('')}
                    </tbody>
                </table>
            `;
        } else {
            itemsHtml = `<div style="padding: 15px; text-align: center; color: #666; border: 1px dashed #ccc; border-radius: 5px; margin-bottom: 20px;">تم احتساب إجمالي الأعمال بقيمة واحدة مباشرة كما هو موضح بملخص الحساب أدناه.</div>`;
        }

        let totalsHtml = `
            <div style="display: flex; gap: 15px; margin-top: 15px; margin-bottom: 25px; align-items: stretch; flex-wrap: wrap;">
                <!-- عمود الإجماليات -->
                <div style="flex: 1; min-width: 250px; background: #fff; border: 1px solid #ced4da; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.02); display: flex; flex-direction: column;">
                    <div style="background-color: #2c3e50; color: #fff; padding: 10px 15px; font-weight: bold; font-size: 14px; border-bottom: 1px solid #1a252f;">
                        ${summaryData.worksTitle || 'الإجماليات'}
                    </div>
                    <div style="padding: 12px 15px; display: flex; flex-direction: column; gap: 10px; flex-grow: 1; justify-content: space-between;">
                        ${summaryData.totalWorks !== undefined ? `
                        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed #e9ecef; padding-bottom: 6px;">
                            <span style="color: #495057; font-size: 13px;">جملة الأعمال الإجمالية (التراكمي):</span>
                            <strong style="color: #2c3e50; font-size: 14px;">${(summaryData.totalWorks || 0).toLocaleString('ar-EG')} ج.م</strong>
                        </div>` : ''}
                        ${(summaryData.prevWorks !== undefined && summaryData.prevWorks > 0) ? `
                        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed #e9ecef; padding-bottom: 6px;">
                            <span style="color: #495057; font-size: 13px;">جملة الأعمال السابقة:</span>
                            <strong style="color: #6c757d; font-size: 14px;">${(summaryData.prevWorks || 0).toLocaleString('ar-EG')} ج.م</strong>
                        </div>` : ''}
                        ${summaryData.currWorks !== undefined ? `
                        <div style="display: flex; justify-content: space-between; align-items: center; background: #eafaf1; padding: 8px 10px; border-radius: 4px; border-right: 3px solid #27ae60;">
                            <span style="color: #1e8449; font-weight: bold; font-size: 13px;">جملة الأعمال الحالية:</span>
                            <strong style="color: #27ae60; font-size: 15px; font-weight: 800;">${(summaryData.currWorks || 0).toLocaleString('ar-EG')} ج.م</strong>
                        </div>` : ''}
                    </div>
                </div>

                <!-- عمود الاستقطاعات -->
                <div style="flex: 1; min-width: 250px; background: #fff; border: 1px solid #ced4da; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.02); display: flex; flex-direction: column;">
                    <div style="background-color: #c0392b; color: #fff; padding: 10px 15px; font-weight: bold; font-size: 14px; border-bottom: 1px solid #922b21;">
                        ${summaryData.deductionsTitle || 'الاستقطاعات من الجاري'}
                    </div>
                    <div style="padding: 12px 15px; display: flex; flex-direction: column; gap: 8px; flex-grow: 1;">
                        ${summaryData.advance > 0 ? `
                        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed #e9ecef; padding-bottom: 5px;">
                            <span style="color: #495057; font-size: 13px;">الدفعات المقدمة:</span>
                            <strong style="color: #c0392b; font-size: 13px;">- ${(summaryData.advance || 0).toLocaleString('ar-EG')} ج.م</strong>
                        </div>` : ''}
                        ${(summaryData.taxVal > 0 || summaryData.taxPct > 0) ? `
                        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed #e9ecef; padding-bottom: 5px;">
                            <span style="color: #495057; font-size: 13px;">الضرائب ${summaryData.taxPct ? `(${summaryData.taxPct}%)` : ''}:</span>
                            <strong style="color: #c0392b; font-size: 13px;">- ${(summaryData.taxVal || 0).toLocaleString('ar-EG')} ج.م</strong>
                        </div>` : ''}
                        ${(summaryData.retentionVal > 0 || summaryData.retentionPct > 0) ? `
                        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed #e9ecef; padding-bottom: 5px;">
                            <span style="color: #495057; font-size: 13px;">تأمين أعمال محجوزة ${summaryData.retentionPct ? `(${summaryData.retentionPct}%)` : ''}:</span>
                            <strong style="color: #c0392b; font-size: 13px;">- ${(summaryData.retentionVal || 0).toLocaleString('ar-EG')} ج.م</strong>
                        </div>` : ''}
                        ${summaryData.otherDed > 0 ? `
                        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed #e9ecef; padding-bottom: 5px;">
                            <span style="color: #495057; font-size: 13px;">استقطاعات أخرى / خصم:</span>
                            <strong style="color: #c0392b; font-size: 13px;">- ${(summaryData.otherDed || 0).toLocaleString('ar-EG')} ج.م</strong>
                        </div>` : ''}
                        <div style="display: flex; justify-content: space-between; align-items: center; background: #fdf2f2; padding: 8px 10px; border-radius: 4px; border-right: 3px solid #e74c3c; margin-top: auto;">
                            <span style="color: #922b21; font-weight: bold; font-size: 13px;">إجمالي الاستقطاعات:</span>
                            <strong style="color: #c0392b; font-size: 14px; font-weight: 800;">- ${(summaryData.totalDed || 0).toLocaleString('ar-EG')} ج.م</strong>
                        </div>
                    </div>
                </div>

                <!-- عمود الصافي -->
                <div style="flex: 1; min-width: 250px; background: #fff; border: 2px solid #27ae60; border-radius: 6px; overflow: hidden; box-shadow: 0 2px 6px rgba(39, 174, 96, 0.15); display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; padding: 20px; background: linear-gradient(135deg, #ffffff 0%, #f4fbf7 100%);">
                    <div style="width: 50px; height: 50px; background: #e8f8f5; color: #27ae60; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 24px; margin-bottom: 12px; box-shadow: 0 2px 6px rgba(39, 174, 96, 0.2);">
                        💰
                    </div>
                    <span style="color: #2c3e50; font-size: 15px; font-weight: 700; margin-bottom: 8px;">
                        ${summaryData.netTitle || 'الصافي المستحق للصرف'}
                    </span>
                    <strong style="color: #1e8449; font-size: 26px; font-weight: 900; background: #e8f8f5; padding: 8px 18px; border-radius: 8px; border: 1px solid #a3e4d7; display: block; width: 90%; word-break: break-word;">
                        ${(summaryData.netValue || 0).toLocaleString('ar-EG')} <span style="font-size: 16px;">ج.م</span>
                    </strong>
                    <span style="color: #7f8c8d; font-size: 11px; margin-top: 10px;">
                        القيمة المستحقة للدفع بعد خصم كافة الاستقطاعات والتأمينات
                    </span>
                </div>
            </div>
        `;

        let electronicSigs = '';
        if (ab && ab.paper_approved_by) {
            electronicSigs = ab.paper_approved_by;
        } else if (type === 'subcontract_modal' || type === 'subcontract') {
            electronicSigs = document.getElementById('subcontract-signatures-list')?.innerHTML || '';
        } else if (type === 'client_modal' || type === 'client') {
            electronicSigs = document.getElementById('client-abstract-signatures-list')?.innerHTML || '';
        }

        let sigSectionHtml = '';
        if (electronicSigs && electronicSigs.trim() !== '') {
            // Split only by <br> or newlines to preserve timestamps and commas inside dates
            const cleanSigs = electronicSigs.split(/<\s*br\s*[\/]?\s*>|\r?\n/i)
                .map(s => s.replace(/<[^>]*>?/gm, '').trim())
                .filter(s => s !== '' && s !== 'undefined');

            if (cleanSigs.length > 0) {
                const sigCards = cleanSigs.map(sig => {
                    const parts = sig.split(' - ');
                    const approverName = parts[0] ? parts[0].trim() : sig;
                    const approverDate = parts.length > 1 ? parts.slice(1).join(' - ').trim() : '';

                    return `
                        <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px; padding: 12px 18px; background: #ffffff; border: 1px solid #dee2e6; border-radius: 6px; border-right: 4px solid #27ae60; box-shadow: 0 1px 3px rgba(0,0,0,0.03);">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <span style="display: flex; align-items: center; justify-content: center; width: 32px; height: 32px; background: #e8f8f5; color: #27ae60; border-radius: 50%; font-weight: bold; font-size: 16px;">✓</span>
                                <div>
                                    <span style="display: block; font-size: 11px; color: #7f8c8d; font-weight: 600;">قام بالاعتماد والتوقيع للمستخلص:</span>
                                    <strong style="font-size: 15px; color: #2c3e50; direction: rtl; display: inline-block;">${approverName}</strong>
                                </div>
                            </div>
                            ${approverDate ? `
                            <div style="background: #f8f9fa; padding: 6px 14px; border-radius: 4px; border: 1px solid #e9ecef; text-align: left; direction: ltr;">
                                <span style="display: inline-block; font-size: 11px; color: #7f8c8d; font-weight: 600; direction: rtl; margin-left: 6px;">تاريخ ووقت الاعتماد:</span>
                                <strong style="font-size: 13px; color: #2f3640; direction: ltr; display: inline-block;">${approverDate}</strong>
                            </div>` : ''}
                        </div>
                    `;
                }).join('');

                sigSectionHtml = `
                    <div style="margin-top: 35px; margin-bottom: 35px; border: 1px solid #ced4da; border-radius: 8px; overflow: hidden; background: #f8f9fa; box-shadow: 0 2px 8px rgba(0,0,0,0.03);">
                        <div style="background-color: #2c3e50; color: #ffffff; padding: 12px 20px; font-weight: 700; font-size: 15px; display: flex; align-items: center; justify-content: space-between;">
                            <span>سجل الاعتمادات والتوقيعات الإلكترونية على النظام</span>
                            <span style="font-size: 12px; background: rgba(255,255,255,0.15); padding: 4px 12px; border-radius: 4px; font-weight: normal;">موثق إلكترونياً وبموجب الصلاحية</span>
                        </div>
                        <div style="padding: 16px; display: flex; flex-direction: column; gap: 10px;">
                            ${sigCards}
                        </div>
                    </div>
                `;
            }
        }

        const printWin = window.open('', '_blank', 'width=1000,height=800');
        if (!printWin) {
            alert('يرجى السماح بالنوافذ المنبثقة (Popups) لعرض وحفظ ملف PDF.');
            return;
        }
        printWin.document.write(`
            <html dir="rtl">
            <head>
                <meta charset="UTF-8">
                <title>حفظ وتنزيل مستخلص بصيغة PDF - ${docTitle}</title>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
                <style>
                    @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap');
                    @media print {
                        @page { size: A4; margin: 15mm; }
                        body { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; background: #fff !important; color: #000 !important; padding: 0 !important; }
                        .no-print { display: none !important; }
                    }
                    body {
                        font-family: 'Cairo', Tahoma, sans-serif;
                        padding: 25px;
                        background: #f4f7f6;
                        color: #222;
                        direction: rtl;
                        line-height: 1.6;
                        margin: 0;
                    }
                    .document-wrapper {
                        max-width: 900px;
                        margin: 0 auto;
                        background: #fff;
                        padding: 40px;
                        border-radius: 8px;
                        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
                    }
                    .header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        border-bottom: 3px solid #27ae60;
                        padding-bottom: 15px;
                        margin-bottom: 25px;
                    }
                    .header-title {
                        text-align: center;
                        flex-grow: 1;
                    }
                    .header-title h2 {
                        margin: 0;
                        font-size: 26px;
                        color: #1a252f;
                        font-weight: 800;
                    }
                    .header-title h4 {
                        margin: 5px 0 0 0;
                        font-size: 16px;
                        color: #7f8c8d;
                    }
                    .meta-box {
                        display: grid;
                        grid-template-columns: repeat(3, 1fr);
                        gap: 15px;
                        background: #f8f9fa;
                        border: 1px solid #dee2e6;
                        border-radius: 6px;
                        padding: 15px;
                        margin-bottom: 25px;
                    }
                    .meta-item strong {
                        color: #555;
                        display: block;
                        font-size: 13px;
                    }
                    .meta-item span {
                        font-size: 16px;
                        font-weight: 700;
                        color: #111;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 25px;
                        font-size: 14px;
                    }
                    th, td {
                        border: 1px solid #ced4da;
                        padding: 10px;
                        text-align: center;
                    }
                    th {
                        background-color: #2c3e50;
                        color: #ffffff;
                        font-weight: 700;
                    }
                    tr:nth-child(even) {
                        background-color: #f8f9fa;
                    }
                    .totals-section {
                        display: flex;
                        justify-content: flex-end;
                        margin-top: 10px;
                        margin-bottom: 30px;
                    }
                    .totals-box {
                        width: 400px;
                        border: 1px solid #ced4da;
                        border-radius: 6px;
                        overflow: hidden;
                        background: #fff;
                    }
                    .total-row {
                        display: flex;
                        justify-content: space-between;
                        padding: 10px 15px;
                        border-bottom: 1px solid #eee;
                        font-size: 14px;
                    }
                    .total-row:last-child {
                        border-bottom: none;
                    }
                    .total-row.net {
                        background: #d4edda;
                        color: #155724;
                        font-size: 18px;
                        font-weight: 800;
                        border-top: 2px solid #27ae60;
                    }
                    .signatures {
                        display: flex;
                        justify-content: space-around;
                        margin-top: 40px;
                        padding-top: 20px;
                        border-top: 2px dashed #bbb;
                        text-align: center;
                    }
                    .sig-box {
                        width: 22%;
                    }
                    .sig-box strong {
                        display: block;
                        font-size: 15px;
                        margin-bottom: 40px;
                        color: #333;
                    }
                    .watermark {
                        text-align: center;
                        color: #6c757d;
                        font-size: 13px;
                        margin-top: 40px;
                        font-weight: bold;
                    }
                    .top-action-bar {
                        max-width: 900px;
                        margin: 0 auto 20px auto;
                        background: #2c3e50;
                        padding: 15px 25px;
                        border-radius: 8px;
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        flex-wrap: wrap;
                        gap: 15px;
                        color: #fff;
                        box-shadow: 0 4px 10px rgba(0,0,0,0.15);
                    }
                    .action-buttons {
                        display: flex;
                        gap: 12px;
                    }
                    .btn {
                        border: none;
                        padding: 10px 22px;
                        font-size: 15px;
                        font-weight: bold;
                        border-radius: 6px;
                        cursor: pointer;
                        font-family: 'Cairo';
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        transition: all 0.2s;
                    }
                    .btn-pdf {
                        background: #e67e22;
                        color: white;
                        box-shadow: 0 2px 5px rgba(230,126,34,0.3);
                    }
                    .btn-pdf:hover { background: #d35400; transform: translateY(-1px); }
                    .btn-print {
                        background: #3498db;
                        color: white;
                        box-shadow: 0 2px 5px rgba(52,152,219,0.3);
                    }
                    .btn-print:hover { background: #2980b9; transform: translateY(-1px); }
                </style>
            </head>
            <body>
                <div class="top-action-bar no-print">
                    <div>
                        <strong style="font-size:16px; display:block;">📄 معاينة المستند جاهز للحفظ أو الطباعة</strong>
                        <span style="font-size:13px; color:#dcdde1;">اختر الحفظ المباشر على جهازك باللون البرتقالي، أو الطباعة العادية باللون الأزرق</span>
                    </div>
                    <div class="action-buttons">
                        <button class="btn btn-pdf" id="btn-dl-pdf" onclick="downloadPDF()">📥 حفظ ملف PDF على جهازك</button>
                        <button class="btn btn-print" onclick="window.print()">🖨️ طباعة ورقية</button>
                    </div>
                </div>

                <div id="document-content" class="document-wrapper">
                    <div class="header">
                        <div class="header-title">
                            <h2>${docTitle}</h2>
                            <h4>رقم المستند: ${abNumber}</h4>
                        </div>
                    </div>

                    <div class="meta-box">
                        <div class="meta-item"><strong>المقاول / العميل:</strong><span>${partnerName || '-'}</span></div>
                        <div class="meta-item"><strong>المشروع / مركز التكلفة:</strong><span>${projectName || '-'}</span></div>
                        <div class="meta-item"><strong>رقم العقد:</strong><span>${contractNumber || '-'}</span></div>
                        <div class="meta-item"><strong>التاريخ:</strong><span>${abDate || '-'}</span></div>
                        <div class="meta-item"><strong>عن الفترة:</strong><span>${abPeriod || '-'}</span></div>
                        <div class="meta-item"><strong>حالة المستخلص:</strong><span>${abStatus}</span></div>
                    </div>

                    ${itemsHtml}

                    ${totalsHtml}

                    ${notes ? `<div style="margin-bottom:25px; padding:12px; background:#f8f9fa; border-left:4px solid #3b82f6; border-radius:4px;"><strong>ملاحظات:</strong> ${notes}</div>` : ''}

                    ${sigSectionHtml}

                    <div class="signatures">
                        <div class="sig-box"><strong>إعداد مهندس الموقع</strong><span>.......................</span></div>
                        <div class="sig-box"><strong>مراجعة المكتب الفني</strong><span>.......................</span></div>
                        <div class="sig-box"><strong>المراجعة المالية والحسابات</strong><span>.......................</span></div>
                        <div class="sig-box"><strong>اعتماد المدير العام</strong><span>.......................</span></div>
                    </div>

                    <div class="watermark">
                        ✔ تم إنشاء واحتساب هذا المستخلص آلياً بواسطة نظام <strong>Easy ERP</strong> لإدارة المشروعات
                    </div>
                </div>

                <script>
                    function downloadPDF() {
                        const btn = document.getElementById('btn-dl-pdf');
                        const oldText = btn.innerHTML;
                        btn.innerHTML = '⌛ جاري التنزيل والحفظ على جهازك...';
                        btn.disabled = true;
                        
                        const element = document.getElementById('document-content');
                        const cleanNum = '${abNumber}'.replace(/[^a-zA-Z0-9_\u0600-\u06FF]/g, "") || 'Document';
                        const filename = 'مستخلص_أعمال_' + cleanNum + '.pdf';
                        
                        const opt = {
                            margin:       10,
                            filename:     filename,
                            image:        { type: 'jpeg', quality: 0.98 },
                            html2canvas:  { scale: 2, useCORS: true, backgroundColor: '#ffffff' },
                            jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
                        };
                        
                        if (typeof html2pdf !== 'undefined') {
                            html2pdf().set(opt).from(element).save().then(() => {
                                btn.innerHTML = oldText;
                                btn.disabled = false;
                            }).catch(err => {
                                console.error('Error:', err);
                                btn.innerHTML = oldText;
                                btn.disabled = false;
                                alert('حدث خطأ أثناء التنزيل المباشر، سيتم فتح نافذة الطباعة لاختيار Save as PDF من قائمة الطابعة.');
                                window.print();
                            });
                        } else {
                            alert('سيتم فتح شاشة الطباعة الآن. لحفظ الملف على الكمبيوتر يرجى تغيير اسم الطابعة (Destination) إلى "Save as PDF" أو "حفظ بتنسيق PDF" وتأكيد الحفظ.');
                            btn.innerHTML = oldText;
                            btn.disabled = false;
                            window.print();
                        }
                    }
                </script>
            </body>
            </html>
        `);
        printWin.document.close();
    } catch (err) {
        console.error('Error generating Abstract PDF:', err);
        alert('حدث خطأ أثناء إعداد مستند PDF');
    }
};

window.printSubcontractAbstract = function(id) {
    window.printAbstractToPDF(id, 'subcontract');
};

