
// Strip old listeners from app_final.js
["btn-save-sales","btn-save-purchases","btn-save-invoice"].forEach(id => {
    let oldElem = document.getElementById(id);
    if (oldElem) {
        let newElem = oldElem.cloneNode(true);
        oldElem.parentNode.replaceChild(newElem, oldElem);
    }
});

// --- SALES & PURCHASES MODULE ---
function renderSales() {
  const tbody = document.getElementById('sales-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  
  const filterNo = document.getElementById('filter-view-sales-no')?.value?.toLowerCase();
  const filterContact = document.getElementById('filter-view-sales-contact')?.value?.toLowerCase();
  const filterFrom = document.getElementById('filter-view-sales-from')?.value;
  const filterTo = document.getElementById('filter-view-sales-to')?.value;

  let baseList = allInvoices.filter(inv => inv.type === 'sales').sort((a,b) => new Date(b.date) - new Date(a.date));
  let finalData = baseList.filter(t => {
      if (filterFrom && t.date < filterFrom) return false;
      if (filterTo && t.date > filterTo) return false;
      if (filterNo && !(String(t.id).includes(filterNo)) && !(t.ref_no && String(t.ref_no).toLowerCase().includes(filterNo))) return false;
      
      if (filterContact) {
          let cName = '';
          if (t.client_name) cName = t.client_name.toLowerCase();
          else if (t.contact_id) {
              const c = currentContacts.find(x => String(x.id) === String(t.contact_id));
              if (c) cName = c.name.toLowerCase();
          }
          if (!cName.includes(filterContact)) return false;
      }
      return true;
  });

  if (finalData.length === 0) {
    tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; padding: 20px; color:#666;">لا توجد فواتير مبيعات حالياً. اضغط على زر "+ إنشاء فاتورة مبيعات" للبدء.</td></tr>';
    return;
  }
  
  finalData.forEach(inv => {
    let contactName = '-';
    if(inv.contact_id) {
      const c = currentContacts.find(x => x.id === inv.contact_id);
      if(c) contactName = c.name;
    }
    let whName = '-';
    if(inv.from_warehouse_id) {
      const w = currentWarehouses.find(x => x.id === inv.from_warehouse_id);
      if(w) whName = w.name;
    }
    
    let statusSpan = '';
    if(inv.status === 'draft') statusSpan = '<span class="badge" style="background:gray;">مسودة</span>';
    else if(inv.status === 'approved') statusSpan = '<span class="badge" style="background:blue;">موافق عليها</span>';
    else if(inv.status === 'pending_store') statusSpan = '<span class="badge" style="background:orange; color:white;">⏳ معلقة (بالمخزن)</span>';
    else if(inv.status === 'completed') statusSpan = '<span class="badge" style="background:#17a2b8; color:white;">مكتملة مخزنياً</span>';
    else if(inv.status === 'pending_decision') statusSpan = '<span class="badge" style="background:#dc3545; color:white;">بانتظار قرار (عجز)</span>';
    else if(inv.status === 'financial_only') statusSpan = '<span class="badge" style="background:#6f42c1; color:white;">مالية فقط</span>';
    else if(inv.status === 'posted') statusSpan = '<span class="badge" style="background:green;">مُرحلة</span>';
    
                let actions = `<button class="action-btn btn-view" onclick="openSalesModal(${inv.id})">👁️ عرض/تعديل</button>
          <button class="action-btn btn-secondary" style="margin-right:5px;" onclick="window.openQuickNotes('sales', ${inv.id})">📝 ملاحظات</button>`;
      if(currentUser && (currentUser.role === 'مدير عام' || (currentUser.role && currentUser.role.includes('مدير')) || currentUser.username === 'admin')) {
         actions += `<button class="action-btn btn-delete" onclick="deleteInvoice(${inv.id})">🗑️ حذف</button>`;
      }
      if(inv.status === 'draft') {
         actions += `<button class="action-btn" style="background:var(--accent); margin-right:5px;" onclick="sendInvoiceToStore(${inv.id})">📤 إرسال للمخزن</button>`;
      }
      if(inv.status === 'posted') {
         actions += ` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = ${inv.id}; openVoucherModal('receipt', ${inv.id}, ${inv.contact_id}); }">سداد 💵</button>`;
      }

      const taxAmt = parseFloat(inv.tax_amount || inv.tax || 0);
      const taxLabel = taxAmt > 0 ? `<span class="badge" style="background:#8e44ad;">ضريبية (${taxAmt.toLocaleString('en-US')})</span>` : '-';

      tbody.innerHTML += `<tr>
      <td>#${inv.id}</td>
      <td>${new Date(inv.date).toLocaleString('ar-EG')}</td>
      <td>${contactName}</td>
      <td>${whName}</td>
      <td style="font-weight:bold;">${(inv.total||0).toLocaleString('en-US')}</td>
      <td>${taxLabel}</td>
      <td>${statusSpan}</td>
      <td>${actions}</td>
    </tr>`;
  });
}

function renderPurchases() {
  const tbody = document.getElementById('purchases-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  
  const filterNo = document.getElementById('filter-view-purchases-no')?.value?.toLowerCase();
  const filterContact = document.getElementById('filter-view-purchases-contact')?.value?.toLowerCase();
  const filterFrom = document.getElementById('filter-view-purchases-from')?.value;
  const filterTo = document.getElementById('filter-view-purchases-to')?.value;

  let baseList = allInvoices.filter(inv => inv.type === 'purchases').sort((a,b) => new Date(b.date) - new Date(a.date));
  let finalData = baseList.filter(t => {
      if (filterFrom && t.date < filterFrom) return false;
      if (filterTo && t.date > filterTo) return false;
      if (filterNo && !(String(t.id).includes(filterNo)) && !(t.ref_no && String(t.ref_no).toLowerCase().includes(filterNo))) return false;
      
      if (filterContact) {
          let cName = '';
          if (t.client_name) cName = t.client_name.toLowerCase();
          else if (t.contact_id) {
              const c = currentContacts.find(x => String(x.id) === String(t.contact_id));
              if (c) cName = c.name.toLowerCase();
          }
          if (!cName.includes(filterContact)) return false;
      }
      return true;
  });

  if (finalData.length === 0) {
    tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; padding: 20px; color:#666;">لا توجد فواتير مشتريات حالياً. اضغط على زر "+ إنشاء فاتورة مشتريات" للبدء.</td></tr>';
    return;
  }
  
  finalData.forEach(inv => {
    let contactName = '-';
    if(inv.contact_id) {
      const c = currentContacts.find(x => x.id === inv.contact_id);
      if(c) contactName = c.name;
    }
    let whName = '-';
    if(inv.to_warehouse_id) {
      const w = currentWarehouses.find(x => x.id === inv.to_warehouse_id);
      if(w) whName = w.name;
    }
    
    let statusSpan = '';
    if(inv.status === 'draft') statusSpan = '<span class="badge" style="background:gray;">مسودة</span>';
    else if(inv.status === 'approved') statusSpan = '<span class="badge" style="background:blue;">موافق عليها</span>';
    else if(inv.status === 'pending_store') statusSpan = '<span class="badge" style="background:orange; color:white;">⏳ معلقة (بالمخزن)</span>';
    else if(inv.status === 'completed') statusSpan = '<span class="badge" style="background:#17a2b8; color:white;">مكتملة مخزنياً</span>';
    else if(inv.status === 'pending_decision') statusSpan = '<span class="badge" style="background:#dc3545; color:white;">بانتظار قرار (عجز)</span>';
    else if(inv.status === 'financial_only') statusSpan = '<span class="badge" style="background:#6f42c1; color:white;">مالية فقط</span>';
    else if(inv.status === 'posted') statusSpan = '<span class="badge" style="background:green;">مُرحلة</span>';
    
                let actions = `<button class="action-btn btn-view" onclick="openPurchasesModal(${inv.id})">👁️ عرض/تعديل</button>
          <button class="action-btn btn-secondary" style="margin-right:5px;" onclick="window.openQuickNotes('purchases', ${inv.id})">📝 ملاحظات</button>`;
      if(currentUser && (currentUser.role === 'مدير عام' || (currentUser.role && currentUser.role.includes('مدير')) || currentUser.username === 'admin')) {
         actions += `<button class="action-btn btn-delete" onclick="deleteInvoice(${inv.id})">🗑️ حذف</button>`;
      }
      if(inv.status === 'draft') {
         actions += `<button class="action-btn" style="background:var(--accent); margin-right:5px;" onclick="sendInvoiceToStore(${inv.id})">📤 إرسال للمخزن</button>`;
      }
      if(inv.status === 'posted') {
         actions += ` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = ${inv.id}; openVoucherModal('payment', ${inv.id}, ${inv.contact_id}); }">سداد 💵</button>`;
      }

      const taxAmt = parseFloat(inv.tax_amount || inv.tax || 0);
      const taxLabel = taxAmt > 0 ? `<span class="badge" style="background:#8e44ad;">ضريبية (${taxAmt.toLocaleString('en-US')})</span>` : '-';

      tbody.innerHTML += `<tr>
      <td>#${inv.id}</td>
      <td>${new Date(inv.date).toLocaleString('ar-EG')}</td>
      <td>${contactName}</td>
      <td>${whName}</td>
      <td style="font-weight:bold;">${(inv.total||0).toLocaleString('en-US')}</td>
      <td>${taxLabel}</td>
      <td>${statusSpan}</td>
      <td>${actions}</td>
    </tr>`;
  });
}

window.openSalesModal = async function(id = null) {
  if (!currentItems || currentItems.length === 0) currentItems = await window.DB.getAll('items') || [];
  if (!currentProjects || currentProjects.length === 0) currentProjects = await window.DB.getAll('projects') || [];
  if (!currentWarehouses || currentWarehouses.length === 0) currentWarehouses = await window.DB.getAll('warehouses') || [];
  if (!currentContacts || currentContacts.length === 0) currentContacts = await window.DB.getAll('contacts') || [];
  const treasuries = await window.DB.getAll('accounts') || [];
  const treasuryAccounts = treasuries.filter(a => a.type === 'treasury' || a.type === 'bank');
  let tHtml = '<option value="">اختر الخزينة / الحساب</option>';
  treasuryAccounts.forEach(a => { tHtml += '<option value="' + a.id + '">' + a.name + '</option>'; });
  const salesTreasury = document.getElementById('sales-treasury');
  if(salesTreasury) salesTreasury.innerHTML = tHtml;

  document.getElementById('sales-modal-title').innerText = id ? 'عرض / تعديل فاتورة مبيعات' : 'إنشاء فاتورة مبيعات جديدة';
  document.getElementById('edit-sales-id').value = id || '';
  
  const contactSel = document.getElementById('sales-contact');
  contactSel.innerHTML = '<option value="">اختر العميل...</option>' + currentContacts.map(c => `<option value="${c.id}">${c.name} (${c.type || ''})</option>`).join('');
  
  const whSel = document.getElementById('sales-warehouse');
  whSel.innerHTML = '<option value="">اختر المخزن...</option>' + currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  
  const projSel = document.getElementById('sales-project');
  projSel.innerHTML = '<option value="">بدون مشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  
  const itemSel = document.getElementById('sales-item');
  const uniqueTagsSales = [...new Set(currentItems.filter(Boolean).map(i => i.tag).filter(t => t && t.trim() !== ''))];
  let tagOptsSales = '<option value="">-- كل التاجات --</option>';
  uniqueTagsSales.forEach(t => tagOptsSales += `<option value="${t}">${t}</option>`);
  
  let tagSelSales = document.getElementById('sales-item-tag');
  if (itemSel && !tagSelSales) {
      const container = itemSel.parentElement;
      if (container && container.parentElement) {
          const tagDiv = document.createElement('div');
          tagDiv.className = 'flex-col';
          tagDiv.style.maxWidth = '150px';
          tagDiv.innerHTML = '<label>التاج (الفلتر)</label><select id="sales-item-tag" onchange="if(window.filterItemsByTagGen) filterItemsByTagGen(\'sales-item-tag\', \'sales-item\')" style="padding: 10px; border-radius: 5px; border: 1px solid var(--border);">' + tagOptsSales + '</select>';
          container.parentElement.insertBefore(tagDiv, container);
          tagSelSales = document.getElementById('sales-item-tag');
      }
  } else if (tagSelSales) {
      tagSelSales.innerHTML = tagOptsSales;
  }
  if(itemSel) itemSel.innerHTML = '<option value="">اختر الصنف...</option>' + currentItems.filter(Boolean).map(i => `<option value="${i.id}">${i.name} (${i.unit || 'وحدة'})</option>`).join('');
  
  const inv = id ? allInvoices.find(x => String(x.id) === String(id)) : null;
  
  if(inv) {
    if(document.getElementById('sales-date')) document.getElementById('sales-date').value = inv.date || '';
    if(contactSel) contactSel.value = inv.contact_id || '';
    if(whSel) whSel.value = inv.from_warehouse_id || '';
    if(projSel) projSel.value = inv.project_id || '';
    if(document.getElementById('sales-status')) document.getElementById('sales-status').value = inv.status || 'draft';
    if(document.getElementById('sales-tax-rate')) document.getElementById('sales-tax-rate').value = inv.tax_rate || 0;
    if(document.getElementById('sales-notes')) document.getElementById('sales-notes').value = inv.notes || '';
    currentSalesLines = inv.items ? JSON.parse(JSON.stringify(inv.items)) : [];
  } else {
    document.getElementById('edit-sales-id').value = '';
    if(document.getElementById('sales-date')) document.getElementById('sales-date').value = new Date().toISOString().slice(0,16);
    if(document.getElementById('sales-status')) document.getElementById('sales-status').value = 'draft';
    if(document.getElementById('sales-tax-rate')) document.getElementById('sales-tax-rate').value = 0;
    if(document.getElementById('sales-notes')) document.getElementById('sales-notes').value = '';
    currentSalesLines = [];
  }
  
  if(document.getElementById('sales-qty')) document.getElementById('sales-qty').value = 1;
  if(document.getElementById('sales-price')) document.getElementById('sales-price').value = 0;
  if(document.getElementById('sales-discount')) document.getElementById('sales-discount').value = 0;

  renderSalesLines();
  showModal('sales-modal');
}

window.addSalesLine = function() {
  const itemIdStr = document.getElementById('sales-item').value;
  if(!itemIdStr) { alert('اختر صنفاً أولاً'); return; }
  
  const itemId = parseInt(itemIdStr);
  let qty = parseFloat(document.getElementById('sales-qty').value) || 1;
  let price = parseFloat(document.getElementById('sales-price').value) || 0;
  const discount = parseFloat(document.getElementById('sales-discount').value) || 0;
    const discountTypeEl = document.getElementById('sales-discount-type');
    const discount_type = discountTypeEl ? discountTypeEl.value : 'percent';
    
    const unitSel = document.getElementById('sales-unit');
    const factor = unitSel && unitSel.options[unitSel.selectedIndex] ? parseFloat(unitSel.options[unitSel.selectedIndex].getAttribute('data-factor') || 1) : 1;
    let displayQtyStr = qty.toString();
    if (factor > 1 && unitSel) {
        const altUnitText = unitSel.options[unitSel.selectedIndex].text.split(' ')[0];
        displayQtyStr = qty + ' ' + altUnitText + ' = ' + (qty * factor);
        qty = qty * factor;
        price = price / factor;
    }
    
    currentSalesLines.push({ item_id: itemId, qty, price, discount, discount_type, display_qty: displayQtyStr });
  
  document.getElementById('sales-item').value = '';
  document.getElementById('sales-qty').value = 1;
  document.getElementById('sales-price').value = 0;
  document.getElementById('sales-discount').value = 0;
  
  renderSalesLines();
}

window.removeSalesLine = function(index) {
  currentSalesLines.splice(index, 1);
  renderSalesLines();
}

function renderSalesLines() {
  const tbody = document.getElementById('sales-lines-tbody');
  tbody.innerHTML = '';
  
  let subtotal = 0;
  let totalDiscountValue = 0;
  
  currentSalesLines.forEach((line, idx) => {
    const item = currentItems.find(i => i.id === line.item_id);
    const itemName = item ? item.name : '-';
    
    const lineTotalBeforeDiscount = line.qty * line.price;
    let lineDiscountValue = 0;
    const isPercent = line.discount_type === 'percent' || !line.discount_type;
    if (isPercent) {
        lineDiscountValue = lineTotalBeforeDiscount * (line.discount / 100);
    } else {
        lineDiscountValue = line.discount || 0;
    }
    if (lineDiscountValue > lineTotalBeforeDiscount) lineDiscountValue = lineTotalBeforeDiscount;
    const lineTotal = lineTotalBeforeDiscount - lineDiscountValue;
    
    subtotal += lineTotalBeforeDiscount;
    totalDiscountValue += lineDiscountValue;
    
    tbody.innerHTML += `<tr>
      <td>${itemName}</td>
      <td>${line.display_qty || line.qty}</td>
      <td>${line.price}</td>
      <td>${line.discount} ${(line.discount_type === 'percent' || !line.discount_type) ? '%' : 'قيمة'}</td>
      <td>${lineTotal.toLocaleString('ar-EG', {minimumFractionDigits:2})}</td>
      <td><button class="action-btn btn-delete" onclick="removeSalesLine(${idx})">❌</button></td>
    </tr>`;
  });
  
  document.getElementById('sales-subtotal').innerText = subtotal.toLocaleString('ar-EG', {minimumFractionDigits:2});
  document.getElementById('sales-total-discount').innerText = totalDiscountValue.toLocaleString('ar-EG', {minimumFractionDigits:2});
  const net = subtotal - totalDiscountValue;
  document.getElementById('sales-net-total').innerText = net.toLocaleString('ar-EG', {minimumFractionDigits:2});

  // Tax calculation
  const taxRate = parseFloat(document.getElementById('sales-tax-rate')?.value) || 0;
  const taxAmount = net * (taxRate / 100);
  const grandTotal = net + taxAmount;
  if(document.getElementById('sales-tax-amount')) document.getElementById('sales-tax-amount').innerText = taxAmount.toLocaleString('ar-EG', {minimumFractionDigits:2});
  if(document.getElementById('sales-grand-total')) document.getElementById('sales-grand-total').innerText = grandTotal.toLocaleString('ar-EG', {minimumFractionDigits:2});

  const idStr = document.getElementById('edit-sales-id').value;
  let paid = 0;
  if(idStr) {
    const existing = allInvoices.find(i => String(i.id) === String(idStr));
    const id = existing ? existing.id : idStr;
    const linkedVouchers = allInvoices.filter(t => (t.type === 'receipt' || t.type === 'payment') && t.status === 'posted' && String(t.linked_invoice_id) === String(id));
    paid = linkedVouchers.reduce((sum, v) => sum + (parseFloat(v.amount) || 0), 0);
    
    const container = document.getElementById('sales-linked-vouchers-container');
    const list = document.getElementById('sales-linked-vouchers-list');
    if (linkedVouchers.length > 0) {
        if(container) container.style.display = 'block';
        if(list) list.innerHTML = linkedVouchers.map(v => {
            const accName = currentAccounts.find(a => a.id == v.treasury_account_id)?.name || 'غير محدد';
            return `<li>🔹 سند ${v.type === 'receipt' ? 'قبض' : 'صرف'} رقم <strong>${v.id}</strong> بمبلغ <strong>${v.amount}</strong> (الخزينة: ${accName}) بتاريخ ${v.date.split('T')[0]}</li>`;
        }).join('');
    } else {
        if(container) container.style.display = 'none';
        if(list) list.innerHTML = '';
    }
  } else {
    const container = document.getElementById('sales-linked-vouchers-container');
    if(container) container.style.display = 'none';
  }
  
  if(document.getElementById('sales-paid-total')) document.getElementById('sales-paid-total').innerText = paid.toLocaleString('ar-EG', {minimumFractionDigits:2});
  if(document.getElementById('sales-remaining')) document.getElementById('sales-remaining').innerText = Math.max(0, grandTotal - paid).toLocaleString('ar-EG', {minimumFractionDigits:2});
}

document.getElementById('btn-save-sales')?.addEventListener('click', async () => {
  const idStr = document.getElementById('edit-sales-id').value;
  const date = document.getElementById('sales-date').value;
  const contact_id = parseInt(document.getElementById('sales-contact').value) || null;
  const from_warehouse_id = parseInt(document.getElementById('sales-warehouse').value) || null;
  const project_id = parseInt(document.getElementById('sales-project').value) || null;
  const status = document.getElementById('sales-status').value;
  
  if(!contact_id) { alert('يجب تحديد العميل'); return; }
  if(!from_warehouse_id) { alert('يجب تحديد المخزن الصادر منه البضاعة'); return; }
  if(currentSalesLines.length === 0) { alert('يجب إضافة أصناف للفاتورة'); return; }
  
  // Calculate total
  let netTotal = 0;
    currentSalesLines.forEach(line => {
        const tot = (parseFloat(line.qty) || 0) * (parseFloat(line.price) || 0);
        let disc = 0;
        const dType = line.discount_type || line.discountType || 'percent';
        const dVal = parseFloat(line.discount) || 0;
        if (dType === 'percent') {
            disc = tot * (dVal / 100);
        } else {
            disc = dVal;
        }
        if (disc > tot) disc = tot;
        netTotal += (tot - disc);
    });
  
  // Tax calculation
  const taxRate = parseFloat(document.getElementById('sales-tax-rate')?.value) || 0;
  const taxAmount = netTotal * (taxRate / 100);
  const grandTotal = netTotal + taxAmount;

  const notesEl = document.getElementById('sales-notes');
  const existingInv = idStr ? allInvoices.find(x => String(x.id) === String(idStr)) : null;
  const wasAlreadyPosted = existingInv && (existingInv.status === 'posted' || existingInv.status === 'financial_only');

  if (wasAlreadyPosted) {
      existingInv.notes = notesEl ? notesEl.value : existingInv.notes;
      try {
          await window.DB.update('transactions', existingInv);
          closeModal('sales-modal');
          await loadData();
          alert('تم حفظ الملاحظات بنجاح (لا يمكن تعديل تفاصيل الفاتورة بعد اعتمادها).');
      } catch(e) { alert("حدث خطأ أثناء الحفظ: " + e.message); }
      return;
  }

  const obj = {
    type: 'sales',
    date,
    contact_id,
    from_warehouse_id,
    to_warehouse_id: null,
    project_id,
    status,
    items: currentSalesLines,
    total: grandTotal,
    net_before_tax: netTotal,
    tax_rate: taxRate,
    tax_amount: taxAmount,
    notes: notesEl ? notesEl.value : (existingInv ? existingInv.notes || '' : ''),
    user: currentUser.username,
    created_at: new Date().toISOString()
  };
  
  try {
    if(idStr) {
      const existing = allInvoices.find(i => String(i.id) === String(idStr));
      obj.id = existing ? existing.id : idStr;
      await window.DB.update('transactions', obj);
      
      // Auto-Journal logic for posted
      if(status === 'posted' || status === 'financial_only') {
         await generateSalesJournal(obj);
         if (window.processInvoicePayment) await window.processInvoicePayment(obj, 'sales');
      }
      if(status === 'pending_store' && typeof window.sendInvoiceToStore === 'function') {
         await window.sendInvoiceToStore(obj.id);
      }
    } else {
      const newId = await window.DB.add('transactions', obj);
      obj.id = newId;
      if(status === 'posted' || status === 'financial_only') {
         await generateSalesJournal(obj);
         if (window.processInvoicePayment) await window.processInvoicePayment(obj, 'sales');
      }
      if(status === 'pending_store' && typeof window.sendInvoiceToStore === 'function') {
         await window.sendInvoiceToStore(newId);
      }
    }
    
    closeModal('sales-modal');
    await loadData();
    alert('تم حفظ الفاتورة بنجاح!');
  } catch(e) { alert("حدث خطأ أثناء الحفظ: " + e.message); }
});

async function generateSalesJournal(invoice) {
    const allJournals = await window.DB.getAll('journal_entries') || [];
    const existingJList = allJournals.filter(j => j.reference === `فاتورة مبيعات #${invoice.id}`);
    for (let ej of existingJList) {
        if (window.DB && window.DB.remove) await window.DB.remove('journal_entries', ej.id);
    }
    
    let clientAcc = currentAccounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل'));
    let salesAcc = currentAccounts.find(a => a.name === 'إيرادات المبيعات' || a.name === 'إيرادات مبيعات');
    let invAcc = currentAccounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
    let cogsAcc = currentAccounts.find(a => a.name.includes('تكلفة') && (a.name.includes('بضاع') || a.name.includes('مباع') || a.name.includes('مبيع')));
    
    // Resolve missing accounts safely
    if (typeof window.resolveSystemAccount === 'function') {
        if(!clientAcc) clientAcc = await window.resolveSystemAccount('العملاء', ['أصول متداولة', 'الأصول'], 'assets');
        if(!salesAcc) salesAcc = await window.resolveSystemAccount('إيرادات المبيعات', ['الإيرادات', 'إيرادات', 'ايرادات'], 'revenues');
        if(!invAcc) invAcc = await window.resolveSystemAccount('مخزون البضاعة', ['أصول متداولة', 'الأصول'], 'assets');
        if(!cogsAcc) cogsAcc = await window.resolveSystemAccount('تكلفة البضاعة المباعة', ['المصروفات', 'مصروفات'], 'expenses');
    }

    let discountAcc = currentAccounts.find(a => a.name === 'خصم مسموح به' || a.name === 'الخصم المسموح به');
    if(!discountAcc && typeof window.resolveSystemAccount === 'function') {
        discountAcc = await window.resolveSystemAccount('الخصم المسموح به', ['المصروفات', 'مصروفات'], 'expenses');
    }

    let taxAcc = currentAccounts.find(a => a.name.includes('ضريب') || a.name.includes('ضرائب'));
    if(!taxAcc && typeof window.resolveSystemAccount === 'function') {
        taxAcc = await window.resolveSystemAccount('الضرائب', ['الخصوم', 'التزامات'], 'liabilities');
    }

    if(!clientAcc || !salesAcc) {
       alert('تحذير: لا يمكن توليد قيد آلي لأنه لم يتم العثور على حساب "العملاء" أو "إيرادات المبيعات" في دليل الحسابات.');
       return;
    }
    
    // Calculate total discount and COGS
    let totalDiscount = 0;
      let totalCogs = 0;
      let computedGross = 0;
      (invoice.items || []).forEach(line => {
          const qty = parseFloat(line.qty) || 0;
          const price = parseFloat(line.price) || 0;
          const tot = qty * price;
          computedGross += tot;
          
          let disc = 0;
          const dType = line.discount_type || line.discountType || 'percent';
          const dVal = parseFloat(line.discount) || 0;
          
          if (dType === 'percent') {
              disc = tot * (dVal / 100);
          } else {
              disc = dVal;
          }
          if (disc > tot) disc = tot;
          totalDiscount += disc;
  
          let balancesToUse = typeof window.balancesCache !== 'undefined' ? window.balancesCache : (typeof balancesCache !== 'undefined' ? balancesCache : null);
          if(balancesToUse) {
              let b = balancesToUse[line.item_id];
              let avgCost = b ? b.avgCost : 0;
              totalCogs += (qty * avgCost);
          }
      });
  
      const grossTotal = computedGross;
      const netTotal = computedGross - totalDiscount;
      const taxAmount = parseFloat(invoice.tax_amount) || 0;
      const grandTotal = netTotal + taxAmount;

    let contactName = '';
    if(typeof currentContacts !== 'undefined') {
        let cc = currentContacts.find(x => String(x.id) === String(invoice.contact_id));
        if(cc) contactName = cc.name;
    }
    if(!contactName && window.DB && window.DB.getAll) {
        let allC = await window.DB.getAll('contacts');
        let cc = allC.find(x => String(x.id) === String(invoice.contact_id));
        if(cc) contactName = cc.name;
    }
    let contactSuffix = contactName ? ` - ${contactName}` : '';

    let totalDebit = 0;

    const journal = {
      id: Date.now() + Math.floor(Math.random()*1000),
      date: invoice.date.split('T')[0],
      reference: `فاتورة مبيعات #${invoice.id}`,
      desc: `فاتورة مبيعات رقم ${invoice.id}${contactSuffix}`,
      status: 'posted',
      created_by: 'النظام',
      total: 0, // will calculate below
      rows: []
    };

    // Client Debit (Grand Total)
    journal.rows.push({ account_id: clientAcc.id, debit: grandTotal, credit: 0, project_id: invoice.project_id, contact_id: invoice.contact_id || null, notes: `قيمة فاتورة مبيعات ${invoice.id}${contactSuffix}` });
    totalDebit += grandTotal;

    // Discount Debit
    if (totalDiscount > 0 && discountAcc) {
        journal.rows.push({ account_id: discountAcc.id, debit: totalDiscount, credit: 0, project_id: invoice.project_id, contact_id: invoice.contact_id || null, notes: `خصم مسموح به فاتورة مبيعات ${invoice.id}${contactSuffix}` });
        totalDebit += totalDiscount;
    }

    // Sales Credit (Gross)
    journal.rows.push({ account_id: salesAcc.id, debit: 0, credit: grossTotal, project_id: invoice.project_id, notes: `إيراد فاتورة مبيعات ${invoice.id}` });

    // Tax Credit
    if (taxAmount > 0 && taxAcc) {
        journal.rows.push({ account_id: taxAcc.id, debit: 0, credit: taxAmount, project_id: invoice.project_id, notes: `ضريبة فاتورة مبيعات ${invoice.id}` });
    }

    // COGS
    if (totalCogs > 0 && cogsAcc && invAcc) {
        journal.rows.push({ account_id: cogsAcc.id, debit: totalCogs, credit: 0, project_id: invoice.project_id, notes: `تكلفة بضاعة مباعة فاتورة ${invoice.id}` });
        journal.rows.push({ account_id: invAcc.id, debit: 0, credit: totalCogs, project_id: invoice.project_id, notes: `منصرف مخزون مبيعات ${invoice.id}` });
        totalDebit += totalCogs;
    }

    journal.total = totalDebit;
    await window.DB.add('journal_entries', journal);
}

// ==========================================
// PURCHASES
// ==========================================
window.openPurchasesModal = async function(id = null) {
  if (!currentItems || currentItems.length === 0) currentItems = await window.DB.getAll('items') || [];
  if (!currentProjects || currentProjects.length === 0) currentProjects = await window.DB.getAll('projects') || [];
  if (!currentWarehouses || currentWarehouses.length === 0) currentWarehouses = await window.DB.getAll('warehouses') || [];
  if (!currentContacts || currentContacts.length === 0) currentContacts = await window.DB.getAll('contacts') || [];
  const treasuries = await window.DB.getAll('accounts') || [];
  const treasuryAccounts = treasuries.filter(a => a.type === 'treasury' || a.type === 'bank');
  let tHtml = '<option value="">اختر الخزينة / الحساب</option>';
  treasuryAccounts.forEach(a => { tHtml += '<option value="' + a.id + '">' + a.name + '</option>'; });
  const purchTreasury = document.getElementById('purchases-treasury');
  if(purchTreasury) purchTreasury.innerHTML = tHtml;

  document.getElementById('purchases-modal-title').innerText = id ? 'عرض / تعديل فاتورة مشتريات' : 'إنشاء فاتورة مشتريات جديدة';
  document.getElementById('edit-purchases-id').value = id || '';
  
  const contactSel = document.getElementById('purchases-contact');
  contactSel.innerHTML = '<option value="">اختر المورد...</option>' + currentContacts.map(c => `<option value="${c.id}">${c.name} (${c.type || ''})</option>`).join('');
  
  const whSel = document.getElementById('purchases-warehouse');
  whSel.innerHTML = '<option value="">اختر المخزن...</option>' + currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  
  const projSel = document.getElementById('purchases-project');
  projSel.innerHTML = '<option value="">بدون مشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  
  const itemSel = document.getElementById('purchases-item');
  const uniqueTagsPurch = [...new Set(currentItems.filter(Boolean).map(i => i.tag).filter(t => t && t.trim() !== ''))];
  let tagOptsPurch = '<option value="">-- كل التاجات --</option>';
  uniqueTagsPurch.forEach(t => tagOptsPurch += `<option value="${t}">${t}</option>`);
  
  let tagSelPurch = document.getElementById('purchases-item-tag');
  if (itemSel && !tagSelPurch) {
      const container = itemSel.parentElement;
      if (container && container.parentElement) {
          const tagDiv = document.createElement('div');
          tagDiv.className = 'flex-col';
          tagDiv.style.maxWidth = '150px';
          tagDiv.innerHTML = '<label>التاج (الفلتر)</label><select id="purchases-item-tag" onchange="if(window.filterItemsByTagGen) filterItemsByTagGen(\'purchases-item-tag\', \'purchases-item\')" style="padding: 10px; border-radius: 5px; border: 1px solid var(--border);">' + tagOptsPurch + '</select>';
          container.parentElement.insertBefore(tagDiv, container);
          tagSelPurch = document.getElementById('purchases-item-tag');
      }
  } else if (tagSelPurch) {
      tagSelPurch.innerHTML = tagOptsPurch;
  }
  if(itemSel) itemSel.innerHTML = '<option value="">اختر الصنف...</option>' + currentItems.filter(Boolean).map(i => `<option value="${i.id}">${i.name} (${i.unit || 'وحدة'})</option>`).join('');
  
  const inv = id ? allInvoices.find(x => String(x.id) === String(id)) : null;
  
  if(inv) {
    if(document.getElementById('purchases-date')) document.getElementById('purchases-date').value = inv.date || '';
    if(contactSel) contactSel.value = inv.contact_id || '';
    if(whSel) whSel.value = inv.to_warehouse_id || '';
    if(projSel) projSel.value = inv.project_id || '';
    if(document.getElementById('purchases-status')) document.getElementById('purchases-status').value = inv.status || 'draft';
    if(document.getElementById('purchases-tax-rate')) document.getElementById('purchases-tax-rate').value = inv.tax_rate || 0;
    if(document.getElementById('purchases-notes')) document.getElementById('purchases-notes').value = inv.notes || '';
    currentPurchasesLines = inv.items ? JSON.parse(JSON.stringify(inv.items)) : [];
  } else {
    document.getElementById('edit-purchases-id').value = '';
    if(document.getElementById('purchases-date')) document.getElementById('purchases-date').value = new Date().toISOString().slice(0,16);
    if(document.getElementById('purchases-status')) document.getElementById('purchases-status').value = 'draft';
    if(document.getElementById('purchases-tax-rate')) document.getElementById('purchases-tax-rate').value = 0;
    if(document.getElementById('purchases-notes')) document.getElementById('purchases-notes').value = '';
    currentPurchasesLines = [];
  }
  
  if(document.getElementById('purchases-qty')) document.getElementById('purchases-qty').value = 1;
  if(document.getElementById('purchases-price')) document.getElementById('purchases-price').value = 0;
  if(document.getElementById('purchases-discount')) document.getElementById('purchases-discount').value = 0;

  renderPurchasesLines();
  showModal('purchases-modal');
}

window.addPurchasesLine = function() {
  const itemIdStr = document.getElementById('purchases-item').value;
  if(!itemIdStr) { alert('اختر صنفاً أولاً'); return; }
  
  const itemId = parseInt(itemIdStr);
  let qty = parseFloat(document.getElementById('purchases-qty').value) || 1;
  let price = parseFloat(document.getElementById('purchases-price').value) || 0;
  const discount = parseFloat(document.getElementById('purchases-discount').value) || 0;
    const discountTypeEl = document.getElementById('purchases-discount-type');
    const discount_type = discountTypeEl ? discountTypeEl.value : 'percent';
    
    const unitSel = document.getElementById('purchases-unit');
    const factor = unitSel && unitSel.options[unitSel.selectedIndex] ? parseFloat(unitSel.options[unitSel.selectedIndex].getAttribute('data-factor') || 1) : 1;
    let displayQtyStr = qty.toString();
    if (factor > 1 && unitSel) {
        const altUnitText = unitSel.options[unitSel.selectedIndex].text.split(' ')[0];
        displayQtyStr = qty + ' ' + altUnitText + ' = ' + (qty * factor);
        qty = qty * factor;
        price = price / factor;
    }
    
    currentPurchasesLines.push({ item_id: itemId, qty, price, discount, discount_type, display_qty: displayQtyStr });
  
  document.getElementById('purchases-item').value = '';
  document.getElementById('purchases-qty').value = 1;
  document.getElementById('purchases-price').value = 0;
  document.getElementById('purchases-discount').value = 0;
  
  renderPurchasesLines();
}

window.removePurchasesLine = function(index) {
  currentPurchasesLines.splice(index, 1);
  renderPurchasesLines();
}

function renderPurchasesLines() {
  const tbody = document.getElementById('purchases-lines-tbody');
  tbody.innerHTML = '';
  
  let subtotal = 0;
  let totalDiscountValue = 0;
  
  currentPurchasesLines.forEach((line, idx) => {
    const item = currentItems.find(i => i.id === line.item_id);
    const itemName = item ? item.name : '-';
    
    const lineTotalBeforeDiscount = line.qty * line.price;
    let lineDiscountValue = 0;
    const isPercent = line.discount_type === 'percent' || !line.discount_type;
    if (isPercent) {
        lineDiscountValue = lineTotalBeforeDiscount * (line.discount / 100);
    } else {
        lineDiscountValue = line.discount || 0;
    }
    if (lineDiscountValue > lineTotalBeforeDiscount) lineDiscountValue = lineTotalBeforeDiscount;
    const lineTotal = lineTotalBeforeDiscount - lineDiscountValue;
    
    subtotal += lineTotalBeforeDiscount;
    totalDiscountValue += lineDiscountValue;
    
    tbody.innerHTML += `<tr>
      <td>${itemName}</td>
      <td>${line.display_qty || line.qty}</td>
      <td>${line.price}</td>
      <td>${line.discount} ${(line.discount_type === 'percent' || !line.discount_type) ? '%' : 'قيمة'}</td>
      <td>${lineTotal.toLocaleString('ar-EG', {minimumFractionDigits:2})}</td>
      <td><button class="action-btn btn-delete" onclick="removePurchasesLine(${idx})">❌</button></td>
    </tr>`;
  });
  
  document.getElementById('purchases-subtotal').innerText = subtotal.toLocaleString('ar-EG', {minimumFractionDigits:2});
  document.getElementById('purchases-total-discount').innerText = totalDiscountValue.toLocaleString('ar-EG', {minimumFractionDigits:2});
  const net = subtotal - totalDiscountValue;
  document.getElementById('purchases-net-total').innerText = net.toLocaleString('ar-EG', {minimumFractionDigits:2});

  // Tax calculation
  const taxRate = parseFloat(document.getElementById('purchases-tax-rate')?.value) || 0;
  const taxAmount = net * (taxRate / 100);
  const grandTotal = net + taxAmount;
  if(document.getElementById('purchases-tax-amount')) document.getElementById('purchases-tax-amount').innerText = taxAmount.toLocaleString('ar-EG', {minimumFractionDigits:2});
  if(document.getElementById('purchases-grand-total')) document.getElementById('purchases-grand-total').innerText = grandTotal.toLocaleString('ar-EG', {minimumFractionDigits:2});

  const idStr = document.getElementById('edit-purchases-id').value;
  let paid = 0;
  if(idStr) {
    const existing = allInvoices.find(i => String(i.id) === String(idStr));
    const id = existing ? existing.id : idStr;
    const linkedVouchers = allInvoices.filter(t => (t.type === 'receipt' || t.type === 'payment') && t.status === 'posted' && String(t.linked_invoice_id) === String(id));
    paid = linkedVouchers.reduce((sum, v) => sum + (parseFloat(v.amount) || 0), 0);
    
    const container = document.getElementById('purchases-linked-vouchers-container');
    const list = document.getElementById('purchases-linked-vouchers-list');
    if (linkedVouchers.length > 0) {
        if(container) container.style.display = 'block';
        if(list) list.innerHTML = linkedVouchers.map(v => {
            const accName = currentAccounts.find(a => a.id == v.treasury_account_id)?.name || 'غير محدد';
            return `<li>🔹 سند ${v.type === 'receipt' ? 'قبض' : 'صرف'} رقم <strong>${v.id}</strong> بمبلغ <strong>${v.amount}</strong> (الخزينة: ${accName}) بتاريخ ${v.date.split('T')[0]}</li>`;
        }).join('');
    } else {
        if(container) container.style.display = 'none';
        if(list) list.innerHTML = '';
    }
  } else {
    const container = document.getElementById('purchases-linked-vouchers-container');
    if(container) container.style.display = 'none';
  }

  if(document.getElementById('purchases-paid-total')) document.getElementById('purchases-paid-total').innerText = paid.toLocaleString('ar-EG', {minimumFractionDigits:2});
  if(document.getElementById('purchases-remaining')) document.getElementById('purchases-remaining').innerText = Math.max(0, grandTotal - paid).toLocaleString('ar-EG', {minimumFractionDigits:2});
}

document.getElementById('btn-save-purchases')?.addEventListener('click', async () => {
  const idStr = document.getElementById('edit-purchases-id').value;
  const date = document.getElementById('purchases-date').value;
  const contact_id = parseInt(document.getElementById('purchases-contact').value) || null;
  const to_warehouse_id = parseInt(document.getElementById('purchases-warehouse').value) || null;
  const project_id = parseInt(document.getElementById('purchases-project').value) || null;
  const status = document.getElementById('purchases-status').value;
  
  if(!contact_id) { alert('يجب تحديد المورد'); return; }
  if(!to_warehouse_id) { alert('يجب تحديد المخزن الوارد إليه البضاعة'); return; }
  if(currentPurchasesLines.length === 0) { alert('يجب إضافة أصناف للفاتورة'); return; }
  
  let netTotal = 0;
    currentPurchasesLines.forEach(line => {
        const tot = (parseFloat(line.qty) || 0) * (parseFloat(line.price) || 0);
        let disc = 0;
        const dType = line.discount_type || line.discountType || 'percent';
        const dVal = parseFloat(line.discount) || 0;
        if (dType === 'percent') {
            disc = tot * (dVal / 100);
        } else {
            disc = dVal;
        }
        if (disc > tot) disc = tot;
        netTotal += (tot - disc);
    });
  
  // Tax calculation
  const taxRate = parseFloat(document.getElementById('purchases-tax-rate')?.value) || 0;
  const taxAmount = netTotal * (taxRate / 100);
  const grandTotal = netTotal + taxAmount;

  const notesEl = document.getElementById('purchases-notes');
  const existingInv = idStr ? allInvoices.find(x => String(x.id) === String(idStr)) : null;
  const wasAlreadyPosted = existingInv && (existingInv.status === 'posted' || existingInv.status === 'financial_only');

  if (wasAlreadyPosted) {
      existingInv.notes = notesEl ? notesEl.value : existingInv.notes;
      try {
          await window.DB.update('transactions', existingInv);
          closeModal('purchases-modal');
          await loadData();
          alert('تم حفظ الملاحظات بنجاح (لا يمكن تعديل تفاصيل الفاتورة بعد اعتمادها).');
      } catch(e) { alert("حدث خطأ أثناء الحفظ: " + e.message); }
      return;
  }

  const obj = {
    type: 'purchases',
    date,
    contact_id,
    from_warehouse_id: null,
    to_warehouse_id,
    project_id,
    status,
    items: currentPurchasesLines,
    total: grandTotal,
    net_before_tax: netTotal,
    tax_rate: taxRate,
    tax_amount: taxAmount,
    notes: notesEl ? notesEl.value : (existingInv ? existingInv.notes || '' : ''),
    user: currentUser.username,
    created_at: new Date().toISOString()
  };
  
  try {
    if(idStr) {
      const existing = allInvoices.find(i => String(i.id) === String(idStr));
      obj.id = existing ? existing.id : idStr;
      await window.DB.update('transactions', obj);
      if(status === 'posted' || status === 'financial_only') {
         await generatePurchasesJournal(obj);
         if (window.processInvoicePayment) await window.processInvoicePayment(obj, 'purchases');
      }
      if(status === 'pending_store' && typeof window.sendInvoiceToStore === 'function') {
         await window.sendInvoiceToStore(obj.id);
      }
    } else {
      const newId = await window.DB.add('transactions', obj);
      obj.id = newId;
      if(status === 'posted' || status === 'financial_only') {
         await generatePurchasesJournal(obj);
         if (window.processInvoicePayment) await window.processInvoicePayment(obj, 'purchases');
      }
      if(status === 'pending_store' && typeof window.sendInvoiceToStore === 'function') {
         await window.sendInvoiceToStore(newId);
      }
    }
    
    closeModal('purchases-modal');
    await loadData();
    alert('تم حفظ الفاتورة بنجاح!');
  } catch(e) { alert("حدث خطأ أثناء الحفظ: " + e.message); }
});

async function generatePurchasesJournal(invoice) {
    const allJournals = await window.DB.getAll('journal_entries') || [];
    const existingJList = allJournals.filter(j => j.reference === `فاتورة مشتريات #${invoice.id}`);
    for (let ej of existingJList) {
        if (window.DB && window.DB.remove) await window.DB.remove('journal_entries', ej.id);
    }
    
    let supplierAcc = currentAccounts.find(a => a.name.includes('موردين') || a.name.includes('مورد'));
    let invAcc = currentAccounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
    let discountAcc = currentAccounts.find(a => a.name === 'خصم مكتسب' || a.name === 'الخصم المكتسب');
    let taxAcc = currentAccounts.find(a => a.name.includes('ضريب') || a.name.includes('ضرائب'));

    if (typeof window.resolveSystemAccount === 'function') {
        if(!supplierAcc) supplierAcc = await window.resolveSystemAccount('الموردين', ['التزامات', 'خصوم'], 'liabilities');
        if(!invAcc) invAcc = await window.resolveSystemAccount('مخزون البضاعة', ['أصول متداولة', 'الأصول'], 'assets');
        if(!discountAcc) discountAcc = await window.resolveSystemAccount('الخصم المكتسب', ['الإيرادات', 'إيرادات'], 'revenues');
        if(!taxAcc) taxAcc = await window.resolveSystemAccount('الضرائب', ['الخصوم', 'التزامات'], 'liabilities');
    }
    
    if(!supplierAcc || !invAcc) {
       alert('تحذير: لا يمكن توليد قيد آلي لأنه لم يتم العثور على حساب "الموردين" أو "المخزون" في دليل الحسابات.');
       return;
    }

    let totalDiscount = 0;
    let computedGross = 0;
    (invoice.items || []).forEach(line => {
        const qty = parseFloat(line.qty) || 0;
        const price = parseFloat(line.price) || 0;
        const tot = qty * price;
        computedGross += tot;
        
        let disc = 0;
        const dType = line.discount_type || line.discountType || 'percent';
        const dVal = parseFloat(line.discount) || 0;
        
        if (dType === 'percent') {
            disc = tot * (dVal / 100);
        } else {
            disc = dVal;
        }
        if (disc > tot) disc = tot;
        totalDiscount += disc;
    });

    const grossTotal = computedGross;
    const netTotal = computedGross - totalDiscount;
    const taxAmount = parseFloat(invoice.tax_amount) || 0;
    const grandTotal = netTotal + taxAmount;

    let contactName = '';
    if(typeof currentContacts !== 'undefined') {
        let cc = currentContacts.find(x => String(x.id) === String(invoice.contact_id));
        if(cc) contactName = cc.name;
    }
    if(!contactName && window.DB && window.DB.getAll) {
        let allC = await window.DB.getAll('contacts');
        let cc = allC.find(x => String(x.id) === String(invoice.contact_id));
        if(cc) contactName = cc.name;
    }
    let contactSuffix = contactName ? ` - المورد: ${contactName}` : '';

    let totalDebit = 0;

    const journal = {
      id: Date.now() + Math.floor(Math.random()*1000),
      date: invoice.date.split('T')[0],
      reference: `فاتورة مشتريات #${invoice.id}`,
      desc: `فاتورة مشتريات رقم ${invoice.id}${contactSuffix}`,
      status: 'posted',
      created_by: 'النظام',
      total: 0,
      rows: []
    };

    // Inventory Debit (Gross)
    journal.rows.push({ account_id: invAcc.id, debit: grossTotal, credit: 0, project_id: invoice.project_id, notes: `قيمة مخزون مشتريات ${invoice.id}` });
    totalDebit += grossTotal;

    // Tax Debit
    if (taxAmount > 0 && taxAcc) {
        journal.rows.push({ account_id: taxAcc.id, debit: taxAmount, credit: 0, project_id: invoice.project_id, notes: `ضريبة فاتورة مشتريات ${invoice.id}` });
        totalDebit += taxAmount;
    }

    // Supplier Credit (Grand Total)
    journal.rows.push({ account_id: supplierAcc.id, debit: 0, credit: grandTotal, project_id: invoice.project_id, contact_id: invoice.contact_id || null, notes: `قيمة فاتورة مشتريات ${invoice.id}${contactSuffix}` });

    // Discount Received Credit
    if (totalDiscount > 0 && discountAcc) {
        journal.rows.push({ account_id: discountAcc.id, debit: 0, credit: totalDiscount, project_id: invoice.project_id, contact_id: invoice.contact_id || null, notes: `خصم مكتسب فاتورة مشتريات ${invoice.id}${contactSuffix}` });
    }

    journal.total = totalDebit;
    await window.DB.add('journal_entries', journal);
}

window.updatePurchasesUnitOptions = function() {
    const sel = document.getElementById('purchases-item');
    if(!sel) return;
    const itemId = sel.value;
    const item = currentItems.find(i => String(i.id) === String(itemId));
    const unitSel = document.getElementById('purchases-unit');
    if(unitSel && item) {
        unitSel.innerHTML = `<option value="base" data-factor="1">${item.unit || 'الأساسية'}</option>`;
        if(item.alt_unit && item.conv_factor) {
            unitSel.innerHTML += `<option value="alt" data-factor="${item.conv_factor}">${item.alt_unit} (/${item.conv_factor})</option>`;
        }
    }
};

window.updateSalesUnitOptions = function() {
    const sel = document.getElementById('sales-item');
    if(!sel) return;
    const itemId = sel.value;
    const item = currentItems.find(i => String(i.id) === String(itemId));
    const unitSel = document.getElementById('sales-unit');
    if(unitSel && item) {
        unitSel.innerHTML = `<option value="base" data-factor="1">${item.unit || 'الأساسية'}</option>`;
        if(item.alt_unit && item.conv_factor) {
            unitSel.innerHTML += `<option value="alt" data-factor="${item.conv_factor}">${item.alt_unit} (/${item.conv_factor})</option>`;
        }
    }
};
