
// Strip old listeners from app_final.js
['btn-save-project'].forEach(id => {
    let oldBtn = document.getElementById(id);
    if (oldBtn) {
        let newBtn = oldBtn.cloneNode(true);
        oldBtn.parentNode.replaceChild(newBtn, oldBtn);
    }
});

window.addProjectBoqRow = function() {
  currentProjectBoqItems.push({ name: '', unit: 'متر', qty: 1, price: 0 });
  renderProjectBoqTable();
};

window.removeProjectBoqRow = function(index) {
  currentProjectBoqItems.splice(index, 1);
  renderProjectBoqTable();
};

window.updateProjectBoqRow = function(index, field, value) {
  currentProjectBoqItems[index][field] = value;
  renderProjectBoqTable();
};

window.removeProjectAttachment = function(index) {
  currentProjectAttachments.splice(index, 1);
  renderProjectAttachments();
};

window.openProjectModal = function(id = null) {
  const isEdit = id !== null;
  document.getElementById('proj-modal-title').innerText = isEdit ? 'تعديل مشروع' : 'إضافة مشروع جديد';
  document.getElementById('edit-project-id').value = id || '';
  if(isEdit) {
    const p = currentProjects.find(x => String(x.id) === String(id));
    document.getElementById('project-name').value = p.name || '';
    if(document.getElementById('project-status')) document.getElementById('project-status').value = p.status || 'مستمر';
    document.getElementById('project-desc').value = p.desc || '';
    document.getElementById('project-client').value = p.client || '';
    document.getElementById('project-client-consultant').value = p.client_consultant || '';
    document.getElementById('project-contractor-consultant').value = p.contractor_consultant || '';
    document.getElementById('project-duration').value = p.duration || '';
    document.getElementById('project-axes').value = p.axes || '';
    currentProjectBoqItems = p.boq_items ? JSON.parse(JSON.stringify(p.boq_items)) : [];
    currentProjectAttachments = p.attachments ? JSON.parse(JSON.stringify(p.attachments)) : [];
  } else {
    document.getElementById('project-name').value = '';
    if(document.getElementById('project-status')) document.getElementById('project-status').value = 'مستمر';
    document.getElementById('project-desc').value = '';
    document.getElementById('project-client').value = '';
    document.getElementById('project-client-consultant').value = '';
    document.getElementById('project-contractor-consultant').value = '';
    document.getElementById('project-duration').value = '';
    document.getElementById('project-axes').value = '';
    currentProjectBoqItems = [];
    currentProjectAttachments = [];
  }
  renderProjectBoqTable();
  renderProjectAttachments();
  showModal('project-modal');
}

window.deleteProject = async function(id) {
  if(isEntityReferenced('project', id)) { alert('لا يمكن حذف المشروع لاستخدامه في صرفيات!'); return; }
  if(confirm('متأكد من الحذف؟')) { await window.DB.remove('projects', id); await loadData(); }
}

window.openProjectDetails = function(id) {
  const p = currentProjects.find(x => String(x.id) === String(id));
  if(!p) return;
  document.getElementById('pd-name').innerText = p.name || '';
  document.getElementById('pd-desc').innerText = p.desc || '';
  document.getElementById('pd-client').innerText = p.client || '-';
  document.getElementById('pd-duration').innerText = p.duration || '-';
  document.getElementById('pd-client-consultant').innerText = p.client_consultant || '-';
  document.getElementById('pd-contractor-consultant').innerText = p.contractor_consultant || '-';
  document.getElementById('pd-axes').innerText = p.axes || '-';
  
  const boqTbody = document.getElementById('pd-boq-tbody');
  boqTbody.innerHTML = '';
  let total = 0;
  if(p.boq_items) {
    (p.boq_items || []).forEach(it => {
      const rowTotal = (it.qty || 0) * (it.price || 0);
      total += rowTotal;
      boqTbody.innerHTML += `<tr><td>${it.name || ''}</td><td>${it.unit || ''}</td><td>${it.qty || 1}</td><td>${it.price || 0}</td><td>${rowTotal.toLocaleString('ar-EG')}</td></tr>`;
    });
  }
  document.getElementById('pd-boq-total').innerText = total.toLocaleString('ar-EG');
  
  const attList = document.getElementById('pd-attachments-list');
  attList.innerHTML = '';
  if(p.attachments && p.attachments.length > 0) {
    (p.attachments || []).forEach(att => {
      attList.innerHTML += `<a href="${att.data}" download="${att.name}" style="color: var(--primary); text-decoration: none; display: block; padding: 5px; background: rgba(0,0,0,0.05); border-radius: 4px; margin-bottom: 5px;"><i class="fas fa-file"></i> ${att.name}</a>`;
    });
  } else {
    attList.innerHTML = '<span style="color:#999; font-size:13px;">لا توجد مرفقات</span>';
  }
  showModal('project-details-modal');
};

document.getElementById('btn-save-project').addEventListener('click', async () => {
  try {
    const getVal = (elId) => { const el = document.getElementById(elId); return el ? el.value : ''; };
    const editIdStr = getVal('edit-project-id');
    const name = getVal('project-name');
    const status = getVal('project-status');
    const desc = getVal('project-desc');
    const client = getVal('project-client');
    const client_consultant = getVal('project-client-consultant');
    const contractor_consultant = getVal('project-contractor-consultant');
    const duration = getVal('project-duration');
    const axes = getVal('project-axes');
    const boq_value = currentProjectBoqItems.reduce((sum, item) => sum + ((item.qty || 0) * (item.price || 0)), 0);

    if(name) { 
      const obj = { 
        name, status, desc, client, client_consultant, contractor_consultant, duration, axes, boq_value,
        boq_items: currentProjectBoqItems, attachments: currentProjectAttachments 
      };
      if(editIdStr) { obj.id = parseInt(editIdStr); await window.DB.update('projects', obj); } 
      else { await window.DB.add('projects', obj); }
      closeModal('project-modal'); await loadData(); 
    } else { alert('أدخل اسم المشروع!'); }
  } catch(e) { alert("خطأ: " + e.message); }
});
