        };

    }, 1500);
});
window.addEventListener('load', function() {
    setTimeout(function() {
        console.log("طھظپط¹ظٹظ„ ظ†ط¸ط§ظ… ظ…ط³طھط®ظ„طµط§طھ ط§ظ„ظ…ظ‚ط§ظˆظ„ظٹظ† (ط§ظ„ظ†ط³ط®ط© ط§ظ„ظ†ظ‡ط§ط¦ظٹط©)...");

        // 1. ط§ظ„ط¯ط§ظ„ط© ط§ظ„طھظٹ طھط¹ظ…ظ„ ط¹ظ†ط¯ ط§ط®طھظٹط§ط± ط§ظ„ط¹ظ‚ط¯ ظپظٹ ط§ظ„ظ…ط³طھط®ظ„طµ
        window.onAbstractContractChange = async function() {
            const contractSelect = document.getElementById('ab-contract-id');
            if (!contractSelect) return;

            const contractId = contractSelect.value;
            if (!contractId) {
                window.currentAbstractItems = [];
                window.renderAbstractItemsTable();
                return;
            }

            try {
                // ط¬ظ„ط¨ ط¨ظٹط§ظ†ط§طھ ط§ظ„ط¹ظ‚ط¯ ظ…ط¨ط§ط´ط±ط© ظ…ظ† ظ‚ط§ط¹ط¯ط© ط§ظ„ط¨ظٹط§ظ†ط§طھ
                const contracts = await window.DB.getAll('subcontracts') || [];
                const contract = contracts.find(c => String(c.id) === String(contractId));

                if (!contract || !contract.boq_items || contract.boq_items.length === 0) {
                    alert('ظ‡ط°ط§ ط§ظ„ط¹ظ‚ط¯ ظ„ط§ ظٹط­طھظˆظٹ ط¹ظ„ظ‰ ط¨ظ†ظˆط¯ ظ…ط³ط¬ظ„ط©. ظٹظ…ظƒظ†ظƒ ط¥ط¶ط§ظپط© ط§ظ„ط¨ظ†ظˆط¯ ظٹط¯ظˆظٹط§ظ‹.');
                    window.currentAbstractItems = [];
                } else {
                    // ط³ط­ط¨ ط¨ظ†ظˆط¯ ط§ظ„ط¹ظ‚ط¯ ظˆطھط¬ظ‡ظٹط²ظ‡ط§ ظ„ظ„ظ…ط³طھط®ظ„طµ
                    window.currentAbstractItems = JSON.parse(JSON.stringify(contract.boq_items)).map(item => ({
                        name: item.name,
                        unit: item.unit,
                        price: parseFloat(item.price) || 0,
                        prev_qty: 0, // ظٹظ…ظƒظ†ظƒ طھط­ط¯ظٹط«ظ‡ط§ ظ„ط§ط­ظ‚ط§ظ‹ ظ…ظ† ظ…ط³طھط®ظ„طµط§طھ ط³ط§ط¨ظ‚ط©
                        current_qty: 0 
                    }));
                }
                window.renderAbstractItemsTable();
            } catch (e) {
                console.error("ط®ط·ط£ ظپظٹ ط¬ظ„ط¨ ط¨ظٹط§ظ†ط§طھ ط§ظ„ط¹ظ‚ط¯:", e);
            }
        };

        // 2. ط¯ط§ظ„ط© ط±ط³ظ… ط¬ط¯ظˆظ„ ط§ظ„ظ…ط³طھط®ظ„طµ
        window.renderAbstractItemsTable = function() {
            const tbody = document.getElementById('ab-items-tbody');
            if (!tbody) return;
            tbody.innerHTML = '';

            let currentWorksTotal = 0;
            let prevWorksTotal = 0;
            let totalWorksTotal = 0;

            (window.currentAbstractItems || []).forEach((it, index) => {
                const currentQty = parseFloat(it.current_qty) || 0;
                const prevQty = parseFloat(it.prev_qty) || 0;
                const totalQty = prevQty + currentQty;
                const price = parseFloat(it.price) || 0;

                const currentVal = currentQty * price;
                const prevVal = prevQty * price;
                const totalVal = totalQty * price;

                currentWorksTotal += currentVal;
                prevWorksTotal += prevVal;
                totalWorksTotal += totalVal;

                tbody.innerHTML += `
                    <tr>
                        <td style="text-align:center;">
                            <button class="action-btn btn-delete" onclick="window.removeAbstractItem(${index})" style="padding: 2px 5px; margin-bottom: 5px;">â‌Œ</button>
                        </td>
                        <td><input type="text" value="${it.name || ''}" onchange="window.updateAbstractItem(${index}, 'name', this.value)" style="width:100%; border:none; background:transparent; color:#fff; font-weight:bold;"></td>
                        <td style="text-align:center;"><input type="text" value="${it.unit || ''}" onchange="window.updateAbstractItem(${index}, 'unit', this.value)" style="width:50px; border:none; background:transparent; color:#fff; text-align:center;"></td>
                        <td style="text-align:center;"><input type="number" step="any" value="${price}" onchange="window.updateAbstractItem(${index}, 'price', this.value)" style="width:70px; border:none; background:transparent; color:#fff; text-align:center;"></td>
                        <td style="text-align:center;"><input type="number" step="any" value="${prevQty}" onchange="window.updateAbstractItem(${index}, 'prev_qty', this.value)" style="width:60px; border:none; background:transparent; color:#aaa; text-align:center;"></td>
                        <td style="text-align:center;"><input type="number" step="any" value="${currentQty}" onchange="window.updateAbstractItem(${index}, 'current_qty', this.value)" style="width:70px; border:1px solid var(--primary); background:rgba(0,0,0,0.3); color:#fff; font-weight:bold; padding:5px;"></td>
                        <td style="text-align:center; color:#ff9800; font-weight:bold;">${totalQty}</td>
                        <td style="text-align:center; color:#aaa;">${prevVal.toLocaleString('en-US')}</td>
                        <td style="text-align:center; color:var(--primary); font-weight:bold;">${currentVal.toLocaleString('en-US')}</td>
                        <td style="text-align:center; color:#4caf50; font-weight:bold;">${totalVal.toLocaleString('en-US')}</td>
                    </tr>
                `;
            });

            // طھط­ط¯ظٹط« ط§ظ„ط¥ط¬ظ…ط§ظ„ظٹط§طھ
            const currWorksEl = document.getElementById('ab-current-works');
            if (currWorksEl) currWorksEl.innerText = currentWorksTotal.toLocaleString('en-US');
            
            if (typeof window.calculateAbstractTotals === 'function') window.calculateAbstractTotals();
        };

        // 3. ط¯ظˆط§ظ„ ط§ظ„طھط­ط¯ظٹط« ظˆط§ظ„ط¥ط¶ط§ظپط©
        window.updateAbstractItem = function(index, field, value) {
            window.currentAbstractItems[index][field] = value;
            window.renderAbstractItemsTable();
        };

        window.removeAbstractItem = function(index) {
            window.currentAbstractItems.splice(index, 1);
            window.renderAbstractItemsTable();
        };

        window.addAbstractItem = function() {
            window.currentAbstractItems.push({ name: 'ط¨ظ†ط¯ ط¬ط¯ظٹط¯', unit: 'ظ…طھط±', price: 0, prev_qty: 0, current_qty: 0 });
            window.renderAbstractItemsTable();
        };

        // 4. ط§ظ„ط­ط³ط§ط¨ط§طھ ط§ظ„طھظ„ظ‚ط§ط¦ظٹط© (ط§ط³طھظ‚ط·ط§ط¹ط§طھ ظˆطµط§ظپظٹ)
        window.calculateAbstractTotals = function() {
            const currWorksText = document.getElementById('ab-current-works')?.innerText || '0';
            const currWorks = parseFloat(currWorksText.replace(/,/g, '')) || 0;

            const advPayment = parseFloat(document.getElementById('ab-advance-payment')?.value) || 0;
            const taxPercent = parseFloat(document.getElementById('ab-tax-percent')?.value) || 0;
            const retPercent = parseFloat(document.getElementById('ab-retention-percent')?.value) || 0;
            const otherDed = parseFloat(document.getElementById('ab-other-deductions')?.value) || 0;

            const taxVal = currWorks * (taxPercent / 100);
            const retentionVal = currWorks * (retPercent / 100);

            if(document.getElementById('ab-tax-value')) document.getElementById('ab-tax-value').innerText = taxVal.toLocaleString('en-US');
            if(document.getElementById('ab-retention-value')) document.getElementById('ab-retention-value').innerText = retentionVal.toLocaleString('en-US');

            const totalDed = advPayment + taxVal + retentionVal + otherDed;
            if(document.getElementById('ab-total-deductions')) document.getElementById('ab-total-deductions').innerText = totalDed.toLocaleString('en-US');

            const netTotal = currWorks - totalDed;
            if(document.getElementById('ab-net-value')) document.getElementById('ab-net-value').innerText = netTotal.toLocaleString('en-US');
        };

    }, 1500);
});
window.renderAbstracts = async function() {
    const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
    const subcontractors = await window.DB.getAll('subcontractors') || [];
    const projects = await window.DB.getAll('projects') || [];
    const subcontracts = await window.DB.getAll('subcontracts') || [];

    // ط§ظ„ط¬ط¯ظˆظ„ ط¯ط§ط®ظ„ view ظ…ط³طھط®ظ„طµط§طھ ظ…ظ‚ط§ظˆظ„ظٹ ط§ظ„ط¨ط§ط·ظ† طھط­ط¯ظٹط¯ط§ظ‹
    const view = document.getElementById('view-subcontract-abstracts');
    const table = view?.querySelector('table');
    if (!table) return;

    const tbody = table.querySelector('tbody') || table.appendChild(document.createElement('tbody'));
    tbody.innerHTML = '';

    abstracts.forEach(abs => {
        const sub  = subcontractors.find(s => s.id === abs.subcontractor_id)?.name || '-';
        const proj = projects.find(p => p.id === abs.project_id)?.name || '-';
        const cont = subcontracts.find(c => c.id === abs.contract_id)?.contract_number || abs.contract_id || '-';
        const paid = abs.advance_payment || 0;
        const net  = abs.net_value || 0;

        tbody.insertAdjacentHTML('beforeend', `
            <tr>
                <td>${abs.abstract_number || '-'}</td>
                <td>${sub}</td>
                <td>${proj}</td>
                <td>${cont}</td>
                <td>${abs.date || '-'}</td>
                <td>${abs.period || '-'}</td>
                <td>${net.toLocaleString()}</td>
                <td>${paid.toLocaleString()}</td>
                <td>${(net - paid).toLocaleString()}</td>
                <td>${abs.status === 'paid' ? 'ظ…ط¯ظپظˆط¹' : abs.status === 'approved' ? 'ظ…ط¹طھظ…ط¯' : 'ظ…ط³ظˆط¯ط©'}</td>
                <td>
                    <button class="btn btn-sm btn-primary" onclick="editAbstract(${abs.id})">طھط¹ط¯ظٹظ„</button>
                    ${abs.status === 'draft' ? `<button class="btn btn-sm btn-success" onclick="approveAbstractWithJournal(${abs.id})">ط§ط¹طھظ…ط§ط¯</button>` : ''}
                    ${abs.status === 'approved' ? `<button class="btn btn-sm btn-info" onclick="paySubcontractAbstract(${abs.id}, ${net - paid}, ${abs.contract_id})">ط³ط¯ط§ط¯</button>` : ''}
                    <button class="btn btn-sm btn-danger" onclick="deleteAbstract(${abs.id})">ط­ط°ظپ</button>
                </td>
            </tr>
        `);
    });
};
window.approveAbstractWithJournal = async function(id) {
    if(confirm('ظ‡ظ„ ط£ظ†طھ ظ…طھط£ظƒط¯ ظ…ظ† ط§ط¹طھظ…ط§ط¯ ظ‡ط°ط§ ط§ظ„ظ…ط³طھط®ظ„طµطں (ط³ظٹطھظ… طھظˆظ„ظٹط¯ ظ‚ظٹط¯ ط§ط³طھط­ظ‚ط§ظ‚ ظ„ظ„ظ…ظ‚ط§ظˆظ„)')) {
        const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
        const a = abstracts.find(x => x.id === id);
        if(a) {
            a.status = 'approved';
            await window.DB.update('subcontract_abstracts', a);
            
            // Generate Journal Entry
            const subcontracts = await window.DB.getAll('subcontracts') || [];
            const cont = subcontracts.find(c => c.id == a.contract_id);
            if (cont) {
                const journalEntry = {
                    date: new Date().toISOString().split('T')[0],
                    reference: 'SUB-ABS-' + a.abstract_number,
                    description: 'ط§ط³طھط­ظ‚ط§ظ‚ ظ…ط³طھط®ظ„طµ ظ…ظ‚ط§ظˆظ„ ط¨ط§ط·ظ† ط±ظ‚ظ… ' + a.abstract_number,
                    lines: [
                        { account_name: 'طھظƒط§ظ„ظٹظپ ظ…ظ‚ط§ظˆظ„ظٹ ط§ظ„ط¨ط§ط·ظ†', debit: a.net_value, credit: 0 },
                        { account_name: 'ط¯ط§ط¦ظ†ظˆ ظ…ظ‚ط§ظˆظ„ظٹ ط§ظ„ط¨ط§ط·ظ†', debit: 0, credit: a.net_value, contact_id: cont.subcontractor_id }
                    ],
                    total: a.net_value
                };
                await window.DB.add('journal_entries', journalEntry);
                alert('طھظ… ط§ط¹طھظ…ط§ط¯ ط§ظ„ظ…ط³طھط®ظ„طµ ظˆطھظˆظ„ظٹط¯ ط§ظ„ظ‚ظٹط¯ ط¨ظ†ط¬ط§ط­!');
            }
            if (typeof window.renderAbstracts === 'function') window.renderAbstracts();
        }
    }
};

window.paySubcontractAbstract = function(abstractId, remainingAmount, contractId) {
    if (typeof window.openVoucherModal === 'function') {
        window.openVoucherModal('payment', null, { 
            linked_subcontract_abstract_id: abstractId, 
            amount: remainingAmount,
            notes: 'ط³ط¯ط§ط¯ ظ…ط³طھط®ظ„طµ ظ…ظ‚ط§ظˆظ„'
        });
    } else {
        alert('ظٹط±ط¬ظ‰ ط³ط¯ط§ط¯ ط§ظ„ظ…ط¨ظ„ط؛ ظ…ظ† ط´ط§ط´ط© ط³ظ†ط¯ط§طھ ط§ظ„طµط±ظپ ظˆط±ط¨ط·ظ‡ط§ ط¨ط§ظ„ظ…ط³طھط®ظ„طµ.');
    }
};
