// ============================================================
// CONTRACTS & ABSTRACTS MODULE
// مستخلصات العملاء + مقاولي الباطن + ربط بنود المقايسة
// ============================================================

// ---- State ----
window.contractsAbstractsReady = false;

// ---- Init ----
async function initContractsAbstracts() {
  try {
    window.allClientContracts      = await window.DB.getAll('client_contracts')      || [];
    window.allClientAbstractsNew   = await window.DB.getAll('client_abstracts_new')  || [];
    window.allSubContracts         = await window.DB.getAll('sub_contracts')         || [];
    window.allSubAbstracts         = await window.DB.getAll('sub_abstracts')         || [];
    window.contractsAbstractsReady = true;
  } catch(e) { console.error('contracts init:', e); }
}

// Run after main loadData
const _origLoadData = window.loadData;
window.loadData = async function() {
  await _origLoadData();
  await initContractsAbstracts();
  if(document.getElementById('view-client-contracts')?.classList.contains('active')) renderClientContracts();
  if(document.getElementById('view-client-abstracts-new')?.classList.contains('active')) renderClientAbstractsNew();
  if(document.getElementById('view-sub-contracts')?.classList.contains('active')) renderSubContracts();
  if(document.getElementById('view-sub-abstracts')?.classList.contains('active')) renderSubAbstracts();
};

// ---- Nav Hooks ----
document.addEventListener('click', e => {
  const li = e.target.closest('li[data-view]');
  if(!li) return;
  const v = li.dataset.view;
  if(v === 'client-contracts')      { if(!window.contractsAbstractsReady) initContractsAbstracts().then(renderClientContracts); else renderClientContracts(); }
  if(v === 'client-abstracts-new')  { if(!window.contractsAbstractsReady) initContractsAbstracts().then(renderClientAbstractsNew); else renderClientAbstractsNew(); }
  if(v === 'sub-contracts')         { if(!window.contractsAbstractsReady) initContractsAbstracts().then(renderSubContracts); else renderSubContracts(); }
  if(v === 'sub-abstracts')         { if(!window.contractsAbstractsReady) initContractsAbstracts().then(renderSubAbstracts); else renderSubAbstracts(); }
});

// ============================================================
// HELPERS
// ============================================================
function fmtMoney(n) { return (parseFloat(n)||0).toLocaleString('en-US',{minimumFractionDigits:2}); }
function projName(id) { return (currentProjects||[]).find(p=>String(p.id)===String(id))?.name || '-'; }
function contactName(id) { return (currentContacts||[]).find(c=>String(c.id)===String(id))?.name || '-'; }
function boqItems(projId) { return ((currentProjects||[]).find(p=>String(p.id)===String(projId))?.boq_items)||[]; }

// حساب إجمالي المستخلصات السابقة لعقد معين
function prevAbstractTotal(contractId, currentAbstractId, store) {
  return (store||[])
    .filter(a => String(a.contract_id)===String(contractId) && String(a.id)!==String(currentAbstractId) && a.status!=='cancelled')
    .reduce((s,a) => s + (parseFloat(a.net_value)||0), 0);
}

// ============================================================
// CLIENT CONTRACTS (عقود العملاء)
// ============================================================
window.renderClientContracts = function() {
  const tbody = document.getElementById('client-contracts-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  const pfilt = document.getElementById('cc-filter-project')?.value || '';
  const sfilt = document.getElementById('cc-filter-status')?.value || 'all';

  let list = (window.allClientContracts||[]).filter(c => {
    if(pfilt && String(c.project_id)!==String(pfilt)) return false;
    if(sfilt!=='all' && c.status!==sfilt) return false;
    return true;
  });

  if(!list.length) { tbody.innerHTML='<tr><td colspan="8" style="text-align:center;padding:20px;color:var(--text-secondary);">لا توجد عقود</td></tr>'; return; }

  list.forEach(c => {
    const totalAbstracts = (window.allClientAbstractsNew||[]).filter(a=>String(a.contract_id)===String(c.id)&&a.status!=='cancelled').reduce((s,a)=>s+(parseFloat(a.net_value)||0),0);
    const remaining = (parseFloat(c.contract_value)||0) - totalAbstracts;
    const statusColor = c.status==='active'?'var(--success)':c.status==='closed'?'var(--text-secondary)':'var(--danger)';
    tbody.innerHTML += `<tr>
      <td><strong>${c.contract_number||'-'}</strong></td>
      <td>${projName(c.project_id)}</td>
      <td>${contactName(c.client_id)}</td>
      <td style="font-weight:bold;">${fmtMoney(c.contract_value)} ج.م</td>
      <td style="color:var(--success);">${fmtMoney(totalAbstracts)} ج.م</td>
      <td style="color:${remaining<0?'var(--danger)':'var(--primary)'}; font-weight:bold;">${fmtMoney(remaining)} ج.م</td>
      <td><span style="background:${statusColor};color:#fff;padding:3px 8px;border-radius:4px;font-size:12px;">${c.status==='active'?'نشط':c.status==='closed'?'مغلق':'معلق'}</span></td>
      <td>
        <button class="action-btn btn-edit" onclick="openClientContractModal(${c.id})">تعديل</button>
        <button class="action-btn" style="background:var(--accent);color:#fff;border:none;" onclick="openClientAbstractModalNew(null,${c.id})">+ مستخلص</button>
        <button class="action-btn btn-danger" onclick="deleteClientContract(${c.id})">حذف</button>
      </td>
    </tr>`;
  });
};

window.openClientContractModal = function(id=null) {
  const isNew = !id;
  const c = id ? (window.allClientContracts||[]).find(x=>String(x.id)===String(id)) : null;

  document.getElementById('cc-modal-title').innerText = isNew ? 'عقد عميل جديد' : `تعديل عقد #${id}`;
  document.getElementById('cc-id').value = id||'';
  document.getElementById('cc-number').value = c?.contract_number||'';
  document.getElementById('cc-date').value = c?.date||new Date().toISOString().split('T')[0];
  document.getElementById('cc-notes').value = c?.notes||'';
  document.getElementById('cc-status').value = c?.status||'active';

  // Populate project select
  const pSel = document.getElementById('cc-project');
  pSel.innerHTML = '<option value="">اختر المشروع...</option>' + (currentProjects||[]).map(p=>`<option value="${p.id}">${p.name}</option>`).join('');
  if(c) pSel.value = c.project_id||'';

  // Populate client select
  const cSel = document.getElementById('cc-client');
  cSel.innerHTML = '<option value="">اختر العميل...</option>' + (currentContacts||[]).map(ct=>`<option value="${ct.id}">${ct.name}</option>`).join('');
  if(c) cSel.value = c.client_id||'';

  // Populate BOQ items
  renderCcBoqTable(c?.project_id||'', c?.boq_items||null);

  document.getElementById('cc-contract-value').value = c?.contract_value||0;
  document.getElementById('cc-deduction-percent').value = c?.deduction_percent||0;
  document.getElementById('cc-retention-percent').value = c?.retention_percent||0;

  showModal('client-contract-modal');
};

window.onCcProjectChange = function() {
  const projId = document.getElementById('cc-project').value;
  if (!projId) { renderCcBoqTable('', []); return; }
  const items = boqItems(projId);
  if (items.length > 0) {
    renderCcBoqTable(projId, JSON.parse(JSON.stringify(items)));
    const total = items.reduce((s,it) => s+(it.qty||0)*(it.price||0), 0);
    if (total > 0) document.getElementById('cc-contract-value').value = total;
  } else {
    renderCcBoqTable(projId, null);
  }
};

function renderCcBoqTable(projId, overrideItems) {
  const tbody = document.getElementById('cc-boq-tbody');
  if(!tbody) return;
  const items = overrideItems || boqItems(projId);
  tbody.innerHTML = '';
  let total = 0;
  items.forEach((it,idx) => {
    const rowTotal = (it.qty||0)*(it.price||0);
    total += rowTotal;
    tbody.innerHTML += `<tr>
      <td><input class="cc-boq-name" type="text" value="${it.name||''}" onchange="updateCcBoq(${idx},'name',this.value)" style="width:100%;"></td>
      <td><input class="cc-boq-unit" type="text" value="${it.unit||''}" onchange="updateCcBoq(${idx},'unit',this.value)" style="width:70px;"></td>
      <td><input class="cc-boq-qty" type="number" value="${it.qty||0}" onchange="updateCcBoq(${idx},'qty',parseFloat(this.value))" style="width:80px;"></td>
      <td><input class="cc-boq-price" type="number" value="${it.price||0}" onchange="updateCcBoq(${idx},'price',parseFloat(this.value))" style="width:100px;"></td>
      <td id="cc-boq-total-${idx}">${rowTotal.toLocaleString('en-US')}</td>
      <td><button class="action-btn btn-delete" onclick="removeCcBoqRow(${idx})">×</button></td>
    </tr>`;
  });
  document.getElementById('cc-boq-grand-total').innerText = total.toLocaleString('en-US');
  window._ccBoqItems = JSON.parse(JSON.stringify(items));
}

window.updateCcBoq = function(idx,field,val) {
  if(!window._ccBoqItems) window._ccBoqItems = [];
  if(!window._ccBoqItems[idx]) window._ccBoqItems[idx] = {};
  window._ccBoqItems[idx][field] = val;
  const rowTotal = (window._ccBoqItems[idx].qty||0)*(window._ccBoqItems[idx].price||0);
  const td = document.getElementById('cc-boq-total-'+idx);
  if(td) td.innerText = rowTotal.toLocaleString('en-US');
  const grand = (window._ccBoqItems||[]).reduce((s,it)=>s+(it.qty||0)*(it.price||0),0);
  document.getElementById('cc-boq-grand-total').innerText = grand.toLocaleString('en-US');
};

window.removeCcBoqRow = function(idx) {
  if(!window._ccBoqItems) return;
  window._ccBoqItems.splice(idx,1);
  renderCcBoqTable('', window._ccBoqItems);
};

window.addCcBoqRow = function() {
  if(!window._ccBoqItems) window._ccBoqItems = [];
  window._ccBoqItems.push({name:'',unit:'',qty:1,price:0});
  renderCcBoqTable('', window._ccBoqItems);
};

window.importBoqFromProject = function() {
  const projId = document.getElementById('cc-project').value;
  if(!projId) { alert('اختر المشروع أولاً'); return; }
  const items = boqItems(projId);
  if(!items.length) { alert('المشروع لا يحتوي على بنود مقايسة'); return; }
  renderCcBoqTable(projId, JSON.parse(JSON.stringify(items)));
  alert('تم استيراد ' + items.length + ' بند من مقايسة المشروع');
};

window.saveClientContract = async function() {
  const id = document.getElementById('cc-id').value;
  const projId = document.getElementById('cc-project').value;
  const clientId = document.getElementById('cc-client').value;
  if(!projId||!clientId) { alert('يرجى اختيار المشروع والعميل'); return; }

  const boqTotal = (window._ccBoqItems||[]).reduce((s,it)=>s+(it.qty||0)*(it.price||0),0);
  const contractValue = parseFloat(document.getElementById('cc-contract-value').value)||boqTotal;

  const obj = {
    contract_number: document.getElementById('cc-number').value||('CC-'+Date.now()),
    date: document.getElementById('cc-date').value,
    project_id: parseInt(projId),
    client_id: parseInt(clientId),
    contract_value: contractValue,
    boq_items: window._ccBoqItems||[],
    deduction_percent: parseFloat(document.getElementById('cc-deduction-percent').value)||0,
    retention_percent: parseFloat(document.getElementById('cc-retention-percent').value)||0,
    notes: document.getElementById('cc-notes').value,
    status: document.getElementById('cc-status').value,
    created_by: currentUser?.username||'نظام'
  };

  try {
    if(id) {
      obj.id = parseInt(id);
      await window.DB.update('client_contracts', obj);
    } else {
      obj.id = Date.now();
      await window.DB.add('client_contracts', obj);
    }
    window.allClientContracts = await window.DB.getAll('client_contracts')||[];
    closeModal('client-contract-modal');
    renderClientContracts();
    alert('تم الحفظ بنجاح');
  } catch(e) { alert('خطأ: '+e.message); }
};

window.deleteClientContract = async function(id) {
  if(!confirm('حذف العقد وجميع مستخلصاته؟')) return;
  await window.DB.remove('client_contracts', id);
  window.allClientContracts = await window.DB.getAll('client_contracts')||[];
  renderClientContracts();
};

// ============================================================
// CLIENT ABSTRACTS (مستخلصات العملاء)
// ============================================================
window.renderClientAbstractsNew = function() {
  const tbody = document.getElementById('ca-new-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  const pfilt = document.getElementById('ca-filter-project')?.value||'';
  const sfilt = document.getElementById('ca-filter-status')?.value||'all';

  let list = (window.allClientAbstractsNew||[]).filter(a=>{
    if(pfilt && String(a.project_id)!==String(pfilt)) return false;
    if(sfilt!=='all' && a.status!==sfilt) return false;
    return true;
  }).sort((a,b)=>new Date(b.date)-new Date(a.date));

  if(!list.length){ tbody.innerHTML='<tr><td colspan="9" style="text-align:center;padding:20px;color:var(--text-secondary);">لا توجد مستخلصات</td></tr>'; return; }

  list.forEach(a=>{
    const contract = (window.allClientContracts||[]).find(c=>String(c.id)===String(a.contract_id));
    const statusColor = a.status==='approved'?'var(--success)':a.status==='paid'?'var(--primary)':a.status==='cancelled'?'var(--danger)':'var(--secondary)';
    const statusLabel = {draft:'مسودة',approved:'معتمد',paid:'مدفوع',cancelled:'ملغي'}[a.status]||a.status;
    tbody.innerHTML += `<tr>
      <td><strong>${a.abstract_number||('#'+a.id)}</strong></td>
      <td>${new Date(a.date).toLocaleDateString('ar-EG')}</td>
      <td>${projName(a.project_id)}</td>
      <td>${contract?.contract_number||'-'}</td>
      <td>${fmtMoney(a.current_value)} ج.م</td>
      <td style="color:var(--text-secondary);">${fmtMoney(a.deduction_value)} ج.م</td>
      <td style="font-weight:bold;color:var(--success);">${fmtMoney(a.net_value)} ج.م</td>
      <td><span style="background:${statusColor};color:#fff;padding:3px 8px;border-radius:4px;font-size:12px;">${statusLabel}</span></td>
      <td>
        <button class="action-btn btn-edit" onclick="openClientAbstractModalNew(${a.id})" ${a.status!=='draft'?'style="opacity:0.5;"':''}>تعديل</button>
        <button class="action-btn" onclick="window.printAbstractToPDF(${a.id}, 'ca_new')" 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>
        ${a.status==='draft'?`<button class="action-btn" style="background:var(--success);color:#fff;border:none;" onclick="approveClientAbstractNew(${a.id})">اعتماد</button>`:''}
        ${a.status==='approved'?`<button class="action-btn" style="background:var(--primary);color:#fff;border:none;" onclick="payClientAbstractNew(${a.id})">سند قبض</button>`:''}
        <button class="action-btn btn-danger" onclick="deleteClientAbstractNew(${a.id})" ${a.status!=='draft'?'style="opacity:0.5;"':''}>حذف</button>
      </td>
    </tr>`;
  });
};

window.openClientAbstractModalNew = async function(id=null, contractIdPreset=null) {
  // تحميل البيانات من DB لو مش موجودة
  if (!window.allClientContracts || !window.allClientContracts.length) {
    try { window.allClientContracts = await window.DB.getAll('client_contracts')||[]; } catch(e) {}
  }
  if (!window.allClientAbstractsNew || !window.allClientAbstractsNew.length) {
    try { window.allClientAbstractsNew = await window.DB.getAll('client_abstracts_new')||[]; } catch(e) {}
  }

  const a = id ? (window.allClientAbstractsNew||[]).find(x=>String(x.id)===String(id)) : null;
  document.getElementById('ca-new-modal-title').innerText = id ? `تعديل مستخلص #${id}` : 'مستخلص عميل جديد';
  document.getElementById('ca-new-id').value = id||'';
  document.getElementById('ca-new-date').value = a?.date||new Date().toISOString().split('T')[0];
  document.getElementById('ca-new-notes').value = a?.notes||'';

  // contracts select - بيجيب العقود مع اسم العميل
  const cSel = document.getElementById('ca-new-contract');
  cSel.innerHTML = '<option value="">اختر العقد...</option>' + (window.allClientContracts||[]).map(c=>{
    const clientN = (currentContacts||[]).find(ct=>String(ct.id)===String(c.client_id))?.name || c.client_name || '';
    return `<option value="${c.id}">${c.contract_number||'#'+c.id} — ${projName(c.project_id)} — ${clientN}</option>`;
  }).join('');
  if(a) cSel.value = a.contract_id||'';
  else if(contractIdPreset) { cSel.value = contractIdPreset; }

  onCaContractChange(a);
  showModal('ca-new-modal');
};

window.onCaContractChange = function(existingAbstract=null) {
  const contractId = document.getElementById('ca-new-contract').value;
  const contract = (window.allClientContracts||[]).find(c=>String(c.id)===String(contractId));
  if(!contract) { document.getElementById('ca-new-boq-section').style.display='none'; return; }

  document.getElementById('ca-new-boq-section').style.display='block';
  document.getElementById('ca-new-deduction-percent').value = existingAbstract?.deduction_percent ?? contract.deduction_percent ?? 0;
  document.getElementById('ca-new-retention-percent').value = existingAbstract?.retention_percent ?? contract.retention_percent ?? 0;

  const tbody = document.getElementById('ca-new-boq-tbody');
  tbody.innerHTML = '';
  const boq = contract.boq_items||[];
  const prevTotal = prevAbstractTotal(contractId, existingAbstract?.id, window.allClientAbstractsNew);

  let grandCurrent = 0;
  boq.forEach((it,idx)=>{
    const prevQty   = existingAbstract?.boq_lines?.[idx]?.prev_qty   ?? 0;
    const currQty   = existingAbstract?.boq_lines?.[idx]?.curr_qty   ?? 0;
    const lineTotal = currQty * (it.price||0);
    grandCurrent += lineTotal;
    tbody.innerHTML += `<tr>
      <td>${it.name||'-'}</td>
      <td>${it.unit||'-'}</td>
      <td>${it.qty||0}</td>
      <td>${fmtMoney(it.price)}</td>
      <td><input type="number" class="ca-prev-qty" value="${prevQty}" readonly style="width:80px;background:rgba(0,0,0,0.1);"></td>
      <td><input type="number" class="ca-curr-qty" data-idx="${idx}" data-price="${it.price||0}" value="${currQty}" min="0" oninput="recalcCaLine(this)" style="width:80px;"></td>
      <td class="ca-line-total" id="ca-lt-${idx}">${fmtMoney(lineTotal)}</td>
    </tr>`;
  });

  window._caAbstractPrevTotal = prevTotal;
  document.getElementById('ca-new-prev-value').value = fmtMoney(prevTotal);
  document.getElementById('ca-new-current-value').value = fmtMoney(grandCurrent);
  recalcCaTotals();
};

window.recalcCaLine = function(input) {
  const idx   = input.dataset.idx;
  const price = parseFloat(input.dataset.price)||0;
  const qty   = parseFloat(input.value)||0;
  const total = qty*price;
  const td = document.getElementById('ca-lt-'+idx);
  if(td) td.innerText = fmtMoney(total);
  let grand = 0;
  document.querySelectorAll('.ca-curr-qty').forEach(inp=>{
    grand += (parseFloat(inp.value)||0)*(parseFloat(inp.dataset.price)||0);
  });
  document.getElementById('ca-new-current-value').value = fmtMoney(grand);
  recalcCaTotals();
};

window.recalcCaTotals = function() {
  const curr = parseFloat(document.getElementById('ca-new-current-value').value.replace(/,/g,''))||0;
  const ded  = parseFloat(document.getElementById('ca-new-deduction-percent').value)||0;
  const ret  = parseFloat(document.getElementById('ca-new-retention-percent').value)||0;
  const dedVal = curr * ded/100;
  const retVal = curr * ret/100;
  const net    = curr - dedVal - retVal;
  document.getElementById('ca-new-deduction-value').innerText  = fmtMoney(dedVal)+' ج.م';
  document.getElementById('ca-new-retention-value').innerText  = fmtMoney(retVal)+' ج.م';
  document.getElementById('ca-new-net-value').innerText        = fmtMoney(net)+' ج.م';
};

window.saveClientAbstractNew = async function() {
  const id         = document.getElementById('ca-new-id')?.value||'';
  const contractId = document.getElementById('ca-new-contract')?.value||'';

  if (!window.allClientContracts || !window.allClientContracts.length) {
    try { window.allClientContracts = await window.DB.getAll('client_contracts')||[]; } catch(e) {}
  }
  const contract = (window.allClientContracts||[]).find(c=>String(c.id)===String(contractId));
  if(!contractId||!contract) { alert('يرجى اختيار العقد أولاً'); return; }

  const currCaEl = document.getElementById('ca-new-current-value');
  const curr    = parseFloat((currCaEl?.value||'0').replace(/,/g,''))||0;
  const dedPct  = parseFloat(document.getElementById('ca-new-deduction-percent')?.value||0)||0;
  const retPct  = parseFloat(document.getElementById('ca-new-retention-percent')?.value||0)||0;
  const dedVal  = curr*dedPct/100;
  const retVal  = curr*retPct/100;
  const net     = curr - dedVal - retVal;
  const prevVal = window._caAbstractPrevTotal||0;

  // Collect BOQ lines
  const boqLines = [];
  document.querySelectorAll('.ca-curr-qty').forEach(inp=>{
    boqLines.push({ curr_qty: parseFloat(inp.value)||0 });
  });
  document.querySelectorAll('.ca-prev-qty').forEach((inp,i)=>{
    if(boqLines[i]) boqLines[i].prev_qty = parseFloat(inp.value)||0;
  });

  const obj = {
    abstract_number: id ? (window.allClientAbstractsNew.find(a=>String(a.id)===String(id))?.abstract_number||('CA-'+Date.now())) : ('CA-'+Date.now()),
    date: document.getElementById('ca-new-date').value,
    contract_id: parseInt(contractId),
    project_id: contract.project_id,
    client_id: contract.client_id,
    previous_value: prevVal,
    current_value: curr,
    total_value: prevVal + curr,
    deduction_percent: dedPct,
    retention_percent: retPct,
    deduction_value: dedVal,
    retention_value: retVal,
    net_value: net,
    boq_lines: boqLines,
    notes: document.getElementById('ca-new-notes').value,
    status: 'draft',
    created_by: currentUser?.username||'نظام'
  };

  try {
    if(id) {
      obj.id = parseInt(id);
      obj.status = (window.allClientAbstractsNew.find(a=>String(a.id)===String(id))?.status)||'draft';
      await window.DB.update('client_abstracts_new', obj);
    } else {
      obj.id = Date.now();
      await window.DB.add('client_abstracts_new', obj);
    }
    window.allClientAbstractsNew = await window.DB.getAll('client_abstracts_new')||[];
    closeModal('ca-new-modal');
    renderClientAbstractsNew();
    alert('تم الحفظ بنجاح');
  } catch(e) { alert('خطأ: '+e.message); }
};

window.approveClientAbstractNew = async function(id) {
  if(!confirm('اعتماد المستخلص؟ لن يمكن تعديله بعد ذلك.')) return;
  const a = (window.allClientAbstractsNew||[]).find(x=>String(x.id)===String(id));
  if(!a) return;
  a.status = 'approved';
  await window.DB.update('client_abstracts_new', a);
  window.allClientAbstractsNew = await window.DB.getAll('client_abstracts_new')||[];
  renderClientAbstractsNew();
  alert('تم الاعتماد');
};

window.payClientAbstractNew = function(id) {
  const a = (window.allClientAbstractsNew||[]).find(x=>String(x.id)===String(id));
  if(!a) return;
  if(typeof showModal === 'function') {
    document.getElementById('receipt-linked-invoice').value = 'ca-new-'+a.id;
    document.getElementById('receipt-amount').value = a.net_value;
    const ct = (currentContacts||[]).find(c=>String(c.id)===String(a.client_id));
    document.getElementById('receipt-party-name').value = ct?.name||'';
    showModal('receipt-modal');
  }
};

window.deleteClientAbstractNew = async function(id) {
  const a = (window.allClientAbstractsNew||[]).find(x=>String(x.id)===String(id));
  if(a && a.status!=='draft') { alert('لا يمكن حذف مستخلص معتمد أو مدفوع'); return; }
  if(!confirm('حذف المستخلص؟')) return;
  await window.DB.remove('client_abstracts_new', id);
  window.allClientAbstractsNew = await window.DB.getAll('client_abstracts_new')||[];
  renderClientAbstractsNew();
};

// ============================================================
// SUBCONTRACTS (عقود مقاولي الباطن)
// ============================================================
window.renderSubContracts = function() {
  const tbody = document.getElementById('sc-new-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  const pfilt = document.getElementById('sc-filter-project')?.value||'';

  let list = (window.allSubContracts||[]).filter(c=>{
    if(pfilt && String(c.project_id)!==String(pfilt)) return false;
    return true;
  });

  if(!list.length){ tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px;color:var(--text-secondary);">لا توجد عقود مقاولي باطن</td></tr>'; return; }

  list.forEach(c=>{
    const totalAbstracts = (window.allSubAbstracts||[]).filter(a=>String(a.contract_id)===String(c.id)&&a.status!=='cancelled').reduce((s,a)=>s+(parseFloat(a.net_value)||0),0);
    const remaining = (parseFloat(c.contract_value)||0) - totalAbstracts;
    tbody.innerHTML += `<tr>
      <td><strong>${c.contract_number||'-'}</strong></td>
      <td>${projName(c.project_id)}</td>
      <td>${contactName(c.subcontractor_id)}</td>
      <td style="font-weight:bold;">${fmtMoney(c.contract_value)} ج.م</td>
      <td style="color:var(--success);">${fmtMoney(totalAbstracts)} ج.م</td>
      <td style="color:${remaining<0?'var(--danger)':'var(--primary)'}; font-weight:bold;">${fmtMoney(remaining)} ج.م</td>
      <td>
        <button class="action-btn btn-edit" onclick="openSubContractModal(${c.id})">تعديل</button>
        <button class="action-btn" style="background:var(--accent);color:#fff;border:none;" onclick="openSubAbstractModal(null,${c.id})">+ مستخلص</button>
        <button class="action-btn btn-danger" onclick="deleteSubContract(${c.id})">حذف</button>
      </td>
    </tr>`;
  });
};

window.openSubContractModal = function(id=null) {
  const isNew = !id;
  const c = id ? (window.allSubContracts||[]).find(x=>String(x.id)===String(id)) : null;
  document.getElementById('sc-new-modal-title').innerText = isNew ? 'عقد مقاول باطن جديد' : `تعديل عقد #${id}`;
  document.getElementById('sc-new-id').value = id||'';
  document.getElementById('sc-new-number').value = c?.contract_number||'';
  document.getElementById('sc-new-date').value = c?.date||new Date().toISOString().split('T')[0];
  document.getElementById('sc-new-notes').value = c?.notes||'';

  const pSel = document.getElementById('sc-new-project');
  pSel.innerHTML = '<option value="">اختر المشروع...</option>'+(currentProjects||[]).map(p=>`<option value="${p.id}">${p.name}</option>`).join('');
  if(c) pSel.value = c.project_id||'';

  const sSel = document.getElementById('sc-new-subcontractor');
  sSel.innerHTML = '<option value="">اختر المقاول...</option>'+(currentContacts||[]).map(ct=>`<option value="${ct.id}">${ct.name}</option>`).join('');
  if(c) sSel.value = c.subcontractor_id||'';

  renderScBoqTable(c?.project_id||'', c?.boq_items||null);
  document.getElementById('sc-new-contract-value').value = c?.contract_value||0;
  document.getElementById('sc-new-deduction-percent').value = c?.deduction_percent||0;
  document.getElementById('sc-new-retention-percent').value = c?.retention_percent||0;
  showModal('sc-new-modal');
};

window.onScProjectChange = function() {
  const projId = document.getElementById('sc-new-project').value;
  if (!projId) { renderScBoqTable('', []); return; }
  // استيراد بنود المقايسة تلقائياً من المشروع
  const items = boqItems(projId);
  if (items.length > 0) {
    renderScBoqTable(projId, JSON.parse(JSON.stringify(items)));
    // تحديث قيمة العقد تلقائياً
    const total = items.reduce((s,it) => s+(it.qty||0)*(it.price||0), 0);
    if (total > 0) document.getElementById('sc-new-contract-value').value = total;
  } else {
    renderScBoqTable(projId, null);
  }
};

function renderScBoqTable(projId, overrideItems) {
  const tbody = document.getElementById('sc-new-boq-tbody');
  if(!tbody) return;
  const items = overrideItems || boqItems(projId);
  tbody.innerHTML = '';
  let total = 0;
  items.forEach((it,idx)=>{
    const rowTotal = (it.qty||0)*(it.price||0);
    total += rowTotal;
    tbody.innerHTML += `<tr>
      <td><input type="text" value="${it.name||''}" onchange="updateScBoq(${idx},'name',this.value)" style="width:100%;"></td>
      <td><input type="text" value="${it.unit||''}" onchange="updateScBoq(${idx},'unit',this.value)" style="width:70px;"></td>
      <td><input type="number" value="${it.qty||0}" onchange="updateScBoq(${idx},'qty',parseFloat(this.value))" style="width:80px;"></td>
      <td><input type="number" value="${it.price||0}" onchange="updateScBoq(${idx},'price',parseFloat(this.value))" style="width:100px;"></td>
      <td id="sc-boq-total-${idx}">${rowTotal.toLocaleString('en-US')}</td>
      <td><button class="action-btn btn-delete" onclick="removeScBoqRow(${idx})">×</button></td>
    </tr>`;
  });
  document.getElementById('sc-new-boq-grand-total').innerText = total.toLocaleString('en-US');
  window._scBoqItems = JSON.parse(JSON.stringify(items));
}

window.updateScBoq = function(idx,field,val) {
  if(!window._scBoqItems) window._scBoqItems = [];
  if(!window._scBoqItems[idx]) window._scBoqItems[idx]={};
  window._scBoqItems[idx][field] = val;
  const rowTotal = (window._scBoqItems[idx].qty||0)*(window._scBoqItems[idx].price||0);
  const td = document.getElementById('sc-boq-total-'+idx);
  if(td) td.innerText = rowTotal.toLocaleString('en-US');
  const grand = (window._scBoqItems||[]).reduce((s,it)=>s+(it.qty||0)*(it.price||0),0);
  document.getElementById('sc-new-boq-grand-total').innerText = grand.toLocaleString('en-US');
};

window.removeScBoqRow = function(idx) {
  if(!window._scBoqItems) return;
  window._scBoqItems.splice(idx,1);
  renderScBoqTable('', window._scBoqItems);
};

window.addScBoqRow = function() {
  if(!window._scBoqItems) window._scBoqItems = [];
  window._scBoqItems.push({name:'',unit:'',qty:1,price:0});
  renderScBoqTable('', window._scBoqItems);
};

window.importScBoqFromProject = function() {
  const projId = document.getElementById('sc-new-project').value;
  if(!projId) { alert('اختر المشروع أولاً'); return; }
  const items = boqItems(projId);
  if(!items.length) { alert('المشروع لا يحتوي على بنود مقايسة'); return; }
  renderScBoqTable(projId, JSON.parse(JSON.stringify(items)));
  alert('تم استيراد '+items.length+' بند من مقايسة المشروع');
};

window.saveSubContract = async function() {
  const id = document.getElementById('sc-new-id').value;
  const projId = document.getElementById('sc-new-project').value;
  const subId = document.getElementById('sc-new-subcontractor').value;
  if(!projId||!subId) { alert('يرجى اختيار المشروع والمقاول'); return; }

  const boqTotal = (window._scBoqItems||[]).reduce((s,it)=>s+(it.qty||0)*(it.price||0),0);
  const contractValue = parseFloat(document.getElementById('sc-new-contract-value').value)||boqTotal;

  const obj = {
    contract_number: document.getElementById('sc-new-number').value||('SC-'+Date.now()),
    date: document.getElementById('sc-new-date').value,
    project_id: parseInt(projId),
    subcontractor_id: parseInt(subId),
    contract_value: contractValue,
    boq_items: window._scBoqItems||[],
    deduction_percent: parseFloat(document.getElementById('sc-new-deduction-percent').value)||0,
    retention_percent: parseFloat(document.getElementById('sc-new-retention-percent').value)||0,
    notes: document.getElementById('sc-new-notes').value,
    created_by: currentUser?.username||'نظام'
  };

  try {
    if(id) { obj.id=parseInt(id); await window.DB.update('sub_contracts',obj); }
    else { obj.id=Date.now(); await window.DB.add('sub_contracts',obj); }
    window.allSubContracts = await window.DB.getAll('sub_contracts')||[];
    closeModal('sc-new-modal');
    renderSubContracts();
    alert('تم الحفظ بنجاح');
  } catch(e) { alert('خطأ: '+e.message); }
};

window.deleteSubContract = async function(id) {
  if(!confirm('حذف العقد وجميع مستخلصاته؟')) return;
  await window.DB.remove('sub_contracts', id);
  window.allSubContracts = await window.DB.getAll('sub_contracts')||[];
  renderSubContracts();
};

// ============================================================
// SUB ABSTRACTS (مستخلصات مقاولي الباطن)
// ============================================================
window.renderSubAbstracts = function() {
  const tbody = document.getElementById('sa-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  const pfilt = document.getElementById('sa-filter-project')?.value||'';
  const sfilt = document.getElementById('sa-filter-status')?.value||'all';

  let list = (window.allSubAbstracts||[]).filter(a=>{
    if(pfilt && String(a.project_id)!==String(pfilt)) return false;
    if(sfilt!=='all' && a.status!==sfilt) return false;
    return true;
  }).sort((a,b)=>new Date(b.date)-new Date(a.date));

  if(!list.length){ tbody.innerHTML='<tr><td colspan="9" style="text-align:center;padding:20px;color:var(--text-secondary);">لا توجد مستخلصات</td></tr>'; return; }

  list.forEach(a=>{
    const contract = (window.allSubContracts||[]).find(c=>String(c.id)===String(a.contract_id));
    const statusColor = a.status==='approved'?'var(--success)':a.status==='paid'?'var(--primary)':a.status==='cancelled'?'var(--danger)':'var(--secondary)';
    const statusLabel = {draft:'مسودة',approved:'معتمد',paid:'مدفوع',cancelled:'ملغي'}[a.status]||a.status;
    tbody.innerHTML += `<tr>
      <td><strong>${a.abstract_number||('#'+a.id)}</strong></td>
      <td>${new Date(a.date).toLocaleDateString('ar-EG')}</td>
      <td>${projName(a.project_id)}</td>
      <td>${contract?.contract_number||'-'}</td>
      <td>${contactName(a.subcontractor_id)}</td>
      <td>${fmtMoney(a.current_value)} ج.م</td>
      <td style="font-weight:bold;color:var(--success);">${fmtMoney(a.net_value)} ج.م</td>
      <td><span style="background:${statusColor};color:#fff;padding:3px 8px;border-radius:4px;font-size:12px;">${statusLabel}</span></td>
      <td>
        <button class="action-btn btn-edit" onclick="openSubAbstractModal(${a.id})" ${a.status!=='draft'?'style="opacity:0.5;"':''}>تعديل</button>
        <button class="action-btn" onclick="window.printAbstractToPDF(${a.id}, 'sa_new')" 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>
        ${a.status==='draft'?`<button class="action-btn" style="background:var(--success);color:#fff;border:none;" onclick="approveSubAbstract(${a.id})">اعتماد</button>`:''}
        ${a.status==='approved'?`<button class="action-btn" style="background:var(--primary);color:#fff;border:none;" onclick="paySubAbstract(${a.id})">سند دفع</button>`:''}
        <button class="action-btn btn-danger" onclick="deleteSubAbstract(${a.id})" ${a.status!=='draft'?'style="opacity:0.5;"':''}>حذف</button>
      </td>
    </tr>`;
  });
};

window.openSubAbstractModal = async function(id=null, contractIdPreset=null) {
  // تحميل البيانات من DB لو مش موجودة
  if (!window.allSubContracts || !window.allSubContracts.length) {
    try { window.allSubContracts = await window.DB.getAll('sub_contracts')||[]; } catch(e) {}
  }
  if (!window.allSubAbstracts || !window.allSubAbstracts.length) {
    try { window.allSubAbstracts = await window.DB.getAll('sub_abstracts')||[]; } catch(e) {}
  }

  const a = id ? (window.allSubAbstracts||[]).find(x=>String(x.id)===String(id)) : null;
  document.getElementById('sa-modal-title').innerText = id ? `تعديل مستخلص مقاول باطن #${id}` : 'مستخلص مقاول باطن جديد';
  document.getElementById('sa-id').value = id||'';
  document.getElementById('sa-date').value = a?.date||new Date().toISOString().split('T')[0];
  document.getElementById('sa-notes').value = a?.notes||'';

  const cSel = document.getElementById('sa-contract');
  cSel.innerHTML = '<option value="">اختر العقد...</option>'+(window.allSubContracts||[]).map(c=>`<option value="${c.id}">${c.contract_number||'#'+c.id} — ${projName(c.project_id)}</option>`).join('');
  if(a) cSel.value = a.contract_id||'';
  else if(contractIdPreset) { cSel.value = contractIdPreset; }

  onSaContractChange(a);
  showModal('sa-modal');
};

window.onSaContractChange = function(existingAbstract=null) {
  // جلب contractId من الـ select أو من المستخلص المفتوح للتعديل
  const contractId = document.getElementById('sa-contract').value || existingAbstract?.contract_id;
  const contract = (window.allSubContracts||[]).find(c=>String(c.id)===String(contractId));
  if(!contract) { document.getElementById('sa-boq-section').style.display='none'; return; }
  // تحديث قيمة الـ select لو كانت فاضية
  if (!document.getElementById('sa-contract').value && contractId) {
    document.getElementById('sa-contract').value = contractId;
  }

  document.getElementById('sa-boq-section').style.display='block';
  document.getElementById('sa-deduction-percent').value = existingAbstract?.deduction_percent ?? contract.deduction_percent ?? 0;
  document.getElementById('sa-retention-percent').value = existingAbstract?.retention_percent ?? contract.retention_percent ?? 0;

  const tbody = document.getElementById('sa-boq-tbody');
  tbody.innerHTML = '';
  const boq = contract.boq_items||[];
  const prevTotal = prevAbstractTotal(contractId, existingAbstract?.id, window.allSubAbstracts);

  let grandCurrent = 0;
  boq.forEach((it,idx)=>{
    const currQty = existingAbstract?.boq_lines?.[idx]?.curr_qty ?? 0;
    const lineTotal = currQty*(it.price||0);
    grandCurrent += lineTotal;
    tbody.innerHTML += `<tr>
      <td>${it.name||'-'}</td>
      <td>${it.unit||'-'}</td>
      <td>${it.qty||0}</td>
      <td>${fmtMoney(it.price)}</td>
      <td><input type="number" class="sa-curr-qty" data-idx="${idx}" data-price="${it.price||0}" value="${currQty}" min="0" oninput="recalcSaLine(this)" style="width:80px;"></td>
      <td class="sa-line-total" id="sa-lt-${idx}">${fmtMoney(lineTotal)}</td>
    </tr>`;
  });

  window._saAbstractPrevTotal = prevTotal;
  document.getElementById('sa-prev-value').value = fmtMoney(prevTotal);
  document.getElementById('sa-current-value').value = fmtMoney(grandCurrent);
  recalcSaTotals();
};

window.recalcSaLine = function(input) {
  const idx = input.dataset.idx;
  const price = parseFloat(input.dataset.price)||0;
  const qty = parseFloat(input.value)||0;
  const total = qty*price;
  const td = document.getElementById('sa-lt-'+idx);
  if(td) td.innerText = fmtMoney(total);
  let grand = 0;
  document.querySelectorAll('.sa-curr-qty').forEach(inp=>{
    grand += (parseFloat(inp.value)||0)*(parseFloat(inp.dataset.price)||0);
  });
  document.getElementById('sa-current-value').value = fmtMoney(grand);
  recalcSaTotals();
};

window.recalcSaTotals = function() {
  const curr = parseFloat(document.getElementById('sa-current-value').value.replace(/,/g,''))||0;
  const ded = parseFloat(document.getElementById('sa-deduction-percent').value)||0;
  const ret = parseFloat(document.getElementById('sa-retention-percent').value)||0;
  const dedVal = curr*ded/100;
  const retVal = curr*ret/100;
  const net = curr - dedVal - retVal;
  document.getElementById('sa-deduction-value').innerText = fmtMoney(dedVal)+' ج.م';
  document.getElementById('sa-retention-value').innerText = fmtMoney(retVal)+' ج.م';
  document.getElementById('sa-net-value').innerText = fmtMoney(net)+' ج.م';
};

window.saveSubAbstract = async function() {
  const id = document.getElementById('sa-id')?.value||'';
  const contractId = document.getElementById('sa-contract')?.value||'';

  // تحميل العقود من DB لو مش موجودة
  if (!window.allSubContracts || !window.allSubContracts.length) {
    try { window.allSubContracts = await window.DB.getAll('sub_contracts')||[]; } catch(e) {}
  }
  const contract = (window.allSubContracts||[]).find(c=>String(c.id)===String(contractId));
  if(!contractId||!contract) { alert('يرجى اختيار العقد أولاً'); return; }

  const currEl = document.getElementById('sa-current-value');
  const curr = parseFloat((currEl?.value||'0').replace(/,/g,''))||0;
  const dedPct = parseFloat(document.getElementById('sa-deduction-percent')?.value||0)||0;
  const retPct = parseFloat(document.getElementById('sa-retention-percent')?.value||0)||0;
  const dedVal = curr*dedPct/100;
  const retVal = curr*retPct/100;
  const net = curr - dedVal - retVal;
  const prevVal = window._saAbstractPrevTotal||0;

  const boqLines = [];
  document.querySelectorAll('.sa-curr-qty').forEach(inp=>{
    boqLines.push({ curr_qty: parseFloat(inp.value)||0 });
  });

  const obj = {
    abstract_number: id ? (window.allSubAbstracts.find(a=>String(a.id)===String(id))?.abstract_number||('SA-'+Date.now())) : ('SA-'+Date.now()),
    date: document.getElementById('sa-date').value,
    contract_id: parseInt(contractId),
    project_id: contract.project_id,
    subcontractor_id: contract.subcontractor_id,
    previous_value: prevVal,
    current_value: curr,
    total_value: prevVal+curr,
    deduction_percent: dedPct,
    retention_percent: retPct,
    deduction_value: dedVal,
    retention_value: retVal,
    net_value: net,
    boq_lines: boqLines,
    notes: document.getElementById('sa-notes').value,
    status: 'draft',
    created_by: currentUser?.username||'نظام'
  };

  try {
    if(id) {
      obj.id = parseInt(id);
      obj.status = (window.allSubAbstracts.find(a=>String(a.id)===String(id))?.status)||'draft';
      await window.DB.update('sub_abstracts', obj);
    } else {
      obj.id = Date.now();
      await window.DB.add('sub_abstracts', obj);
    }
    window.allSubAbstracts = await window.DB.getAll('sub_abstracts')||[];
    closeModal('sa-modal');
    renderSubAbstracts();
    alert('تم الحفظ بنجاح');
  } catch(e) { alert('خطأ: '+e.message); }
};

window.approveSubAbstract = async function(id) {
  if(!confirm('اعتماد المستخلص؟')) return;
  const a = (window.allSubAbstracts||[]).find(x=>String(x.id)===String(id));
  if(!a) return;
  a.status = 'approved';
  await window.DB.update('sub_abstracts', a);
  window.allSubAbstracts = await window.DB.getAll('sub_abstracts')||[];
  renderSubAbstracts();
};

window.paySubAbstract = function(id) {
  const a = (window.allSubAbstracts||[]).find(x=>String(x.id)===String(id));
  if(!a) return;
  if(typeof window.openVoucherModal === 'function') {
    window.openVoucherModal('payment');
    setTimeout(()=>{
      document.getElementById('voucher-linked-invoice').value = 'sa-'+a.id;
      document.getElementById('voucher-amount').value = a.net_value;
      const sc = (window.allSubContracts||[]).find(c=>String(c.id)===String(a.contract_id));
      if(sc) {
        const subc = (currentContacts||[]).find(c=>String(c.id)===String(sc.subcontractor_id));
        if(subc && document.getElementById('voucher-contact')) document.getElementById('voucher-contact').value = subc.id;
      }
    }, 100);
  }
};

window.deleteSubAbstract = async function(id) {
  const a = (window.allSubAbstracts||[]).find(x=>String(x.id)===String(id));
  if(a && a.status!=='draft') { alert('لا يمكن حذف مستخلص معتمد أو مدفوع'); return; }
  if(!confirm('حذف المستخلص؟')) return;
  await window.DB.remove('sub_abstracts', id);
  window.allSubAbstracts = await window.DB.getAll('sub_abstracts')||[];
  renderSubAbstracts();
};

// ============================================================
// Init on page load
// ============================================================
window.addEventListener('load', ()=>{ setTimeout(initContractsAbstracts, 1500); });
