
// ============================================
// CLIENT ABSTRACTS LOGIC (RESTORED)
// ============================================

window.onClientAbstractProjectChange = function() {
    const pId = document.getElementById('client-abstract-project').value;
    const proj = currentProjects.find(p => String(p.id) === String(pId));
    if(!proj) return;
    
    document.getElementById('client-abstract-client-name').value = proj.client_name || '';
    
    const tbody = document.getElementById('client-abstract-items-tbody');
    tbody.innerHTML = '';
    
    if(proj.boq_items && Array.isArray(proj.boq_items)) {
        proj.boq_items.forEach(b => {
             let tr = document.createElement('tr');
             tr.innerHTML = `
                 <td><input type="text" class="ca-item-name" value="${b.name || ''}" readonly style="border:none;background:transparent;color:#fff;"></td>
                 <td><input type="text" class="ca-item-unit" value="${b.unit || ''}" readonly style="border:none;background:transparent;color:#fff;width:50px;"></td>
                 <td><input type="number" class="ca-item-price" value="${b.price || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                 <td><input type="number" class="ca-item-total-qty" value="${b.qty || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                 <td><input type="number" class="ca-item-prev-qty" value="0" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                 <td><input type="number" class="ca-item-curr-qty" value="0" step="0.01" style="width:70px;" oninput="window.calcClientAbstractTotals()"></td>
                 <td class="ca-item-total-exec">0</td>
                 <td class="ca-item-prev-val">0</td>
                 <td class="ca-item-curr-val" style="color:var(--primary); font-weight:bold;">0</td>
                 <td class="ca-item-total-val" style="font-weight:bold;">0</td>
                 <td class="ca-item-pct">0%</td>
             `;
             tbody.appendChild(tr);
        });
    }
    
    window.calcClientAbstractTotals();
};

window.calcClientAbstractTotals = function() {
    let prevTotal = 0;
    let currTotal = 0;
    let grossTotal = 0;
    const tbody = document.getElementById('client-abstract-items-tbody');
    if(!tbody) return;
    const rows = tbody.querySelectorAll('tr');
    
    rows.forEach(tr => {
        let price = parseFloat(tr.querySelector('.ca-item-price').value) || 0;
        let totalQty = parseFloat(tr.querySelector('.ca-item-total-qty').value) || 0;
        let pQty = parseFloat(tr.querySelector('.ca-item-prev-qty').value) || 0;
        let cQty = parseFloat(tr.querySelector('.ca-item-curr-qty').value) || 0;
        
        let totalExec = pQty + cQty;
        
        let pVal = pQty * price;
        let cVal = cQty * price;
        let tVal = totalExec * price;
        
        prevTotal += pVal;
        currTotal += cVal;
        grossTotal += tVal;
        
        tr.querySelector('.ca-item-total-exec').innerText = totalExec.toFixed(2);
        tr.querySelector('.ca-item-prev-val').innerText = pVal.toLocaleString('ar-EG');
        tr.querySelector('.ca-item-curr-val').innerText = cVal.toLocaleString('ar-EG');
        tr.querySelector('.ca-item-total-val').innerText = tVal.toLocaleString('ar-EG');
        let pct = totalQty > 0 ? ((totalExec / totalQty) * 100).toFixed(1) : 0;
        tr.querySelector('.ca-item-pct').innerText = pct + '%';
    });
    
    document.getElementById('client-abstract-prev-works').innerText = prevTotal.toLocaleString('ar-EG');
    document.getElementById('client-abstract-current-works').innerText = currTotal.toLocaleString('ar-EG');
    document.getElementById('client-abstract-total-works').innerText = grossTotal.toLocaleString('ar-EG');
    
    let advance = parseFloat(document.getElementById('client-abstract-advance-payment')?.value) || 0;
    
    let taxPct = parseFloat(document.getElementById('client-abstract-tax-percent')?.value) || 0;
    let taxVal = currTotal * (taxPct / 100);
    if(document.getElementById('client-abstract-tax-value')) document.getElementById('client-abstract-tax-value').innerText = taxVal.toLocaleString('ar-EG');
    
    let retPct = parseFloat(document.getElementById('client-abstract-retention-percent')?.value) || 0;
    let retVal = currTotal * (retPct / 100);
    if(document.getElementById('client-abstract-retention-value')) document.getElementById('client-abstract-retention-value').innerText = retVal.toLocaleString('ar-EG');
    
    let otherDed = parseFloat(document.getElementById('client-abstract-other-deductions')?.value) || 0;
    
    let totalDed = advance + taxVal + retVal + otherDed;
    let net = currTotal - totalDed;
    
    if(document.getElementById('client-abstract-total-deductions')) document.getElementById('client-abstract-total-deductions').innerText = totalDed.toLocaleString('ar-EG');
    if(document.getElementById('client-abstract-net-total')) document.getElementById('client-abstract-net-total').innerText = net.toLocaleString('ar-EG');
    
    return { currTotal, grossTotal, totalDed, net, taxVal, retVal, advance, otherDed };
};

// Global click delegation for save to ensure it works even if re-rendered
document.addEventListener('click', async (e) => {
    if(e.target && e.target.id === 'btn-save-client-abstract') {
        try {
            const editIdStr = document.getElementById('edit-client-abstract-id').value;
            const abstract_number = document.getElementById('client-abstract-number').value;
            const date = document.getElementById('client-abstract-date').value;
            const period = document.getElementById('client-abstract-period')?.value || '';
            const project_id = document.getElementById('client-abstract-project').value;
            const client_name = document.getElementById('client-abstract-client-name').value;
            
            if(!project_id) { alert('يجب اختيار المشروع'); return; }
            
            const fileInput = document.getElementById('client-abstract-attachment');
            let attachment = document.getElementById('client-abstract-attachment-view')?.href || null;
            if(attachment === window.location.href || (attachment && attachment.endsWith('#'))) attachment = null;
            
            if (fileInput && fileInput.files && fileInput.files[0]) {
                const file = fileInput.files[0];
                attachment = await new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = (ev) => resolve(ev.target.result);
                    reader.onerror = (ev) => reject(ev);
                    reader.readAsDataURL(file);
                });
            }
            
            const tbody = document.getElementById('client-abstract-items-tbody');
            const rows = tbody.querySelectorAll('tr');
            let items = [];
            rows.forEach(tr => {
                items.push({
                    name: tr.querySelector('.ca-item-name').value,
                    unit: tr.querySelector('.ca-item-unit').value,
                    price: parseFloat(tr.querySelector('.ca-item-price').value) || 0,
                    total_qty: parseFloat(tr.querySelector('.ca-item-total-qty').value) || 0,
                    prev_qty: parseFloat(tr.querySelector('.ca-item-prev-qty').value) || 0,
                    curr_qty: parseFloat(tr.querySelector('.ca-item-curr-qty').value) || 0
                });
            });
            
            const totals = window.calcClientAbstractTotals();
            
            const obj = {
                abstract_number, date, period, project_id, client_name, attachment,
                items,
                advance_payment: totals.advance,
                tax_percent: parseFloat(document.getElementById('client-abstract-tax-percent')?.value) || 0,
                tax_value: totals.taxVal,
                retention_percent: parseFloat(document.getElementById('client-abstract-retention-percent')?.value) || 0,
                retention_value: totals.retVal,
                other_deductions: totals.otherDed,
                gross_value: totals.grossTotal,
                current_value: totals.currTotal,
                total_deductions: totals.totalDed,
                net_value: totals.net,
                status: 'draft'
            };
            
            if (editIdStr) {
                obj.id = parseInt(editIdStr);
                const existing = currentClientAbstracts.find(a => String(a.id) === String(obj.id));
                if(existing) obj.status = existing.status;
                if(obj.status === 'approved') { alert('لا يمكن تعديل مستخلص معتمد'); return; }
                if(!attachment && existing && existing.attachment) obj.attachment = existing.attachment;
                await window.DB.update('client_abstracts', obj);
            } else {
                await window.DB.add('client_abstracts', obj);
            }
            
            closeModal('client-abstract-modal');
            
            // Re-fetch client abstracts
            currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];
            if(typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
            
            alert('تم الحفظ بنجاح');
        } catch(err) {
            alert('خطأ: ' + err.message);
        }
    }
});
