
window.onClientAbstractProjectChange = function() {
    const pId = document.getElementById('client-abstract-project').value;
    const proj = currentProjects.find(p => String(p.id) === String(pId));
    if(!proj) {
        document.getElementById('client-abstract-client-name').value = '';
        document.getElementById('client-abstract-items-tbody').innerHTML = '';
        window.calcClientAbstractTotals();
        return;
    }
    
    document.getElementById('client-abstract-client-name').value = proj.client || '';
    
    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.addClientAbstractTaxRow = function(name = '', value = 0) {
    const list = document.getElementById('client-abstract-taxes-list');
    if(!list) return;
    const div = document.createElement('div');
    div.style.display = 'flex';
    div.style.gap = '5px';
    div.style.marginBottom = '5px';
    div.innerHTML = `
        <input type="text" class="ca-tax-name" placeholder="اسم الضريبة" value="${name}" style="flex:1; padding:4px; font-size:0.9em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;">
        <input type="number" class="ca-tax-value" placeholder="القيمة أو %" value="${value}" style="width:70px; padding:4px; font-size:0.9em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;" oninput="window.calcClientAbstractTotals()">
        <select class="ca-tax-type" style="padding:4px; font-size:0.9em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;" onchange="window.calcClientAbstractTotals()">
            <option value="percent">%</option>
            <option value="amount">قيمة</option>
        </select>
        <button type="button" class="btn-danger" style="padding:2px 6px;" onclick="this.parentElement.remove(); window.calcClientAbstractTotals()">X</button>
    `;
    list.appendChild(div);
    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 { currTotal: 0, grossTotal: 0, totalDed: 0, net: 0, taxVal: 0, retVal: 0, advance: 0, otherDed: 0 };
    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 + '%';
    });
    
    if(document.getElementById('client-abstract-prev-works')) document.getElementById('client-abstract-prev-works').innerText = prevTotal.toLocaleString('ar-EG');
    if(document.getElementById('client-abstract-current-works')) document.getElementById('client-abstract-current-works').innerText = currTotal.toLocaleString('ar-EG');
    if(document.getElementById('client-abstract-total-works')) document.getElementById('client-abstract-total-works').innerText = grossTotal.toLocaleString('ar-EG');
    
    let advance = parseFloat(document.getElementById('client-abstract-advance-payment')?.value) || 0;
    
    // Dynamic taxes
    let taxVal = 0;
    let taxesArr = [];
    document.querySelectorAll('#client-abstract-taxes-list > div').forEach(div => {
        let name = div.querySelector('.ca-tax-name').value;
        let v = parseFloat(div.querySelector('.ca-tax-value').value) || 0;
        let type = div.querySelector('.ca-tax-type').value;
        taxesArr.push({ name, value: v, type });
        if(type === 'percent') {
            taxVal += currTotal * (v / 100);
        } else {
            taxVal += v;
        }
    });
    if(document.getElementById('client-abstract-tax-total-value')) {
        document.getElementById('client-abstract-tax-total-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, taxesArr };
};

// Directly attach the onclick event to the save button
const bSaveClientAb = document.getElementById('btn-save-client-abstract');
if (bSaveClientAb) {
    bSaveClientAb.onclick = async () => {
        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,
                taxes: totals.taxesArr,
                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);
        }
    };
}
