
// Strip old listeners from app_final.js
['btn-confirm-receipt', 'btn-execute-decision', 'btn-approve-storekeeper'].forEach(id => {
    let oldElem = document.getElementById(id);
    if (oldElem) {
        let newElem = oldElem.cloneNode(true);
        oldElem.parentNode.replaceChild(newElem, oldElem);
    }
});

window.openReceiveModal = function(invoiceId) {
  const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
  document.getElementById('receive-invoice-id').value = invoiceId;
  document.getElementById('receive-info').innerText = `إذن تحويل رقم #${inv.id} من مخزن ${inv.from_warehouse_name}`;
  const tbody = document.getElementById('receive-items-tbody'); tbody.innerHTML = '';
  let newTotal = 0;
  (inv.items || []).forEach((it, idx) => {
    tbody.innerHTML += `<tr><td>${it.item_name}</td><td>${it.qty} ${it.unit}</td><td><input type="number" id="rec-qty-${idx}" min="0" max="${it.qty}" value="${it.qty}"></td></tr>`;
  });
  showModal('receive-modal');
}

window.openDecisionModal = function(invoiceId) {
  const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
  document.getElementById('decision-invoice-id').value = invoiceId;
  document.getElementById('decision-info').innerText = `إذن تحويل #${inv.id} من (${inv.from_warehouse_name}) إلى (${inv.to_warehouse_name})`;
  const tbody = document.getElementById('decision-items-tbody'); tbody.innerHTML = '';
  (inv.items || []).forEach((it) => {
    const diff = it.qty - it.received_qty;
    if (diff > 0) tbody.innerHTML += `<tr><td>${it.item_name}</td><td>${it.qty}</td><td>${it.received_qty}</td><td style="color:var(--danger); font-weight:bold;">${diff}</td></tr>`;
  });
  showModal('decision-modal');
}

window.viewDetails = function(invId) {
  const inv = allInvoices.find(i => String(i.id) === String(invId));
  
  let typeStr = inv.type === 'in' ? 'إضافة/مشتريات' : 
                inv.type === 'out_project' ? 'منصرف لمشروع' : 
                inv.type === 'depreciate_asset' ? 'إهلاك أصل' : 
                inv.type === 'transfer' ? 'تحويل بين مخازن' : 
                inv.type === 'manufacture' ? 'تصنيع' : 
                inv.type === 'opening_balance' ? 'رصيد أول المدة' : inv.type;

  let extraInfo = '';
  if(inv.from_warehouse_name) extraInfo += `<strong>من مخزن:</strong> ${inv.from_warehouse_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if(inv.to_warehouse_name) extraInfo += `<strong>إلى مخزن:</strong> ${inv.to_warehouse_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if(inv.contact_name) extraInfo += `<strong>المورد/المقاول:</strong> ${inv.contact_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if(inv.project_name) extraInfo += `<strong>المشروع:</strong> ${inv.project_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if(inv.driver_name) extraInfo += `<br><strong>السائق:</strong> ${inv.driver_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if(inv.car_number) extraInfo += `<strong>رقم السيارة:</strong> ${inv.car_number}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if(inv.receiver_name) extraInfo += `<strong>المستلم:</strong> ${inv.receiver_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if(inv.user) extraInfo += `<br><strong>بواسطة:</strong> ${inv.user}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if(inv.notes) extraInfo += `<br><strong>ملاحظات:</strong> ${inv.notes}`;

  document.getElementById('details-info').innerHTML = `
    <div style="background: var(--bg); padding: 15px; border-radius: 8px; line-height: 1.8; border: 1px solid var(--border);">
      <strong>رقم المستند:</strong> #${inv.id} &nbsp;&nbsp;|&nbsp;&nbsp; 
      ${inv.doc_no ? `<strong>رقم الإذن اليدوي:</strong> ${inv.doc_no} &nbsp;&nbsp;|&nbsp;&nbsp; ` : ''}
      <strong>التاريخ:</strong> ${new Date(inv.date).toLocaleString('ar-EG')} &nbsp;&nbsp;|&nbsp;&nbsp; 
      <strong>النوع:</strong> <span style="color:var(--primary); font-weight:bold;">${typeStr}</span><br>
      ${extraInfo}
    </div>
  `;
  const tbody = document.getElementById('details-items-tbody'); tbody.innerHTML = '';
  
  if (inv.type === 'manufacture') {
    const prod = currentItems.find(i => i.id === inv.product_id);
    const pName = prod ? prod.name : (inv.produced_item_name || 'غير معروف');
    const pQty = inv.product_qty || inv.produced_qty || 0;
    const pCost = inv.produced_cost || inv.items.reduce((sum, it) => sum + (it.qty * (balancesCache[it.item_id]?.avgCost || 0)), 0);
    tbody.innerHTML += `<tr style="background:rgba(255,255,255,0.05); color:var(--primary); font-weight:bold;"><td colspan="4">المنتج التام: ${pName} | الكمية المنتجة: ${pQty} | التكلفة الإجمالية: ${pCost.toLocaleString()}</td></tr>`;
  }
  
  (inv.items || []).forEach(it => {
 
    let itemName = it.item_name;
    let itemUnit = it.unit;
    if (!itemName && it.item_id) {
       const dbItem = currentItems.find(x => x.id === it.item_id);
       if (dbItem) { itemName = dbItem.name; itemUnit = dbItem.unit || ''; }
    }
    tbody.innerHTML += `<tr><td>${itemName || '-'}</td><td>${it.asset_code || '-'}</td><td>${it.qty} ${itemUnit || ''}</td><td>${it.price || '-'}</td></tr>`; 
  });


  const attachDiv = document.getElementById('details-attachment-section');
  const attachLink = document.getElementById('details-attachment-link');
  if (inv.attachment) {
    if (inv.attachment.startsWith('data:')) {
      try {
        const arr = inv.attachment.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) u8arr[n] = bstr.charCodeAt(n);
        attachLink.href = URL.createObjectURL(new Blob([u8arr], {type: mime}));
      } catch (e) {
        attachLink.href = inv.attachment;
      }
    } else {
      attachLink.href = inv.attachment;
    }
    attachDiv.style.display = 'block';
  } else {
    attachDiv.style.display = 'none';
  }
  
  window.currentViewingInvoiceId = inv.id;
  if(window.renderComments) window.renderComments(inv);
  const commentInput = document.getElementById('details-new-comment');
  if(commentInput) commentInput.value = '';

  const actions = document.getElementById('details-action-buttons');
  let btnHtml = `<button class="btn-primary" onclick="printInvoice(${inv.id})">🖨️ طباعة الإذن</button>`;
  if (currentUser.role === 'مدير عام') btnHtml += `<button class="btn-secondary" style="background:var(--danger);" onclick="deleteInvoice(${inv.id})">🗑️ حذف</button>`;
  btnHtml += `<button class="btn-secondary" onclick="closeModal('details-modal')">إغلاق</button>`;
  actions.innerHTML = btnHtml; 
  if (typeof renderRelatedLinks === 'function') renderRelatedLinks('invoice', inv.id, 'details-related-links');
  showModal('details-modal');
}

window.printInvoice = function(invId) {
  const inv = allInvoices.find(i => String(i.id) === String(invId));
  const hasAsset = inv.items && inv.items.some(it => it.category === 'أصل');
  document.getElementById('print-doc-title').innerText = inv.type === 'in' ? 'إذن إضافة (استلام)' : inv.type === 'depreciate_asset' ? 'إذن إهلاك أصل على مشروع' : inv.type === 'out_project' ? (hasAsset ? 'إذن إهلاك أصل على مشروع' : 'إذن صرف مخزني لمشروع') : inv.type === 'transfer' ? 'إذن تحويل بين المخازن' : inv.type === 'manufacture' ? 'أمر تصنيع وإنتاج' : 'مستند أول المدة';

  let info = `<strong>رقم المستند:</strong> #${inv.id} <br><strong>التاريخ:</strong> ${new Date(inv.date).toLocaleString('ar-EG')} <br>`;
  if(inv.from_warehouse_name && inv.type !== 'manufacture') info += `<strong>المنصرف من:</strong> ${inv.from_warehouse_name} <br>`;
  if(inv.type === 'manufacture') info += `<strong>مخزن السحب والإنتاج:</strong> ${inv.from_warehouse_name} <br>`;
  if(inv.to_warehouse_name) info += `<strong>المستلم:</strong> ${inv.to_warehouse_name} <br>`;
  if(inv.project_name) info += `<strong>المشروع:</strong> ${inv.project_name} <br>`;
  if(inv.contact_name) info += `<strong>الجهة (المورد/العميل):</strong> ${inv.contact_name} <br>`;
  info += `<br><strong>تم الإنشاء/الإرسال بواسطة:</strong> ${inv.user} <br>`;
  if (inv.type === 'transfer') {
    info += `<strong>تم الاستلام بواسطة:</strong> ${inv.receiver_user ? inv.receiver_user : 'لم يتم الاستلام بعد'} <br>`;
    if (inv.manager_user) info += `<strong>قرار العجز بواسطة المدير:</strong> ${inv.manager_user} <br>`;
  }
  document.getElementById('print-doc-info').innerHTML = info;

  const tbody = document.getElementById('print-items-tbody'); tbody.innerHTML = '';
  
  if(inv.type === 'manufacture') {
    tbody.innerHTML += `<tr style="background:#e8f4f8; font-weight:bold;"><td></td><td>المنتج التام (الإنتاج): ${inv.produced_item_name}</td><td>-</td><td>${inv.produced_qty}</td><td>-</td><td>${inv.produced_cost ? inv.produced_cost.toLocaleString('en-US') : '-'}</td></tr>`;
    tbody.innerHTML += `<tr style="background:#eee; text-align:center;"><td colspan="6">المواد الخام المستهلكة في أمر التصنيع أعلاه</td></tr>`;
  }
  
  (inv.items || []).forEach(it => {

    const total = it.price ? (it.qty * it.price) : 0;
    tbody.innerHTML += `<tr><td>${currentItems.find(x => x.id === it.item_id)?.code || ''}</td><td>${it.item_name}</td><td>${it.asset_code || '-'}</td><td>${it.qty} ${it.unit}</td><td>${it.price ? it.price.toLocaleString('en-US') : '-'}</td><td>${total ? total.toLocaleString('en-US') : '-'}</td></tr>`;
  });
  window.print();
}

window.markNotifAsRead = async function(notifDate) {
  const n = allNotifications.find(x => x.date === notifDate);
  if(n) {
    n.read = true;
    await window.DB.update('notifications', n);
    const myNotifs = allNotifications.filter(x => x.user === currentUser.username && !n.read);
    document.getElementById('stat-pending').innerText = myNotifs.length;
    document.getElementById('notif-count').style.display = myNotifs.length > 0 ? 'inline-block' : 'none';
    document.getElementById('notif-count').innerText = myNotifs.length;
    renderNotifications(myNotifs);
  }
};

window.openStorekeeperReviewModal = function(invId, notifDate) {
  const inv = allInvoices.find(x => parseInt(x.id) === parseInt(invId));
  if (!inv) {
    alert('لم يتم العثور على الفاتورة، قد تكون حذفت.');
    return;
  }
  
  window.currentStorekeeperReviewInvoice = inv;
  window.currentStorekeeperReviewNotifDate = notifDate;
  
  document.getElementById('storekeeper-review-title').innerText = inv.type === 'purchases' ? 'مراجعة واستلام مشتريات' : 'مراجعة وصرف مبيعات';
  let info = `<strong>رقم المستند:</strong> #${inv.id} &nbsp;|&nbsp; <strong>النوع:</strong> ${inv.type === 'purchases' ? 'مشتريات' : 'مبيعات'}`;
  document.getElementById('storekeeper-review-info').innerHTML = info;
  
  const tbody = document.getElementById('storekeeper-review-tbody');
  tbody.innerHTML = '';
  const items = inv.items || [];
  (items || []).forEach((it, idx) => {
    let itemName = it.item_name;
    if (!itemName && it.item_id) {
       const dbItem = currentItems.find(x => parseInt(x.id) === parseInt(it.item_id));
       if (dbItem) itemName = dbItem.name;
    }
    tbody.innerHTML += `<tr>
      <td>${itemName || '-'}</td>
      <td>${it.qty}</td>
      <td><input type="number" id="review-qty-${idx}" value="${it.qty}" min="0" style="width:100px;"></td>
    </tr>`;
  });
  
  showModal('storekeeper-review-modal');
};

window.renderItemCard = function() {
  const itemId = document.getElementById('card-item-filter')?.value;
  const whId = document.getElementById('card-warehouse-filter')?.value;
  const filterFrom = document.getElementById('card-date-from')?.value;
  const filterTo = document.getElementById('card-date-to')?.value;
  
  const tbody = document.getElementById('item-card-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  
  if(!itemId) {
    document.getElementById('card-total-in').innerText = '0';
    document.getElementById('card-total-out').innerText = '0';
    document.getElementById('card-final-balance').innerText = '0';
    return;
  }
  
  let records = [];
  (allInvoices || []).forEach(inv => {
    let typeLabel = '';
    let locLabel = '';
    
    // Check if item was produced
    if (inv.type === 'manufacture' && inv.product_id === parseInt(itemId)) {
       records.push({ date: inv.date, inv: inv, type: 'وارد (منتج تام)', loc: inv.from_warehouse_name, whId: inv.from_warehouse_id, qtyIn: inv.product_qty || inv.produced_qty || 0, qtyOut: 0, price: inv.produced_cost || 0 });
    }
    
    // Check if item was in items array
    (inv.items || []).forEach(it => {

      if (it.item_id === parseInt(itemId)) {
        
        if (inv.type === 'sales_return' && inv.status === 'posted') {
           records.push({ date: inv.date, inv: inv, type: 'مرتجع مبيعات', loc: inv.from_warehouse_name || '', whId: inv.from_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price });
        } else if (inv.type === 'purchases_return' && inv.status === 'posted') {
           records.push({ date: inv.date, inv: inv, type: 'مرتجع مشتريات', loc: inv.to_warehouse_name || '', whId: inv.to_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price });
        } else if (inv.type === 'in' || inv.type === 'opening_balance') {
           records.push({ date: inv.date, inv: inv, type: inv.type==='in'?'وارد (مشتريات)':'رصيد أول', loc: inv.to_warehouse_name, whId: inv.to_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price });
        } else if (inv.type === 'out_project' || inv.type === 'depreciate_asset') {
           records.push({ date: inv.date, inv: inv, type: inv.type==='out_project'?'منصرف لمشروع':'إهلاك أصل', loc: inv.from_warehouse_name + (inv.project_name ? ' ⬅️ ' + inv.project_name : ''), whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price });
        } else if (inv.type === 'manufacture') {
           records.push({ date: inv.date, inv: inv, type: 'مسحوب للتصنيع', loc: inv.from_warehouse_name, whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: balancesCache[it.item_id]?.avgCost || 0 });
        } else if (inv.type === 'transfer') {
           // Out from source
           records.push({ date: inv.date, inv: inv, type: 'محول (منصرف)', loc: inv.from_warehouse_name, whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price || 0 });
           // In to dest
           if(inv.status === 'completed') {
             records.push({ date: inv.date, inv: inv, type: 'محول (وارد)', loc: inv.to_warehouse_name, whId: inv.to_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price || 0 });
           }
        }
      }
    });
  });

  // Sort chronologically
  records.sort((a,b) => new Date(a.date) - new Date(b.date));
  
  // Warehouse filtering
  if (whId && whId !== 'all') {
    records = records.filter(r => r.whId === parseInt(whId));
  }
  
  // Date filtering
  if (filterFrom) {
    const fromDate = new Date(filterFrom); fromDate.setHours(0,0,0,0);
    records = records.filter(r => new Date(r.date) >= fromDate);
  }
  if (filterTo) {
    const toDate = new Date(filterTo); toDate.setHours(23,59,59,999);
    records = records.filter(r => new Date(r.date) <= toDate);
  }

  let runningBalance = 0;
  let totalIn = 0;
  let totalOut = 0;

  (records || []).forEach(r => {
    runningBalance += (r.qtyIn - r.qtyOut);
    totalIn += r.qtyIn;
    totalOut += r.qtyOut;
    tbody.innerHTML += `<tr>
      <td>${new Date(r.date).toLocaleString('ar-EG')}</td>
      <td>#${r.inv.id} <button class="btn-primary" style="padding:1px 5px; font-size:11px;" onclick="viewDetails(${r.inv.id})">🔍</button></td>
      <td>${r.type}</td>
      <td>${r.loc}</td>
      <td>${Number(r.price).toLocaleString('en-US')}</td>
      <td style="color:var(--success); font-weight:bold;">${r.qtyIn > 0 ? r.qtyIn : '-'}</td>
      <td style="color:var(--danger); font-weight:bold;">${r.qtyOut > 0 ? r.qtyOut : '-'}</td>
      <td style="font-weight:bold; background:rgba(255,255,255,0.05);">${runningBalance}</td>
    </tr>`;
  });

  document.getElementById('card-total-in').innerText = totalIn;
  document.getElementById('card-total-out').innerText = totalOut;
  document.getElementById('card-final-balance').innerText = runningBalance;
}

window.populateDropdowns = function() {
  oldPopulate();
  const cardItemSelect = document.getElementById('card-item-filter');
  if(cardItemSelect) {
    cardItemSelect.innerHTML = `<option value="">-- إختر الصنف --</option>` + currentItems.map(i => `<option value="${i.id}">${i.name}</option>`).join('');
  }
  const cardWhFilter = document.getElementById('card-warehouse-filter');
  if(cardWhFilter) {
    cardWhFilter.innerHTML = `<option value="all">كل المخازن</option>` + currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  }
  
  const contactTagsList = document.getElementById('contact-tags-list');
  const filterContactTagsList = document.getElementById('filter-contact-tags-list');
  if(contactTagsList || filterContactTagsList) {
    const tags = [...new Set(currentContacts.map(c => c.tag).filter(t => t && t.trim()))];
    const tagsHtml = tags.map(t => `<option value="${t}"></option>`).join('');
    if(contactTagsList) contactTagsList.innerHTML = tagsHtml;
    if(filterContactTagsList) filterContactTagsList.innerHTML = tagsHtml;
  }
  
  const itemTagsList = document.getElementById('item-tags-list');
  const filterItemTagsList = document.getElementById('filter-item-tags-list');
  if(itemTagsList || filterItemTagsList) {
    const tags = [...new Set(currentItems.map(i => i.tag).filter(t => t && t.trim()))];
    const tagsHtml = tags.map(t => `<option value="${t}"></option>`).join('');
    if(itemTagsList) itemTagsList.innerHTML = tagsHtml;
    if(filterItemTagsList) filterItemTagsList.innerHTML = tagsHtml;
  }
}

window.updateAvailableBalance = function() {
  const whId = document.getElementById('invoice-warehouse').value;
  const itemId = document.getElementById('invoice-item').value;
  let balLabel = document.getElementById('available-balance-label');
  if(!balLabel) {
    const parent = document.getElementById('invoice-item').parentElement;
    balLabel = document.createElement('div');
    balLabel.id = 'available-balance-label';
    balLabel.style = 'font-size:12px; color:var(--success); margin-top:5px; font-weight:bold;';
    parent.appendChild(balLabel);
  }
  
  if(!whId || !itemId) {
    balLabel.innerText = '';
    return;
  }
  
  const bInfo = balancesCache[itemId];
  if(bInfo && bInfo.warehouses[whId]) {
    balLabel.innerText = 'الرصيد المتاح حالياً في هذا المخزن: ' + bInfo.warehouses[whId].qty;
  } else {
    balLabel.innerText = 'لا يوجد رصيد من هذا الصنف في المخزن المحدد.';
    balLabel.style.color = 'var(--danger)';
  }
}

window.renderComments = function(inv) {
  const list = document.getElementById('details-comments-list');
  if(!list) return;
  list.innerHTML = '';
  if (!inv.comments || inv.comments.length === 0) {
    list.innerHTML = '<div style="color:var(--text-secondary); text-align:center; font-size:12px;">لا توجد تعليقات بعد.</div>';
    return;
  }
  (inv.comments || []).forEach(c => {
    let text = c.text;
    // highlight mentions
    text = text.replace(/@([\w\u0600-\u06FF]+)/g, '<span style="color:var(--primary); font-weight:bold;">@$1</span>');
    list.innerHTML += `<div style="margin-bottom:8px; padding-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.05);">
      <strong style="font-size:12px; color:var(--text-secondary);">${c.user} - ${new Date(c.date).toLocaleString('ar-EG')}</strong>
      <div style="margin-top:4px;">${text}</div>
    </div>`;
  });
  list.scrollTop = list.scrollHeight;
};

window.addComment = async function() {
  try {
    const input = document.getElementById('details-new-comment');
    const text = input.value.trim();
    if(!text || !window.currentViewingInvoiceId) return;
    
    const invIndex = allInvoices.findIndex(i => i.id === window.currentViewingInvoiceId);
    if(invIndex === -1) return;
    
    const inv = allInvoices[invIndex];
    if(!inv.comments) inv.comments = [];
    
    const commentObj = { user: currentUser.username, text: text, date: new Date().toISOString() };
    inv.comments.push(commentObj);
    
    // Extract Mentions
    const mentions = text.match(/@([\w\u0600-\u06FF]+)/g);
    if(mentions) {
      for(let m of mentions) {
        const username = m.substring(1);
        const mentionedUser = currentUsers.find(u => u.username === username);
        if(mentionedUser) {
          const notif = {
            date: new Date().toISOString(),
            message: `الموظف ${currentUser.username} ذكرك في تعليق على المستند #${inv.id}: "${text}"`,
            user: mentionedUser.username,
            read: false,
            invoice_id: inv.id
          };
          await window.DB.add('notifications', notif);
        }
      }
    }
    
    await window.DB.update('transactions', inv);
    allInvoices[invIndex] = inv;
    
    input.value = '';
    renderComments(inv);
    
    // Update notifications if needed
    allNotifications = await window.DB.getAll('notifications') || [];
    const myNotifs = allNotifications.filter(n => n.user === currentUser.username && !n.read);
    if(window.renderNotifications) renderNotifications(myNotifs);
  } catch(e) {
    alert("حدث خطأ أثناء حفظ التعليق: " + e.message);
    console.error(e);
  }
};

window.handleMentionInput = function(input) {
  try {
    const val = input.value;
    const lastAt = val.lastIndexOf('@');
    const dropdown = document.getElementById('mention-dropdown');
    if (!dropdown) return;
    
    if (lastAt !== -1) {
      const searchStr = val.substring(lastAt + 1).toLowerCase();
      if (searchStr.includes(' ')) {
        dropdown.style.display = 'none';
        return;
      }
      const matches = currentUsers.filter(u => u.username.toLowerCase().startsWith(searchStr));
      if (matches.length > 0) {
        dropdown.innerHTML = matches.map(u => `<div style="padding:8px 10px; cursor:pointer; border-bottom:1px solid rgba(0,0,0,0.1); color:black;" class="mention-item" onclick="insertMention('${u.username}')">${u.username}</div>`).join('');
        dropdown.style.display = 'block';
      } else {
        dropdown.style.display = 'none';
      }
    } else {
      dropdown.style.display = 'none';
    }
  } catch(e) {
    console.error("Mention Error:", e);
  }
};

window.insertMention = function(username) {
  const input = document.getElementById('details-new-comment');
  const val = input.value;
  const lastAt = val.lastIndexOf('@');
  if (lastAt !== -1) {
    input.value = val.substring(0, lastAt) + '@' + username + ' ';
  }
  document.getElementById('mention-dropdown').style.display = 'none';
  input.focus();
};

window._sendingInvoiceToStore = window._sendingInvoiceToStore || {};

window.sendInvoiceToStore = async function(invId) {
  if (window._sendingInvoiceToStore[invId]) return;
  window._sendingInvoiceToStore[invId] = true;

  try {
      let inv = allInvoices.find(x => String(x.id) === String(invId));
      if (!inv) {
         const dbInvs = await window.DB.getAll('transactions');
         inv = dbInvs.find(x => String(x.id) === String(invId));
      }
      if (!inv) return;
      inv.status = 'pending_store';
      await window.DB.update('transactions', inv);
    
      const users = await window.DB.getAll('users');
      const existingNotifs = await window.DB.getAll('notifications') || [];
      const storekeepers = users.filter(u => u.role === 'أمين مخزن');
      
      for (let sk of storekeepers) {
          const exists = existingNotifs.find(n => n.user === sk.username && String(n.invoice_id) === String(inv.id));
          if (!exists) {
              const notifObj = {
                user: sk.username,
                invoice_id: inv.id,
                message: inv.type === 'purchases' ? 'إذن استلام مشتريات وارد لك للتأكيد' : 'إذن صرف مبيعات وارد لك للتأكيد',
                date: new Date().toISOString(),
                read: false
              };
              await window.DB.add('notifications', notifObj);
          }
      }
    
      await loadData();
      alert('تم الإرسال للمخزن بنجاح.');
  } finally {
      delete window._sendingInvoiceToStore[invId];
  }
};

            if (typeof window.sendInvoiceToStore === 'function') {
                await window.sendInvoiceToStore(newInvId);
            }

window.renderAbstractComments = function(type, ab) {
  const section = document.getElementById(type + '-chat-section');
  if(section) section.style.display = ab.id ? 'block' : 'none';
  
  const listId = type + '-comments-list';
  const list = document.getElementById(listId);
  if(!list) return;
  list.innerHTML = '';
  if (!ab.comments || ab.comments.length === 0) {
    list.innerHTML = '<div style="color:var(--text-secondary); text-align:center; font-size:12px;">لا توجد تعليقات بعد.</div>';
    return;
  }
  (ab.comments || []).forEach(c => {
    let text = c.text;
    text = text.replace(/@([\w\u0600-\u06FF]+)/g, '<span style="color:var(--primary); font-weight:bold;">@$1</span>');
    list.innerHTML += `<div style="margin-bottom:8px; padding-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.05);">
      <strong style="font-size:12px; color:var(--text-secondary);">${c.user} - ${new Date(c.date).toLocaleString('ar-EG')}</strong>
      <div style="margin-top:4px;">${text}</div>
    </div>`;
  });
  list.scrollTop = list.scrollHeight;
};

window.addAbstractComment = async function(type) {
  try {
    const input = document.getElementById(type + '-new-comment');
    const text = input.value.trim();
    if(!text || !window.currentViewingAbstractId) return;
    
    let isClient = type === 'client-abstract';
    let dbTable = isClient ? 'client_abstracts' : 'abstracts';
    let allData = isClient ? allClientAbstracts : allAbstracts;
    
    const abIndex = allData.findIndex(i => i.id === window.currentViewingAbstractId);
    if(abIndex === -1) return;
    
    const ab = allData[abIndex];
    if(!ab.comments) ab.comments = [];
    
    const commentObj = { user: currentUser.username, text: text, date: new Date().toISOString() };
    ab.comments.push(commentObj);
    
    const mentions = text.match(/@([\w\u0600-\u06FF]+)/g);
    if(mentions) {
      for(let m of mentions) {
        const username = m.substring(1);
        const mentionedUser = currentUsers.find(u => u.username === username);
        if(mentionedUser) {
          let notifs = await window.DB.getAll('notifications') || [];
          notifs.push({
            id: Date.now().toString() + Math.random().toString(36).substring(2),
            user: mentionedUser.username,
            text: `تم عمل منشن لك في مستخلص رقم ${ab.doc_no}`,
            link: `#`,
            date: new Date().toISOString(),
            read: false
          });
          await window.DB.put('notifications', notifs);
        }
      }
    }
    
    await window.DB.put(dbTable, ab);
    input.value = '';
    window.renderAbstractComments(type, ab);
    
    const allNotifications = await window.DB.getAll('notifications') || [];
    const myNotifs = allNotifications.filter(n => n.user === currentUser.username && !n.read);
    if(window.renderNotifications) renderNotifications(myNotifs);
  } catch(e) {
    alert("حدث خطأ أثناء إضافة التعليق: " + e.message);
  }
};

    if(e.target.dataset.view === 'client-abstracts' && typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();

window.renderClientAbstracts = async function() {
  currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];
  const tbody = document.getElementById('client-abstracts-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  const search = document.getElementById('client-abstract-search').value.toLowerCase();
  const statusFilter = document.getElementById('client-abstract-status-filter').value;
  
  let filtered = currentClientAbstracts.filter(ab => {
    const pName = (currentProjects.find(p => p.id == ab.project_id) || {}).name || '';
    const matchSearch = ab.client_name.toLowerCase().includes(search) || 
                        pName.toLowerCase().includes(search) || 
                        (ab.abstract_number && ab.abstract_number.toLowerCase().includes(search));
    const matchStatus = statusFilter === 'all' || ab.status === statusFilter;
    return matchSearch && matchStatus;
  });
  
  filtered.sort((a,b) => new Date(b.date) - new Date(a.date));
  
  (filtered || []).forEach(ab => {
    const tr = document.createElement('tr');
    const pName = (currentProjects.find(p => p.id == ab.project_id) || {}).name || '';
    
    let paid = 0;
    const linkedVouchers = allInvoices.filter(j => j.type === 'receipt' && j.status === 'posted' && j.linked_invoice_id === 'cab-' + ab.id);
    (linkedVouchers || []).forEach(v => {
        paid += parseFloat(v.amount) || 0;
    });
    
    let actions = `
      <button class="action-btn btn-view" onclick="printClientAbstract(${ab.id})">عرض</button>
      ${ab.status === 'draft' ? `<button class="action-btn" style="background:var(--success); color:#fff; border:none;" onclick="approveClientAbstract(${ab.id})">اعتماد</button>` : ''}
      ${ab.status === 'approved' ? `<button class="action-btn" style="background:var(--success); color:#fff; border:none;" onclick="payClientAbstract(${ab.id})">سند قبض</button>` : ''}
      ${ab.status === 'draft' ? `<button class="action-btn btn-edit" onclick="openClientAbstractModal(${ab.id})">تعديل</button>` : ''}
      ${ab.status === 'draft' ? `<button class="action-btn btn-danger" onclick="deleteClientAbstract(${ab.id})">حذف</button>` : ''}
    `;
    
    let remaining = Math.max(0, (parseFloat(ab.net_value) || 0) - paid);
    
    tr.innerHTML = `
      <td>${ab.abstract_number || ('#' + ab.id)}</td>
      <td>${new Date(ab.date).toLocaleDateString('ar-EG')}</td>
      <td>${pName}</td>
      <td>${ab.client_name || ''}</td>
      <td style="font-weight:bold; color:var(--success);">${(parseFloat(ab.net_value) || 0).toLocaleString('en-US')} ج.م</td>
      <td style="color:var(--primary); font-weight:bold;">${paid.toLocaleString('en-US')} ج.م</td>
      <td style="color:var(--danger); font-weight:bold;">${remaining.toLocaleString('en-US')} ج.م</td>
      <td><span class="status-badge ${ab.status==='approved'?'status-posted':'status-draft'}">${ab.status==='approved'?'معتمد':'مسودة'}</span></td>
      <td>${actions}</td>
    `;
    tbody.appendChild(tr);
  });
};

        if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();

            if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();

window.openClientAbstractModal = function(id = null) {
  window.currentViewingAbstractId = id;
  document.getElementById('client-abstract-modal-title').innerText = id ? 'تعديل مستخلص عميل #' + id : 'مستخلص عميل جديد';
  document.getElementById('edit-client-abstract-id').value = id || '';
  
  const pSel = document.getElementById('client-abstract-project');
  pSel.innerHTML = '<option value="">اختر المشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  
  if (id) {
      const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
      if (ab) {
          pSel.value = ab.project_id;
          document.getElementById('client-abstract-date').value = ab.date;
          document.getElementById('client-abstract-name').value = ab.client_name || '';
          document.getElementById('client-abstract-notes').value = ab.notes || '';
          document.getElementById('client-abstract-previous-value').value = ab.previous_value || 0;
          document.getElementById('client-abstract-current-value').value = ab.current_value || 0;
          document.getElementById('client-abstract-total-value').value = ab.total_value || 0;
          document.getElementById('client-abstract-deduction-percent').value = ab.deduction_percent || 0;
          document.getElementById('client-abstract-retention-percent').value = ab.retention_percent || 0;
          if(window.renderAbstractComments) window.renderAbstractComments('client-abstract', ab);
      }
  } else {
      const form = document.getElementById('client-abstract-form'); if(form) form.reset();
      document.getElementById('client-abstract-date').value = new Date().toISOString().split('T')[0];
      const nextId = (currentClientAbstracts.length > 0 ? Math.max(...currentClientAbstracts.map(a=>a.id)) : 0) + 1;
      document.getElementById('client-abstract-number').value = 'CAB-' + nextId;
      if(window.renderAbstractComments) window.renderAbstractComments('client-abstract', {id:null});
  }
  
  showModal('client-abstract-modal');
};

window.deleteClientAbstract = async function(id) {
    if(confirm('هل أنت متأكد من حذف هذا المستخلص؟')) {
        await window.DB.remove('client_abstracts', id);
        if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
    }
};

window.approveClientAbstract = async function(id) {
    if(confirm('هل أنت متأكد من اعتماد هذا المستخلص؟')) {
        const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
        if(ab) {
            ab.status = 'approved';
            await window.DB.update('client_abstracts', ab);
            if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
            alert('تم الاعتماد بنجاح.');
        }
    }
};

window.payClientAbstract = function(id) {
    const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
    if(ab) {
        document.getElementById('receipt-linked-invoice').value = 'cab-' + ab.id;
        document.getElementById('receipt-amount').value = ab.net_value;
        const proj = currentProjects.find(p => p.id === parseInt(ab.project_id));
        if (proj && proj.client_name) {
            document.getElementById('receipt-party-name').value = proj.client_name;
        } else {
            document.getElementById('receipt-party-name').value = ab.client_name || '';
        }
        showModal('receipt-modal');
    }
};

window.renderStorekeepersDashboard = function() {
    const section = document.getElementById('storekeepers-dashboard-section');
    const tbody = document.getElementById('storekeepers-dashboard-tbody');
    if (!section || !tbody) return;

    // --- My Custody Card Logic (For the logged-in user) ---
    const myCustodyCard = document.getElementById('my-custody-card');
    if (myCustodyCard) {
        if (currentUser && currentUser.custody_account_id) {
            myCustodyCard.style.display = 'block';
            let myRunningBalance = 0;
            currentJournals.forEach(j => {
                if (j.status !== 'posted') return;
                if (j.rows) {
                    j.rows.forEach(r => {
                        if (r.account_id == currentUser.custody_account_id) {
                            myRunningBalance += (parseFloat(r.debit) || 0) - (parseFloat(r.credit) || 0);
                        }
                    });
                }
            });
            const myOpAcc = currentAccounts.find(a => a.id == currentUser.custody_account_id);
            if(myOpAcc) myRunningBalance += (parseFloat(myOpAcc.op_debit) || 0) - (parseFloat(myOpAcc.op_credit) || 0);
            document.getElementById('my-custody-balance').innerText = Math.abs(myRunningBalance).toLocaleString('ar-EG', {minimumFractionDigits:2}) + (myRunningBalance >= 0 ? ' مدين' : ' دائن');
        } else {
            myCustodyCard.style.display = 'none';
        }
    }

    // Only general manager should see all storekeepers
    if (currentUser.role !== 'مدير عام') {
        section.style.display = 'none';
        return;
    }

    // Find storekeepers
    const storekeepers = currentUsers.filter(u => u.role === 'أمين مخزن' || u.role === 'أمينة مخزن' || u.role === 'مدير مخازن' || u.username.includes('امين'));
    
    // Also include anyone who has a custody account that has the word عهدة in it
    currentUsers.forEach(u => {
       if (u.custody_account_id && !storekeepers.find(sk => sk.id === u.id)) {
           const acc = currentAccounts.find(a => a.id === u.custody_account_id);
           if (acc && acc.name.includes('عهد')) {
               storekeepers.push(u);
           }
       }
    });

    if (storekeepers.length === 0) {
        section.style.display = 'none';
        return;
    }

    section.style.display = 'block';
    tbody.innerHTML = '';

    storekeepers.forEach(sk => {
        let accName = 'لا يوجد';
        let balanceStr = '0';
        let balanceHtml = '<span>0</span>';

        if (sk.custody_account_id) {
            const acc = currentAccounts.find(a => a.id === sk.custody_account_id);
            if (acc) {
                accName = acc.name;
                
                // Calculate balance
                let runningBalance = 0;
                currentJournals.forEach(j => {
                    if (j.status !== 'posted') return;
                    if (j.rows) {
                        j.rows.forEach(r => {
                            if (r.account_id == sk.custody_account_id) {
                                runningBalance += (parseFloat(r.debit) || 0) - (parseFloat(r.credit) || 0);
                            }
                        });
                    }
                });

                balanceStr = Math.abs(runningBalance).toLocaleString('en-US');
                if (runningBalance > 0) balanceHtml = `<span style="color:var(--danger); font-weight:bold;">${balanceStr} مدين</span>`;
                else if (runningBalance < 0) balanceHtml = `<span style="color:var(--success); font-weight:bold;">${balanceStr} دائن</span>`;
                else balanceHtml = `<span>0</span>`;
            }
        }

        let actionBtn = `<button class="btn btn-sm btn-secondary" disabled>📄 كشف حساب</button>`;
        if (sk.custody_account_id) {
            actionBtn = `<button class="btn btn-sm btn-primary" onclick="openAccountStatement(${sk.custody_account_id})">📄 كشف حساب</button>`;
        }

        tbody.innerHTML += `
            <tr>
                <td>${sk.username}</td>
                <td>${accName}</td>
                <td style="font-size: 16px;">${balanceHtml}</td>
                <td>${actionBtn}</td>
            </tr>
        `;
    });
};

document.getElementById('btn-confirm-receipt').addEventListener('click', async () => {
  try {
    const invoiceId = parseInt(document.getElementById('receive-invoice-id').value);
    const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
    let hasDeficit = false;
    inv.receiver_user = currentUser.username;
    (inv.items || []).forEach((it, idx) => {
      const recQty = parseFloat(document.getElementById(`rec-qty-${idx}`).value);
      it.received_qty = recQty; if (recQty < it.qty) hasDeficit = true;
    });

    if (hasDeficit) {
      inv.status = 'pending_decision';
      const managers = currentUsers.filter(u => u.role === 'مدير عام');
      for (let m of managers) { await window.DB.add('notifications', { user: m.username, message: `عجز في التحويل #${inv.id}. بانتظار قرارك.`, invoice_id: inv.id, date: new Date().toISOString(), read: false }); }
    } else {
      inv.status = 'completed'; (inv.items || []).forEach(it => {
 it.deducted_qty = it.qty; it.received_qty = it.qty; });
    }
    await window.DB.update('transactions', inv);
    const myNotif = allNotifications.find(n => n.invoice_id === inv.id && n.user === currentUser.username);
    if(myNotif) { myNotif.read = true; await window.DB.update('notifications', myNotif); }
    closeModal('receive-modal'); await loadData(); alert('تم تأكيد الاستلام!');
  } catch(e) { alert("خطأ: " + e.message); }
});

document.getElementById('btn-execute-decision').addEventListener('click', async () => {
  try {
    const invoiceId = parseInt(document.getElementById('decision-invoice-id').value);
    const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
    const action = document.getElementById('decision-action').value;
    
    inv.status = 'completed'; inv.manager_user = currentUser.username;
    (inv.items || []).forEach(it => {

      if (it.received_qty < it.qty) {
        if (action === 'charge_sender') it.deducted_qty = it.received_qty; 
        else if (action === 'charge_receiver') { it.received_qty = it.qty; it.deducted_qty = it.qty; } 
        else if (action === 'log_deficit') it.deducted_qty = it.qty;
      } else { it.deducted_qty = it.qty; }
    });
    await window.DB.update('transactions', inv);
    
    // Find all related notifications and mark them as read
    const relatedNotifs = allNotifications.filter(n => 
      n.user === currentUser.username && 
      !n.read && 
      (n.invoice_id === inv.id || String(n.message).includes('#' + inv.id))
    );
    for (let notif of relatedNotifs) {
      notif.read = true;
      await window.DB.update('notifications', notif);
    }
    
    closeModal('decision-modal'); await loadData(); alert('تم اعتماد القرار وتحديث الأرصدة!');
  } catch(e) { alert("خطأ: " + e.message); }
});

document.getElementById('btn-approve-storekeeper')?.addEventListener('click', async () => {
  const inv = window.currentStorekeeperReviewInvoice;
  if(!inv) return;
  
  // Update quantities based on storekeeper input
  (inv.items || []).forEach((it, idx) => {
    const actQty = parseFloat(document.getElementById(`review-qty-${idx}`).value) || 0;
    it.qty = actQty;
    // re-calculate line price/discount if needed, but for inventory qty is what matters most.
  });
  let newTotal = 0; (inv.items || []).forEach(it => {
 newTotal += (it.qty * (it.price || 0)); });
  inv.total = newTotal;
  inv.amount = newTotal;
  
  inv.status = 'posted';
  await window.DB.update('transactions', inv);
  
  if (inv.type === 'sales') await generateSalesJournal(inv);
  else if (inv.type === 'purchases') await generatePurchasesJournal(inv);
  
  if (window.currentStorekeeperReviewNotifDate) {
    await markNotifAsRead(window.currentStorekeeperReviewNotifDate);
  }
  
  closeModal('storekeeper-review-modal');
  alert('?? ?????? ??????? ??????? ??????');
  if (typeof renderNotifications === 'function') renderNotifications();
  await loadData();
  alert('تم الاعتماد والتحديث بنجاح.');
});
