
// 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 || '-';
  const stEl = document.getElementById('pd-status');
  if (stEl) {
    const st = p.status || 'مستمر';
    if (st === 'مستمر' || st === 'active') stEl.innerHTML = '<span style="color:#16a34a; font-weight:bold;">🟢 مستمر (نشط)</span>';
    else if (st === 'متوقف' || st === 'stopped') stEl.innerHTML = '<span style="color:#d97706; font-weight:bold;">⏸️ متوقف (معلق)</span>';
    else stEl.innerHTML = '<span style="color:#64748b; font-weight:bold;">🏁 منتهي (تم التسليم)</span>';
  }
  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); }
});

/* =======================================================================================
   UNIVERSAL PROJECT STATUS PROTECTION ENGINE & ENHANCED TABLE DISPLAY
   ======================================================================================= */

window.toggleProjectStatus = async function(id, newStatus) {
    try {
        const projs = (typeof currentProjects !== 'undefined' ? currentProjects : window.currentProjects || []);
        const p = projs.find(x => String(x.id) === String(id));
        if (!p) return;
        
        const actionLabel = newStatus === 'متوقف' ? 'إيقاف المشروع مؤقتاً (لن يظهر بالقوائم اليومية)' : 
                            newStatus === 'منتهي' ? 'إنهاء المشروع نهائياً وتعيينه كمسلم (يختفي من قوائم الأنشطة)' : 'إعادة تنشيط المشروع وإظهاره بالقوائم';
        if (!confirm(`هل تريد بالتأكيد ${actionLabel}؟`)) return;

        document.body.style.cursor = 'wait';
        p.status = newStatus;
        if (window.DB && typeof window.DB.update === 'function') {
            await window.DB.update('projects', p);
        }
        document.body.style.cursor = 'default';
        
        if (typeof window.loadData === 'function') {
            await window.loadData();
        } else {
            if (typeof renderEnhancedProjectsTable === 'function') renderEnhancedProjectsTable();
            if (typeof window.filterAllProjectSelects === 'function') window.filterAllProjectSelects();
        }
        
        // Brief notification
        const msg = newStatus === 'مستمر' ? '✅ تم تفعيل المشروع واعادته للقوائم بنجاح' : '⏸️ تم تحويل المشروع إلى: ' + newStatus + ' وحجبه من القوائم بنجاح';
        const toast = document.createElement('div');
        toast.style.cssText = "position:fixed; top:20px; right:20px; background:#1e293b; color:#fff; padding:12px 24px; border-radius:8px; z-index:999999; font-weight:bold; box-shadow:0 10px 25px rgba(0,0,0,0.3); border-right:5px solid " + (newStatus==='مستمر'?'#22c55e':'#f97316');
        toast.innerText = msg;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 4500);
    } catch (e) {
        document.body.style.cursor = 'default';
        console.error('Error updating project status:', e);
        alert('حدث خطأ أثناء تعديل حالة المشروع');
    }
};

function renderEnhancedProjectsTable() {
    const tbody = document.getElementById('projects-tbody');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    let projs = (typeof currentProjects !== 'undefined' ? currentProjects : window.currentProjects || []);
    let userProjs = projs;
    if (typeof currentUser !== 'undefined' && currentUser) {
        if (currentUser.role === 'موظف مخصص' && currentUser.allowed_projects) {
            userProjs = projs.filter(p => currentUser.allowed_projects.includes(p.id));
        } else if (currentUser.role === 'أمين مخزن' && currentUser.project_id) {
            userProjs = projs.filter(p => p.id === currentUser.project_id);
        }
    }

    (userProjs || []).forEach(p => {
        let actions = `<button class="action-btn btn-view" onclick="openProjectDetails(${p.id})">🔍 عرض</button> <button class="action-btn btn-view" style="background:#6c757d;" onclick="window.openProjectStatement(${p.id})">كشف حساب</button> `;
        if (typeof currentUser !== 'undefined' && (currentUser.role === 'مدير عام' || (currentUser.allowed_modules && currentUser.allowed_modules.includes('projects')))) {
            actions += `<button class="action-btn btn-edit" onclick="openProjectModal(${p.id})">✏️ تعديل</button> <button class="action-btn btn-delete" onclick="deleteProject(${p.id})">حذف</button>`;
        }
        
        const val = p.boq_value ? (typeof p.boq_value.toLocaleString === 'function' ? p.boq_value.toLocaleString('ar-EG') : p.boq_value) + ' ج.م' : '-';
        const st = p.status || 'مستمر';
        let stBadge = '';
        let nextSt = 'متوقف';
        let btnBg = '#f59e0b';
        let btnText = '⏸️ إيقاف';
        
        if (st === 'مستمر' || st === 'active') {
            stBadge = `<span style="background:#dcfce7; color:#166534; padding:4px 10px; border-radius:12px; font-size:12px; font-weight:bold; border:1px solid #bbf7d0; display:inline-flex; align-items:center; gap:4px;">🟢 مستمر (نشط)</span>`;
            nextSt = 'متوقف';
            btnBg = '#f59e0b';
            btnText = '⏸️ تحويل לمتوقف';
        } else if (st === 'متوقف' || st === 'stopped') {
            stBadge = `<span style="background:#fef3c7; color:#92400e; padding:4px 10px; border-radius:12px; font-size:12px; font-weight:bold; border:1px solid #fde68a; display:inline-flex; align-items:center; gap:4px;">⏸️ متوقف (معلق)</span>`;
            nextSt = 'منتهي';
            btnBg = '#64748b';
            btnText = '🏁 تحويل לمنتهي';
        } else if (st === 'منتهي' || st === 'completed' || st === 'closed') {
            stBadge = `<span style="background:#f1f5f9; color:#475569; padding:4px 10px; border-radius:12px; font-size:12px; font-weight:bold; border:1px solid #cbd5e1; display:inline-flex; align-items:center; gap:4px;">🏁 منتهي (مسلم)</span>`;
            nextSt = 'مستمر';
            btnBg = '#10b981';
            btnText = '🔄 إعادة تنشيط';
        }

        const statusAction = `<button class="action-btn" style="background:${btnBg}; color:#fff; font-size:11px; padding:4px 8px; margin-right:4px; border-radius:6px; font-weight:bold; border:none; cursor:pointer;" onclick="window.toggleProjectStatus(${p.id}, '${nextSt}')" title="تغيير حالة المشروع في المنظومة">${btnText}</button>`;
        
        tbody.innerHTML += `<tr class="proj-enhanced-row" style="${st === 'منتهي' ? 'opacity:0.8; background:#fafafa;' : ''}">
            <td style="font-weight:bold;">${p.name}</td>
            <td>${p.client || '-'}</td>
            <td style="color:var(--primary); font-weight:bold;">${val}</td>
            <td class="proj-status-cell" style="text-align:center;">${stBadge}</td>
            <td style="white-space:nowrap;">${statusAction} ${actions}</td>
        </tr>`;
    });
}

function getClosedProjectsMap() {
    const projs = (typeof currentProjects !== 'undefined' ? currentProjects : window.currentProjects || []);
    const map = new Map();
    projs.forEach(p => {
        if (!p) return;
        const st = (p.status || '').trim();
        if (st === 'متوقف' || st === 'منتهي' || st === 'stopped' || st === 'completed' || st === 'closed') {
            map.set(String(p.id), p);
            map.set('project_' + p.id, p);
            map.set('proj_' + p.id, p);
        }
    });
    return map;
}

function filterProjectSelectElement(sel) {
    if (!sel || sel.tagName !== 'SELECT' || sel.id === 'project-status') return;
    
    const closedMap = getClosedProjectsMap();
    if (closedMap.size === 0) return;

    const selInfo = (sel.id + ' ' + (sel.name || '') + ' ' + (sel.className || '') + ' ' + (sel.dataset && sel.dataset.type ? sel.dataset.type : '')).toLowerCase();
    let isProj = selInfo.includes('proj') || selInfo.includes('sc-project') || selInfo.includes('user-project') || selInfo.includes('batch-target');
    
    if (!isProj && sel.options && sel.options.length > 0) {
        const firstTxt = sel.options[0].text || '';
        if (firstTxt.includes('مشروع') || firstTxt.includes('المشروع') || firstTxt.includes('مشاريع')) {
            isProj = true;
        }
    }
    if (!isProj && sel.options && sel.options.length > 0) {
        for (let i = 0; i < Math.min(5, sel.options.length); i++) {
            if ((sel.options[i].value || '').startsWith('project_')) {
                isProj = true;
                break;
            }
        }
    }

    if (!isProj) return;

    const currentSelectedVal = String(sel.value || '');
    const options = Array.from(sel.options || []);
    
    options.forEach(opt => {
        const val = String(opt.value || '');
        if (!val) return; 
        const closedProj = closedMap.get(val);
        if (closedProj) {
            if (val !== currentSelectedVal) {
                opt.remove();
            } else {
                const tag = closedProj.status === 'متوقف' ? ' [متوقف]' : ' [منتهي]';
                if (!opt.text.includes('[متوقف]') && !opt.text.includes('[منتهي]')) {
                    opt.text = opt.text + tag;
                    opt.style.color = '#ef4444';
                }
            }
        }
    });
}

function filterProjectCheckboxes(root) {
    const closedMap = getClosedProjectsMap();
    if (closedMap.size === 0) return;
    (root.querySelectorAll || document.querySelectorAll).call(root || document, 'input.perm-project, input[data-type="project"]').forEach(chk => {
        const val = String(chk.value || '');
        if (closedMap.has(val)) {
            const label = chk.closest('label') || chk.parentElement;
            if (label && !chk.checked) {
                label.style.display = 'none';
            } else if (label && chk.checked) {
                const closedProj = closedMap.get(val);
                const tag = closedProj.status === 'متوقف' ? ' (متوقف)' : ' (منتهي)';
                if (!label.innerText.includes('متوقف') && !label.innerText.includes('منتهي')) {
                    label.innerHTML = label.innerHTML + `<span style="color:#ef4444;font-size:11px;">${tag}</span>`;
                }
            }
        }
    });
}

window.filterAllProjectSelects = function() {
    document.querySelectorAll('select').forEach(filterProjectSelectElement);
    filterProjectCheckboxes(document);
};

(function initUniversalProjectProtection() {
    const tryTableObs = () => {
        const tbody = document.getElementById('projects-tbody');
        if (tbody && !tbody._projObserved) {
            tbody._projObserved = true;
            const obs = new MutationObserver(() => {
                if (tbody.querySelector('tr:not(.proj-enhanced-row)')) {
                    renderEnhancedProjectsTable();
                }
            });
            obs.observe(tbody, { childList: true });
            if (tbody.querySelector('tr:not(.proj-enhanced-row)')) {
                renderEnhancedProjectsTable();
            }
        } else if (!tbody) {
            setTimeout(tryTableObs, 1000);
        }
    };

    const attachHook = () => {
        if (window.populateDropdowns && !window.populateDropdowns._projProtected) {
            const orig = window.populateDropdowns;
            const protectedFunc = function() {
                const res = orig.apply(this, arguments);
                window.filterAllProjectSelects();
                setTimeout(window.filterAllProjectSelects, 20);
                return res;
            };
            protectedFunc._projProtected = true;
            window.populateDropdowns = protectedFunc;
        }
    };

    const startGlobalObs = () => {
        tryTableObs();
        attachHook();
        
        const globalObserver = new MutationObserver(mutations => {
            let needsFilter = false;
            mutations.forEach(m => {
                if (m.type === 'childList') {
                    if (m.target.tagName === 'SELECT' || (m.target.id && m.target.id.includes('project')) || (m.target.querySelector && m.target.querySelector('select, .perm-project'))) {
                        needsFilter = true;
                    }
                }
            });
            if (needsFilter) {
                window.filterAllProjectSelects();
                attachHook();
            }
        });
        
        if (document.body) {
            globalObserver.observe(document.body, { childList: true, subtree: true });
            window.filterAllProjectSelects();
        } else {
            setTimeout(startGlobalObs, 100);
        }
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', startGlobalObs);
    } else {
        startGlobalObs();
    }
    
    window.addEventListener('load', () => {
        startGlobalObs();
        setTimeout(window.filterAllProjectSelects, 100);
        setTimeout(window.filterAllProjectSelects, 500);
    });
})();

