
// 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));
  if (!inv) { alert('لم يتم العثور على المستند.'); return; }
  const fromWh = inv.from_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(inv.from_warehouse_id))?.name) || 'غير محدد';
  document.getElementById('receive-invoice-id').value = invoiceId;
  document.getElementById('receive-info').innerText = `إذن تحويل رقم #${inv.id} من مخزن ${fromWh}`;
  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;`;
  let notesText = inv.notes || 'لا يوجد';
  extraInfo += `<br><div style="margin-top:8px; border-top:1px dashed #ccc; padding-top:5px;">
    <strong>ملاحظات:</strong> <span id="inv-notes-display-${inv.id}">${notesText}</span>
    <button onclick="window.editInvoiceNote(${inv.id})" class="btn-secondary" style="padding: 2px 8px; font-size: 11px; margin-right: 15px; border-radius: 4px; border: 1px solid #ccc; cursor: pointer;">تعديل الملاحظات ✏️</button>
    <div id="inv-notes-edit-container-${inv.id}" style="display:none; margin-top:8px;">
      <textarea id="inv-notes-input-${inv.id}" style="width:100%; min-height:60px; padding:8px; border-radius:5px; border:1px solid var(--border); resize:vertical; font-family: inherit;">${inv.notes || ''}</textarea>
      <div style="margin-top:5px; display:flex; gap: 8px;">
        <button onclick="window.saveInvoiceNote(${inv.id})" class="btn-primary" style="padding: 4px 12px; font-size: 12px; border-radius: 4px; cursor: pointer;">حفظ الملاحظات</button>
        <button onclick="document.getElementById('inv-notes-edit-container-${inv.id}').style.display='none'" class="btn-secondary" style="padding: 4px 12px; font-size: 12px; border-radius: 4px; cursor: pointer;">إلغاء</button>
      </div>
    </div>
  </div>`;

  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' ? 'مراجعة واستلام مشتريات' : (inv.type === 'sales' ? 'مراجعة وصرف مبيعات' : (inv.type === 'sales_return' ? '📦 مراجعة واستلام مرتجع مبيعات' : '📦 مراجعة وصرف مرتجع مشتريات'));
  
  const typeLabels = { purchases: 'مشتريات', sales: 'مبيعات', sales_return: 'مرتجع مبيعات', purchases_return: 'مرتجع مشتريات' };
  const dirLabels = { purchases: '⬇️ إضافة للمخزن', sales: '⬆️ خصم من المخزن', sales_return: '⬇️ إضافة للمخزن (استرداد بضاعة من عميل)', purchases_return: '⬆️ خصم من المخزن (إرجاع بضاعة لمورد)' };
  const contactName = inv.contact_name || (typeof currentContacts !== 'undefined' ? currentContacts.find(c => c.id == inv.contact_id)?.name : '') || '-';
  
  let info = `
    <div style="display:flex; gap:20px; flex-wrap:wrap; margin-bottom:8px;">
      <span><strong>رقم المستند:</strong> #${inv.id}</span>
      <span><strong>النوع:</strong> <span style="color:var(--accent); font-weight:bold;">${typeLabels[inv.type] || inv.type}</span></span>
      <span><strong>التاريخ:</strong> ${inv.date ? new Date(inv.date).toLocaleDateString('ar-EG') : '-'}</span>
    </div>
    <div style="display:flex; gap:20px; flex-wrap:wrap;">
      <span><strong>الجهة:</strong> ${contactName}</span>
      <span><strong>الإجراء المخزني:</strong> <span style="color:var(--success);">${dirLabels[inv.type] || '-'}</span></span>
      <span><strong>القيمة الإجمالية:</strong> ${(parseFloat(inv.total_amount || inv.total || 0)).toLocaleString('ar-EG')} ج.م</span>
    </div>`;
  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 = '';
  
  // Ensure tag card exists (create dynamically if missing from HTML)
  if (!document.getElementById('card-item-tag-display')) {
    const balanceCard = document.getElementById('card-final-balance');
    if (balanceCard) {
      const parent = balanceCard.closest('div[style]')?.parentElement;
      if (parent) {
        const tagDiv = document.createElement('div');
        tagDiv.className = 'stat-card';
        tagDiv.style.cssText = 'flex:1; min-width:150px; background:#2d1f4e; border:2px solid #f39c12; border-radius:10px; padding:12px 15px;';
        tagDiv.innerHTML = '🏷️ التاج (التصنيف): <span id="card-item-tag-display" style="color:#f39c12; font-weight:bold; font-size:16px;">--</span>';
        balanceCard.parentElement.appendChild(tagDiv);
      }
    }
  }

  const tagEl = document.getElementById('card-item-tag-display');

  if(!itemId) {
    document.getElementById('card-total-in').innerText = '0';
    document.getElementById('card-total-out').innerText = '0';
    document.getElementById('card-final-balance').innerText = '0';
    if (tagEl) tagEl.innerText = '--';
    return;
  }
  
  const itemObj = currentItems.find(i => String(i.id) === String(itemId));
  if (tagEl) {
     tagEl.innerText = itemObj && itemObj.tag ? itemObj.tag : '--';
  }
  
  let records = [];
  const parsedItemId = parseInt(itemId);

  // 1. تجميع كل الفواتير من كل المصفوفات المحتملة في النظام بعد فصل الموديولات
  let allData = [];
  if (typeof allInvoices !== 'undefined') allData = allData.concat(allInvoices);
  if (typeof window.allSales !== 'undefined') allData = allData.concat(window.allSales);
  if (typeof window.allPurchases !== 'undefined') allData = allData.concat(window.allPurchases);
  if (typeof window.allSalesReturns !== 'undefined') allData = allData.concat(window.allSalesReturns);
  if (typeof window.allPurchasesReturns !== 'undefined') allData = allData.concat(window.allPurchasesReturns);

  // 2. إزالة التكرار لضمان عدم تكرار عرض الفاتورة (لو كانت موجودة في أكثر من مصفوفة)
  let uniqueDataMap = new Map();
  allData.forEach(inv => {
     if (inv && inv.id && inv.type) {
         uniqueDataMap.set(inv.type + '_' + inv.id, inv);
     }
  });
  let mergedInvoices = Array.from(uniqueDataMap.values());

  // 3. تحليل وقراءة بنود جميع الفواتير
  mergedInvoices.forEach(inv => {
    // تجاهل المسودات والفواتير المالية والمعلقة لأنها لا تؤثر على الرصيد
    if (inv.status === 'draft' || inv.status === 'pending_store' || inv.status === 'financial_only') return;

    // فحص المنتج التام من أوامر التصنيع
    if (inv.type === 'manufacture' && parseInt(inv.product_id) === parsedItemId) {
       records.push({ 
           date: inv.date, inv: inv, type: 'وارد (منتج تام)', 
           loc: inv.from_warehouse_name || 'مخزن التصنيع', 
           whId: inv.from_warehouse_id, 
           qtyIn: parseFloat(inv.product_qty || inv.produced_qty) || 0, 
           qtyOut: 0, 
           price: parseFloat(inv.produced_cost) || 0 
       });
    }
    
    // الفحص داخل بنود كل فاتورة
    (inv.items || []).forEach(it => {
      if (parseInt(it.item_id) === parsedItemId) {
        
        // --- المبيعات (منصرف) ---
        if (inv.type === 'sales') {
           const locName = inv.contact_name || 'عميل';
           records.push({ date: inv.date, inv: inv, type: 'فاتورة مبيعات', loc: locName, whId: inv.warehouse_id, qtyIn: 0, qtyOut: parseFloat(it.qty), price: parseFloat(it.price) });
        } 
        // --- المشتريات (وارد) ---
        else if (inv.type === 'purchases') {
           const locName = inv.contact_name || 'مورد';
           records.push({ date: inv.date, inv: inv, type: 'فاتورة شراء', loc: locName, whId: inv.warehouse_id, qtyIn: parseFloat(it.qty), qtyOut: 0, price: parseFloat(it.price) });
        }
        // --- مرتجع المبيعات (وارد) ---
        else if (inv.type === 'sales_return' || inv.type === 'sales_returns') {
           const locName = window.currentWarehouses?.find(w => w.id == (inv.to_warehouse_id || inv.warehouse_id))?.name || inv.to_warehouse_name || inv.contact_name || 'عميل';
           records.push({ date: inv.date, inv: inv, type: 'مرتجع مبيعات', loc: locName, whId: inv.to_warehouse_id || inv.warehouse_id, qtyIn: parseFloat(it.qty), qtyOut: 0, price: parseFloat(it.price) });
        } 
        // --- مرتجع المشتريات (منصرف) ---
        else if (inv.type === 'purchases_return' || inv.type === 'purchases_returns') {
           const locName = window.currentWarehouses?.find(w => w.id == (inv.from_warehouse_id || inv.warehouse_id))?.name || inv.from_warehouse_name || inv.contact_name || 'مورد';
           records.push({ date: inv.date, inv: inv, type: 'مرتجع مشتريات', loc: locName, whId: inv.from_warehouse_id || inv.warehouse_id, qtyIn: 0, qtyOut: parseFloat(it.qty), price: parseFloat(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: parseFloat(it.qty), qtyOut: 0, price: parseFloat(it.price) });
        } 
        // --- منصرف مشروع أو إهلاك أصل أو تسوية هالك (منصرف) ---
        else if (inv.type === 'out' || inv.type === 'out_project' || inv.type === 'depreciate_asset') {
           records.push({ date: inv.date, inv: inv, type: inv.type==='out_project'?'منصرف لمشروع':(inv.type==='out'?'صرف/تسوية هالك':'إهلاك أصل'), loc: (inv.from_warehouse_name||'') + (inv.project_name ? ' ⬅️ ' + inv.project_name : ''), whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: parseFloat(it.qty), price: parseFloat(it.price) });
        } 
        // --- مسحوب للتصنيع (منصرف) ---
        else if (inv.type === 'manufacture') {
           let price = typeof balancesCache !== 'undefined' && balancesCache[it.item_id] ? balancesCache[it.item_id].avgCost : (it.price || 0);
           records.push({ date: inv.date, inv: inv, type: 'مسحوب للتصنيع', loc: inv.from_warehouse_name || 'مخزن', whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: parseFloat(it.qty), price: parseFloat(price) });
        } 
        // --- تحويل بين المخازن (وارد / منصرف) ---
        else if (inv.type === 'transfer') {
           records.push({ date: inv.date, inv: inv, type: 'محول (منصرف)', loc: inv.from_warehouse_name || 'مخزن المصدر', whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: parseFloat(it.qty), price: parseFloat(it.price) || 0 });
           if(inv.status === 'completed' || inv.status === 'posted') {
             records.push({ date: inv.date, inv: inv, type: 'محول (وارد)', loc: inv.to_warehouse_name || 'مخزن الوجهة', whId: inv.to_warehouse_id, qtyIn: parseFloat(it.qty), qtyOut: 0, price: parseFloat(it.price) || 0 });
           }
        }
      }
    });
  });

  // 4. الترتيب الزمني (من الأقدم للأحدث)
  records.sort((a,b) => new Date(a.date) - new Date(b.date));
  
  // 5. الفلترة حسب المخزن المختار
  if (whId && whId !== 'all') {
    records = records.filter(r => String(r.whId) === String(whId));
  }
  
  // 6. الفلترة حسب التاريخ
  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);
  }

  // Unit toggle logic
  const unitToggle = document.getElementById('card-unit-toggle')?.value || 'base';
  let factor = 1;
  let unitName = itemObj ? (itemObj.unit || '') : '';
  if (unitToggle === 'alt' && itemObj && itemObj.alt_unit && itemObj.conv_factor) {
      factor = parseFloat(itemObj.conv_factor) || 1;
      unitName = itemObj.alt_unit;
  }

  // 7. حساب الأرصدة ورسم الجدول
  let runningBalance = 0;
  let totalIn = 0;
  let totalOut = 0;

  if (records.length === 0) {
      tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;">لا توجد حركات لهذا الصنف</td></tr>';
  } else {
      records.forEach(r => {
        runningBalance += (r.qtyIn - r.qtyOut);
        totalIn += r.qtyIn;
        totalOut += r.qtyOut;
        
        const docIdDisplay = r.inv.doc_no ? `${r.inv.doc_no} (#${r.inv.id})` : `#${r.inv.id}`;
        
        const dispIn = r.qtyIn > 0 ? +(r.qtyIn / factor).toFixed(4) : '-';
        const dispOut = r.qtyOut > 0 ? +(r.qtyOut / factor).toFixed(4) : '-';
        const dispBal = +(runningBalance / factor).toFixed(4);
        const dispPrice = r.price > 0 ? Number(r.price * factor).toLocaleString('en-US') : '0';

        tbody.innerHTML += `<tr>
          <td>${new Date(r.date).toLocaleString('ar-EG')}</td>
          <td>${docIdDisplay} <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>${dispPrice}</td>
          <td style="color:var(--success); font-weight:bold;">${dispIn}</td>
          <td style="color:var(--danger); font-weight:bold;">${dispOut}</td>
          <td style="font-weight:bold; background:rgba(255,255,255,0.05);">${dispBal}</td>
        </tr>`;
      });
  }

  // 8. تحديث العدادات العلوية
  document.getElementById('card-total-in').innerText = +(totalIn / factor).toFixed(4) + (unitName ? ' ' + unitName : '');
  document.getElementById('card-total-out').innerText = +(totalOut / factor).toFixed(4) + (unitName ? ' ' + unitName : '');
  document.getElementById('card-final-balance').innerText = +(runningBalance / factor).toFixed(4) + (unitName ? ' ' + unitName : '');
}

const storeOldPopulate = window.populateDropdowns;
window.populateDropdowns = function() {
  if(storeOldPopulate) storeOldPopulate();
  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 && String(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 && String(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 invWhId = String(inv.to_warehouse_id || inv.from_warehouse_id || inv.warehouse_id || '');
  
  let recipients = users.filter(u => {
    const role = (u.role || '').trim();
    if (role === 'مدير عام' || role === 'admin') return true;
    
    if (invWhId) {
        if (String(u.warehouse_id) === invWhId) return true;
        
        let allowed = [];
        if (Array.isArray(u.allowed_warehouses)) allowed = u.allowed_warehouses;
        else if (typeof u.allowed_warehouses === 'string' && u.allowed_warehouses.trim() !== '') {
            allowed = u.allowed_warehouses.split(',').map(s=>s.trim());
        }
        
        if (allowed.some(w => String(w) === invWhId)) return true;
    } else {
        if (role.includes('مخزن') || role.includes('مخازن') || role.includes('امين') || role.includes('أمين')) return true;
    }
    return false;
  });

  if (recipients.length === 0) {
      recipients = users.filter(u => {
          const r = (u.role || '').trim();
          return r.includes('مخزن') || r.includes('مخازن') || r.includes('امين') || r.includes('أمين');
      });
  }
  if (recipients.length === 0) {
      recipients = users;
  }
  
  const msgMap = {
    'purchases': 'إذن استلام مشتريات وارد للمراجعة والاعتماد',
    'sales': 'إذن صرف مبيعات وارد للمراجعة والاعتماد',
    'sales_return': 'مرتجع مبيعات (استلام بضاعة) وارد للمراجعة والاعتماد',
    'purchases_return': 'مرتجع مشتريات (صرف بضاعة) وارد للمراجعة والاعتماد'
  };
  const msg = msgMap[inv.type] || 'مستند جديد يحتاج مراجعة';

  for (let sk of recipients) {
      const exists = existingNotifs.find(n => n.user === sk.username && String(n.invoice_id) === String(inv.id));
      if (!exists) {
          const notifObj = {
            // NO manual id - let IndexedDB autoIncrement assign it
            user: sk.username,
            invoice_id: inv.id,
            message: msg,
            date: new Date().toISOString(),
            read: false
          };
          try {
            await window.DB.add('notifications', notifObj);
            console.log('Notification sent to:', sk.username, '| invoice:', inv.id);
          } catch(notifErr) {
            console.error('Failed to send notification to', sk.username, ':', notifErr);
          }
      }
      await new Promise(r => setTimeout(r, 5));
  }

  await loadData();
  alert('تم الإرسال بنجاح - تم إرسال إشعار لـ ' + recipients.length + ' مستخدم.');
  } finally {
      delete window._sendingInvoiceToStore[invId];
  }
};

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);
  else if (inv.type === 'sales_return') { if(typeof generateSalesReturnJournal === 'function') await generateSalesReturnJournal(inv); }
  else if (inv.type === 'purchases_return') { if(typeof generatePurchasesReturnJournal === 'function') await generatePurchasesReturnJournal(inv); }
  
  if (window.currentStorekeeperReviewNotifDate) {
    await markNotifAsRead(window.currentStorekeeperReviewNotifDate);
  }
  
  closeModal('storekeeper-review-modal');
  if (typeof renderNotifications === 'function') renderNotifications();
  await loadData();
  alert('تم الاعتماد وتحديث المخزون والقيد المحاسبي بنجاح.');
});

window.editInvoiceNote = function(invId) {
  document.getElementById(`inv-notes-edit-container-${invId}`).style.display = 'block';
};
window.saveInvoiceNote = async function(invId) {
  const inv = allInvoices.find(i => String(i.id) === String(invId));
  if(!inv) return;
  const newNotes = document.getElementById(`inv-notes-input-${invId}`).value;
  
  try {
    inv.notes = newNotes;
    await window.DB.update('transactions', inv);
    
    // Bump local version to prevent sync from overwriting
    let localVersions = JSON.parse(localStorage.getItem('erp_db_versions') || '{}');
    localVersions['transactions'] = (Date.now() / 1000) + 2;
    localStorage.setItem('erp_db_versions', JSON.stringify(localVersions));
    
    document.getElementById(`inv-notes-display-${invId}`).innerText = newNotes || 'لا يوجد';
    document.getElementById(`inv-notes-edit-container-${invId}`).style.display = 'none';
    if(window.renderInvoices) window.renderInvoices();
    alert('تم حفظ الملاحظات بنجاح للمستند رقم ' + invId);
  } catch (err) {
    console.error('saveInvoiceNote error:', err);
    alert("حدث خطأ أثناء حفظ الملاحظة: " + (err.message || err));
  }
};
