
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 = '';
    
    // Calculate previous quantities from approved abstracts for this project
    const approvedAbstracts = (currentClientAbstracts || []).filter(a => String(a.project_id) === String(pId) && a.status === 'approved');
    let prevQuantities = {};
    approvedAbstracts.forEach(ab => {
        if(ab.items && Array.isArray(ab.items)) {
            ab.items.forEach(item => {
                if(!prevQuantities[item.name]) prevQuantities[item.name] = 0;
                // Add the current quantity executed in that approved abstract
                prevQuantities[item.name] += parseFloat(item.curr_qty) || 0;
            });
        }
    });
    
    if(proj.boq_items && Array.isArray(proj.boq_items)) {
        proj.boq_items.forEach(b => {
             let prevQty = prevQuantities[b.name] || 0;
             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="${prevQty}" 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>
             `;
             tbody.appendChild(tr);
        });
    }
    
    window.calcClientAbstractTotals();
};
