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

window.currentSalesReturnLines = [];
window.currentPurchasesReturnLines = [];
﻿// ==========================================
// VOUCHERS & RETURNS MODULE
// ==========================================

// Helper to open Data URLs cleanly without browser blocking or white screen
window.openDataUrlAttachment = function(dataUrl, title = 'المرفق') {
    if (!dataUrl) {
        alert('لا يوجد ملف مرفق.');
        return;
    }
    try {
        if (dataUrl.startsWith('data:')) {
            const parts = dataUrl.split(';base64,');
            if (parts.length === 2) {
                const contentType = parts[0].split(':')[1] || 'application/octet-stream';
                const byteCharacters = atob(parts[1]);
                const byteNumbers = new Array(byteCharacters.length);
                for (let i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }
                const byteArray = new Uint8Array(byteNumbers);
                const blob = new Blob([byteArray], { type: contentType });
                const blobUrl = URL.createObjectURL(blob);
                
                const newWindow = window.open(blobUrl, '_blank');
                if (!newWindow || newWindow.closed || typeof newWindow.closed == 'undefined') {
                    const a = document.createElement('a');
                    a.href = blobUrl;
                    a.download = title.replace(/\s+/g, '_') + (contentType.includes('pdf') ? '.pdf' : '.png');
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                }
                return;
            }
        }
        window.open(dataUrl, '_blank');
    } catch (e) {
        console.error('Error viewing attachment:', e);
        window.open(dataUrl, '_blank');
    }
};

window.viewTransactionAttachment = async function(id) {
    let trans = (typeof allInvoices !== 'undefined' ? allInvoices.find(t => String(t.id) === String(id)) : null);
    if (!trans && window.DB) {
        try { trans = await window.DB.get('transactions', parseInt(id)); } catch(e) {}
    }
    if (!trans || !trans.attachment) {
        alert('لا يوجد ملف مرفق لهذا السند.');
        return;
    }
    window.openDataUrlAttachment(trans.attachment, `مرفق_سند_${id}`);
};

// ------------------------------------------
// VOUCHERS (سندات القبض والدفع)
// ------------------------------------------

window.renderVouchers = function() {
  const tbody = document.querySelector('#vouchers-table tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  
  // Populate contact filter if empty
  const contactFilter = document.getElementById('filter-voucher-contact');
  if (contactFilter && contactFilter.options.length <= 1 && typeof currentContacts !== 'undefined') {
    const sortedContacts = [...currentContacts].sort((a,b) => a.name.localeCompare(b.name));
    sortedContacts.forEach(c => {
      contactFilter.innerHTML += `<option value="${c.id}">${c.name} (${c.type || ''})</option>`;
    });
  }
  
  // Populate treasury/bank filter if empty
  const treasuryFilter = document.getElementById('filter-voucher-treasury');
  if (treasuryFilter && treasuryFilter.options.length <= 1 && typeof currentAccounts !== 'undefined') {
    const sortedAccounts = currentAccounts.filter(a => a.name.includes('خزينة') || a.name.includes('بنك') || a.name.includes('عهدة') || a.name.includes('صندوق')).sort((a,b) => a.name.localeCompare(b.name));
    sortedAccounts.forEach(a => {
      treasuryFilter.innerHTML += `<option value="${a.id}">${a.name}</option>`;
    });
  }

  const typeF = document.getElementById('filter-voucher-type')?.value;
  const contactF = document.getElementById('filter-voucher-contact')?.value;
  const treasuryF = document.getElementById('filter-voucher-treasury')?.value;
  
  let vouchers = allInvoices.filter(t => t.type === 'receipt' || t.type === 'payment' || t.type === 'money_transfer');
  
  if (typeF) {
      vouchers = vouchers.filter(t => t.type === typeF);
  }
  if (contactF) {
      vouchers = vouchers.filter(t => t.contact_id == contactF);
  }
  if (treasuryF) {
      vouchers = vouchers.filter(t => t.treasury_account_id == treasuryF);
  }
  
  vouchers.sort((a, b) => new Date(b.date) - new Date(a.date) || b.id - a.id);
  vouchers.forEach(v => {
    const contact = currentContacts.find(c => c.id == v.contact_id);
    const treasury = currentAccounts.find(a => a.id == v.treasury_account_id);
    const destTreasury = currentAccounts.find(a => a.id == v.to_treasury_account_id);
    const contactName = v.type === 'money_transfer' ? (destTreasury ? destTreasury.name : 'غير محدد') : (contact ? contact.name : 'غير محدد');
    const treasuryName = treasury ? treasury.name : 'غير محدد';
    const typeText = v.type === 'receipt' ? 'سند قبض' : (v.type === 'payment' ? 'سند صرف' : 'سند تحويل');
    
    let statusBadge = v.status === 'draft' 
      ? '<span class="badge" style="background:#ff9800;color:#fff; display:inline-block; margin-top:6px; box-shadow:0 1px 3px rgba(0,0,0,0.1);">مسودة</span>' 
      : '<span class="badge" style="background:#4caf50;color:#fff; display:inline-block; margin-top:6px; box-shadow:0 1px 3px rgba(0,0,0,0.1);">مُرحل</span>';

    let projectName = '';
    if (v.project_id && typeof currentProjects !== 'undefined') {
        const pObj = currentProjects.find(p => p.id == v.project_id);
        if (pObj) projectName = `<br><span style="background:rgba(0, 191, 165, 0.15); color:#00bfa5; padding:2px 6px; border-radius:4px; font-size:12px; font-weight:bold; display:inline-block; margin-top:4px;">🏗️ ${pObj.name}</span>`;
    }

    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${v.id}</td>
      <td>${typeText}</td>
      <td>${new Date(v.date).toLocaleString('ar-EG')}</td>
      <td style="max-width: 180px; white-space: normal; word-wrap: break-word; line-height: 1.6; padding: 10px 5px;">${contactName}</td>
      <td>${treasuryName}</td>
      <td>${v.amount ? parseFloat(v.amount).toLocaleString('en-US') : '0'}</td>
      <td style="max-width: 200px; white-space: normal; word-wrap: break-word; line-height: 1.6; padding: 10px 5px;">${v.notes || ''} <br> ${statusBadge} ${projectName}</td>
      <td>${v.created_by || ''}</td>
      <td>
        <div style="display:flex; gap:5px; justify-content:center; flex-wrap:wrap;">
          <button class="action-btn btn-edit" onclick="${v.type === 'money_transfer' ? `editTransfer(${v.id})` : `editVoucher(${v.id})`}" style="padding:5px 10px;">تعديل/عرض</button>
          ${v.attachment ? `<button type="button" class="action-btn" onclick="window.viewTransactionAttachment('${v.id}')" style="background:#00bcd4;color:#fff;padding:5px 10px;border:none;border-radius:4px;cursor:pointer;display:inline-block;font-size:13px;" title="عرض المرفق">📎 المرفق</button>` : ''}
          ${currentUser && currentUser.role === 'مدير عام' ? `<button class="action-btn btn-delete" onclick="deleteInvoice(${v.id}, 'voucher')" style="padding:5px 10px;">حذف</button>` : ''}
        </div>
      </td>
    `;
    tbody.appendChild(tr);
  });
};

window.openVoucherModal = function(type, linkedInvoiceId = null, contactId = null) {
  window.currentLinkedInvoiceId = linkedInvoiceId;
  document.getElementById('voucher-modal-title').innerText = type === 'receipt' ? 'إنشاء سند قبض (استلام نقدية)' : 'إنشاء سند صرف (دفع نقدية)';
  document.getElementById('edit-voucher-id').value = '';
  document.getElementById('voucher-type').value = type;
  document.getElementById('voucher-date').value = new Date().toISOString().slice(0, 16);
  document.getElementById('voucher-doc-no').value = linkedInvoiceId ? String(linkedInvoiceId) : '';
  document.getElementById('voucher-amount').value = '';
  document.getElementById('voucher-notes').value = linkedInvoiceId ? 'دفعة للفاتورة رقم ' + linkedInvoiceId : '';
  document.getElementById('voucher-status').value = 'posted';
  document.getElementById('btn-save-voucher').style.display = 'inline-block';
  
  const contactSelect = document.getElementById('voucher-contact');
  contactSelect.innerHTML = '<option value="">-- اختر --</option>';
  currentContacts.forEach(c => {
    let typeName = c.type;
    contactSelect.innerHTML += `<option value="${c.id}">${c.name} (${typeName})</option>`;
  });
  if (contactId) {
      contactSelect.value = contactId;
  }
  
  const treasurySelect = document.getElementById('voucher-treasury-account');
  const cashAccounts = currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('خزن') || a.name.includes('بنك') || a.name.includes('بنوك') || a.name.includes('صندوق') || a.name.includes('عهد') || a.name.includes('سلف') || a.name.includes('نقد'));
  treasurySelect.innerHTML = '<option value="">-- اختر الخزينة/البنك --</option>';
  cashAccounts.forEach(a => {
    treasurySelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
  });
  
  const projSelect = document.getElementById('voucher-project');
  if (projSelect) {
      projSelect.innerHTML = '<option value="">-- بدون مشروع / عام --</option>';
      if (typeof currentProjects !== 'undefined') {
          currentProjects.forEach(p => projSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`);
      }
      projSelect.value = '';
  }
  window.currentEditingVoucherAttachment = null;
  const attInput = document.getElementById('voucher-attachment');
  if (attInput) attInput.value = '';
  const attView = document.getElementById('voucher-attachment-view');
  if (attView) { attView.style.display = 'none'; attView.removeAttribute('href'); attView.onclick = null; }
  
  document.getElementById('voucher-modal').classList.add('active');
};

window.editVoucher = function(id) {
  const v = allInvoices.find(t => String(t.id) === String(id));
  if (!v) return;
  if (v.type === 'money_transfer') {
      if (typeof window.editTransfer === 'function') return window.editTransfer(id);
  }
  
  document.getElementById('voucher-modal-title').innerText = v.type === 'receipt' ? 'تعديل سند قبض' : 'تعديل سند صرف';
  document.getElementById('edit-voucher-id').value = v.id;
  document.getElementById('voucher-type').value = v.type;
  document.getElementById('voucher-date').value = new Date(v.date).toISOString().slice(0, 16);
  document.getElementById('voucher-doc-no').value = v.doc_no || '';
  
  const contactSelect = document.getElementById('voucher-contact');
  contactSelect.innerHTML = '<option value="">-- اختر --</option>';
  currentContacts.forEach(c => {
    contactSelect.innerHTML += `<option value="${c.id}">${c.name} (${c.type})</option>`;
  });
  contactSelect.value = v.contact_id || '';
  
  const treasurySelect = document.getElementById('voucher-treasury-account');
  const cashAccounts = currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('خزن') || a.name.includes('بنك') || a.name.includes('بنوك') || a.name.includes('صندوق') || a.name.includes('عهد') || a.name.includes('سلف') || a.name.includes('نقد'));
  treasurySelect.innerHTML = '<option value="">-- اختر --</option>';
  cashAccounts.forEach(a => {
    treasurySelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
  });
  treasurySelect.value = v.treasury_account_id || '';
  
  const projSelect = document.getElementById('voucher-project');
  if (projSelect) {
      projSelect.innerHTML = '<option value="">-- بدون مشروع / عام --</option>';
      if (typeof currentProjects !== 'undefined') {
          currentProjects.forEach(p => projSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`);
      }
      projSelect.value = v.project_id || '';
  }
  const attInput = document.getElementById('voucher-attachment');
  if (attInput) attInput.value = '';
  window.currentEditingVoucherAttachment = v.attachment || null;
  const attView = document.getElementById('voucher-attachment-view');
  if (attView) {
      if (v.attachment) {
          attView.removeAttribute('href');
          attView.onclick = (e) => { e.preventDefault(); window.openDataUrlAttachment(v.attachment, `مرفق_سند_${v.id}`); };
          attView.style.display = 'inline-block';
          attView.style.cursor = 'pointer';
      } else {
          attView.style.display = 'none';
          attView.removeAttribute('href');
          attView.onclick = null;
      }
  }
  
  document.getElementById('voucher-amount').value = v.amount;
  document.getElementById('voucher-notes').value = v.notes || '';
  document.getElementById('voucher-status').value = v.status || 'draft';
  
  if (v.status === 'posted') {
      document.getElementById('btn-save-voucher').style.display = 'none';
  } else {
      document.getElementById('btn-save-voucher').style.display = 'inline-block';
  }
  
  document.getElementById('voucher-modal').classList.add('active');
};

const btnSaveVoucher = document.getElementById('btn-save-voucher');
if (btnSaveVoucher) {
  btnSaveVoucher.addEventListener('click', async () => {
    try {
      const id = document.getElementById('edit-voucher-id').value;
      const type = document.getElementById('voucher-type').value;
      const date = document.getElementById('voucher-date').value;
      const docNo = document.getElementById('voucher-doc-no').value;
      const contactId = document.getElementById('voucher-contact').value;
      const treasuryId = document.getElementById('voucher-treasury-account').value;
      const amount = parseFloat(document.getElementById('voucher-amount').value);
      const notes = document.getElementById('voucher-notes').value;
      const status = document.getElementById('voucher-status').value;
      
      const projVal = document.getElementById('voucher-project')?.value;
      const projectId = projVal ? parseInt(projVal) : null;
      
      const fileInput = document.getElementById('voucher-attachment');
      let attachment = window.currentEditingVoucherAttachment || null;
      if (id && !attachment) {
          const existing = allInvoices.find(t => String(t.id) === String(id));
          if (existing && existing.attachment) attachment = existing.attachment;
      }
      if (fileInput && fileInput.files && fileInput.files[0]) {
          const file = fileInput.files[0];
          attachment = await new Promise((resolve, reject) => {
              const reader = new FileReader();
              reader.onload = (ev) => resolve(ev.target.result);
              reader.onerror = (ev) => reject(ev);
              reader.readAsDataURL(file);
          });
      }
      
      if (!date || !contactId || !treasuryId || !amount) {
        alert('يرجى تعبئة الحقول الإلزامية.');
        return;
      }
      
      const v = {
        type: type,
        date: date,
        doc_no: docNo,
        contact_id: parseInt(contactId),
        treasury_account_id: parseInt(treasuryId),
        amount: amount,
        notes: notes,
        status: status,
        project_id: projectId,
        attachment: attachment,
        created_by: currentUser ? currentUser.username : 'النظام',
        linked_invoice_id: window.currentLinkedInvoiceId || null
      };
      
      if (id) {
        v.id = parseInt(id);
        await window.DB.update('transactions', v);
        
        if (status === 'posted') {
            await window.generateVoucherJournal(v);
        } else {
            // Delete old journal if draft
            const allJournals = await window.DB.getAll('journal_entries');
            const oldJ = allJournals.find(j => j.reference === 'voucher_' + v.id);
            if (oldJ) {
                await window.DB.delete('journal_entries', oldJ.id);
            }
        }
      } else {
          // Send to server without an ID so it generates one
          delete v.id;
          const res = await window.DB.add('transactions', v);
          v.id = res && res.id ? res.id : Date.now(); // use server ID if available
          
          if (status === 'posted') {
              await window.generateVoucherJournal(v);
          }
        }
      
      closeModal('voucher-modal'); if (window.loadData) await window.loadData(); if (typeof renderVouchers === 'function') renderVouchers();
    } catch(err) {
      console.error(err);
      alert('Error details:\n' + err.message + '\n' + err.stack);
    }
  });
}

window.generateVoucherJournal = async function(voucher) {
    try {
      if (window.loadData) await window.loadData(false);
      const contact = currentContacts.find(c => c.id == voucher.contact_id);
      if (!contact) { alert('لم يتم العثور على جهة اتصال للسند ' + voucher.id); return; }
      
      let cAcc = await window.resolveContactAccount(voucher.contact_id, voucher.type);
      if (!cAcc) {
          alert('لم يتم العثور على حساب العملاء أو الموردين الافتراضي في الدليل المحاسبي.');
          return;
      }
      contact.account_id = cAcc.id;
  
      let debitAcc, creditAcc;
      if (voucher.type === 'receipt') {
        debitAcc = voucher.treasury_account_id;
        creditAcc = contact.account_id;
      } else {
        debitAcc = contact.account_id;
        creditAcc = voucher.treasury_account_id;
      }
      
      if (!debitAcc || !creditAcc) {
         alert('خطأ: الخزينة أو حساب العميل غير موجود');
         return;
      }
      
      let descStr = voucher.notes || '';
      if (!descStr.includes('دفعة')) {
          descStr = (voucher.type === 'receipt' ? 'قبض دفعة ' : 'صرف دفعة ') + descStr;
      }
      let cNameObj = currentContacts.find(c => c.id === parseInt(voucher.contact_id));
      if (cNameObj && !descStr.includes(cNameObj.name)) {
          descStr += ' - ' + cNameObj.name;
      }

      const journalId = Date.now() + Math.floor(Math.random() * 10000);
      const journal = {
        id: journalId,
        date: voucher.date,
        desc: descStr,
        reference: 'voucher_' + voucher.id,
        project_id: voucher.project_id || null,
        attachment: voucher.attachment || null,
        status: 'posted',
        total: voucher.amount,
        created_by: typeof currentUser !== 'undefined' && currentUser ? currentUser.username : 'نظام',
        rows: [
          { account_id: debitAcc, debit: voucher.amount, credit: 0 },
          { account_id: creditAcc, debit: 0, credit: voucher.amount }
        ]
      };
      
      const allJournals = await window.DB.getAll('journal_entries');
      const oldJ = allJournals.find(j => j.reference === 'voucher_' + voucher.id);
      if (oldJ) {
          journal.id = oldJ.id;
          await window.DB.update('journal_entries', journal);
      } else {
          await window.DB.add('journal_entries', journal);
      }
      
    } catch(err) {
      alert("حدث خطأ أثناء ترحيل قيد السداد: " + err.message);
      console.error(err);
    }
}

// ------------------------------------------
// QUICK ADD TREASURY
// ------------------------------------------
window.quickAddTreasury = async function() {
  const name = prompt('أدخل اسم الخزينة أو البنك أو العهدة الجديدة:');
  if (!name || name.trim() === '') return;
  
  const cashParent = currentAccounts.find(a => a.name.includes('صول') || a.name.includes('نقدية') || a.name.includes('خزن') || a.name.includes('بنك') || a.name.includes('اصول') || a.name.includes('أصول'));
  if (!cashParent) {
    alert('تعذر العثور على الحساب الرئيسي.');
    return;
  }
  
  if (currentAccounts.find(a => a.name.trim() === name.trim())) {
    alert('هذا الحساب موجود بالفعل!');
    return;
  }
  
  try {
      const newAccId = await window.DB.add('accounts', {
        id: Date.now(),
        code: '',
        name: name.trim(),
        type: 'أصل',
        parent_id: cashParent.id
      });
      
      currentAccounts = await window.DB.getAll('accounts');
      
      const cashAccounts = currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('خزن') || a.name.includes('بنك') || a.name.includes('بنوك') || a.name.includes('صندوق') || a.name.includes('عهد') || a.name.includes('سلف') || a.name.includes('نقد'));
      
      const selects = [
        document.getElementById('voucher-treasury-account'),
        document.getElementById('transfer-source-account'),
        document.getElementById('transfer-destination-account')
      ];
      
      selects.forEach(select => {
          if (select) {
              select.innerHTML = '<option value="">-- اختر --</option>';
              cashAccounts.forEach(a => {
                  select.innerHTML += `<option value="${a.id}">${a.name}</option>`;
              });
          }
      });
      
      if (document.getElementById('transfer-modal') && document.getElementById('transfer-modal').classList.contains('active')) {
          const dest = document.getElementById('transfer-destination-account');
          if (dest && !dest.value) dest.value = newAccId;
      } else {
          const treas = document.getElementById('voucher-treasury-account');
          if (treas) treas.value = newAccId;
      }
  } catch (err) {
      console.error(err);
      alert('حدث خطأ أثناء الإضافة!');
  }
};

// ------------------------------------------
// INTERNAL TRANSFER (تحويل بين الخزائن)
// ------------------------------------------
window.openTransferModal = function() {
  if (document.getElementById('edit-transfer-id')) document.getElementById('edit-transfer-id').value = '';
  if (document.getElementById('transfer-modal-title')) document.getElementById('transfer-modal-title').innerText = 'تحويل نقدية بين الخزائن';
  document.getElementById('transfer-date').value = new Date().toISOString().slice(0, 16);
  document.getElementById('transfer-amount').value = '';
  document.getElementById('transfer-notes').value = '';
  
  const cashAccounts = currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('خزن') || a.name.includes('بنك') || a.name.includes('بنوك') || a.name.includes('صندوق') || a.name.includes('عهد') || a.name.includes('سلف') || a.name.includes('نقد'));
  
  const sourceSelect = document.getElementById('transfer-source-account');
  const destSelect = document.getElementById('transfer-destination-account');
  
  if (sourceSelect) sourceSelect.innerHTML = '<option value="">-- اختر --</option>';
  if (destSelect) destSelect.innerHTML = '<option value="">-- اختر --</option>';
  
  cashAccounts.forEach(a => {
    if (sourceSelect) sourceSelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
    if (destSelect) destSelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
  });
  
  const projSelect = document.getElementById('transfer-project');
  if (projSelect) {
      projSelect.innerHTML = '<option value="">-- بدون مشروع / عام --</option>';
      if (typeof currentProjects !== 'undefined') {
          currentProjects.forEach(p => projSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`);
      }
      projSelect.value = '';
  }
  window.currentEditingTransferAttachment = null;
  const attInput = document.getElementById('transfer-attachment');
  if (attInput) attInput.value = '';
  const attView = document.getElementById('transfer-attachment-view');
  if (attView) { attView.style.display = 'none'; attView.removeAttribute('href'); attView.onclick = null; }
  
  document.getElementById('transfer-modal').classList.add('active');
};

window.editTransfer = function(id) {
  const v = allInvoices.find(t => String(t.id) === String(id));
  if (!v) return;
  document.getElementById('transfer-modal-title').innerText = 'تعديل سند تحويل نقدية';
  if (document.getElementById('edit-transfer-id')) document.getElementById('edit-transfer-id').value = v.id;
  document.getElementById('transfer-date').value = new Date(v.date).toISOString().slice(0, 16);
  document.getElementById('transfer-amount').value = v.amount || '';
  document.getElementById('transfer-notes').value = v.notes || '';
  
  const cashAccounts = currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('خزن') || a.name.includes('بنك') || a.name.includes('بنوك') || a.name.includes('صندوق') || a.name.includes('عهد') || a.name.includes('سلف') || a.name.includes('نقد'));
  const sourceSelect = document.getElementById('transfer-source-account');
  const destSelect = document.getElementById('transfer-destination-account');
  if (sourceSelect) {
      sourceSelect.innerHTML = '<option value="">-- اختر --</option>';
      cashAccounts.forEach(a => sourceSelect.innerHTML += `<option value="${a.id}">${a.name}</option>`);
      sourceSelect.value = v.treasury_account_id || '';
  }
  if (destSelect) {
      destSelect.innerHTML = '<option value="">-- اختر --</option>';
      cashAccounts.forEach(a => destSelect.innerHTML += `<option value="${a.id}">${a.name}</option>`);
      destSelect.value = v.to_treasury_account_id || '';
  }
  const projSelect = document.getElementById('transfer-project');
  if (projSelect) {
      projSelect.innerHTML = '<option value="">-- بدون مشروع / عام --</option>';
      if (typeof currentProjects !== 'undefined') {
          currentProjects.forEach(p => projSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`);
      }
      projSelect.value = v.project_id || '';
  }
  const attInput = document.getElementById('transfer-attachment');
  if (attInput) attInput.value = '';
  window.currentEditingTransferAttachment = v.attachment || null;
  const attView = document.getElementById('transfer-attachment-view');
  if (attView) {
      if (v.attachment) {
          attView.removeAttribute('href');
          attView.onclick = (e) => { e.preventDefault(); window.openDataUrlAttachment(v.attachment, `مرفق_تحويل_${v.id}`); };
          attView.style.display = 'inline-block';
          attView.style.cursor = 'pointer';
      } else {
          attView.style.display = 'none';
          attView.removeAttribute('href');
          attView.onclick = null;
      }
  }
  document.getElementById('transfer-modal').classList.add('active');
};

const btnSaveTransfer = document.getElementById('btn-save-transfer');
if (btnSaveTransfer) {
    btnSaveTransfer.addEventListener('click', async () => {
      try {
        const origEditVal = document.getElementById('edit-transfer-id')?.value;
        let journalId = origEditVal;
        const date = document.getElementById('transfer-date').value;
        const sourceSelect = document.getElementById('transfer-source-account');
        const destSelect = document.getElementById('transfer-destination-account');
        const sourceId = sourceSelect.value;
        const destId = destSelect.value;
        const amount = parseFloat(document.getElementById('transfer-amount').value);
        const notes = document.getElementById('transfer-notes').value;
        
        if (!sourceId || !destId || !amount || amount <= 0) {
            alert('يرجى تحديد الخزائن وإدخال مبلغ صحيح.');
            return;
        }
        if (sourceId === destId) {
            alert('لا يمكن التحويل لنفس الخزينة.');
            return;
        }
        
        const sourceName = sourceSelect.options[sourceSelect.selectedIndex].text;
        const destName = destSelect.options[destSelect.selectedIndex].text;
        
        const projVal = document.getElementById('transfer-project')?.value;
        const projectId = projVal ? parseInt(projVal) : null;
        
        const fileInput = document.getElementById('transfer-attachment');
        let attachment = window.currentEditingTransferAttachment || null;
        if (journalId && !attachment) {
            const existing = allInvoices.find(t => String(t.id) === String(journalId));
            if (existing && existing.attachment) attachment = existing.attachment;
        }
        if (fileInput && fileInput.files && fileInput.files[0]) {
            const file = fileInput.files[0];
            attachment = await new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (ev) => resolve(ev.target.result);
                reader.onerror = (ev) => reject(ev);
                reader.readAsDataURL(file);
            });
        }
        
        const transaction = {
            id: journalId ? parseInt(journalId) : null,
            date: date,
            type: 'money_transfer',
            treasury_account_id: parseInt(sourceId),
            to_treasury_account_id: parseInt(destId),
            amount: amount,
            notes: notes,
            project_id: projectId,
            attachment: attachment,
            status: 'posted',
            created_by: currentUser ? currentUser.username : 'مدير'
        };
        if (journalId) {
            await window.DB.update('transactions', transaction);
        } else {
            delete transaction.id; // Let server assign ID
            const newId = await window.DB.add('transactions', transaction);
            journalId = newId;
            transaction.id = journalId;
        }

          const journal = {
            id: journalId,
            date: date,
            desc: `تحويل من (${sourceName}) إلى (${destName})` + (notes ? ' - ' + notes : ''),
            reference: 'transfer_' + journalId,
            project_id: projectId,
            attachment: attachment,
            status: 'posted',
            total: amount,
            created_by: typeof currentUser !== 'undefined' && currentUser ? currentUser.username : 'مدير',
            rows: [
              { account_id: parseInt(destId), debit: amount, credit: 0, project_id: projectId },
              { account_id: parseInt(sourceId), debit: 0, credit: amount, project_id: projectId }
            ]
          };
          
          if (origEditVal) {
            const allJournals = await window.DB.getAll('journal_entries');
            const oldJ = allJournals.find(j => j.reference === 'transfer_' + journalId || j.id === journalId);
            if (oldJ) {
                journal.id = oldJ.id;
                await window.DB.update('journal_entries', journal);
            } else {
                await window.DB.add('journal_entries', journal);
            }
            alert('تم تعديل التحويل بنجاح!');
            closeModal('transfer-modal');
            if (window.loadData) await window.loadData();
            if (typeof renderVouchers === 'function') renderVouchers();
            return;
        }
        
        const allUsers = await window.DB.getAll('users');
        const destAccountUser = allUsers.find(u => u.custody_account_id == destId);
        
        if (destAccountUser) {
            journal.ack_status = 'pending';
            journal.custody_account_id = parseInt(destId);
            
            await window.DB.add('notifications', {
                user: destAccountUser.username,
                message: `تم تحويل مبلغ ${amount} إلى عهدتك. يرجى تأكيد الاستلام من إشعارات العهدة.`,
                date: new Date().toISOString(),
                read: false,
                invoice_id: journalId
            });
            
            // Re-render bell icon if possible
            if(window.renderNotificationsBadge) window.renderNotificationsBadge();
        } else {
            journal.ack_status = 'confirmed';
        }
        
        await window.DB.add('journal_entries', journal);
        
        alert('تم التحويل بنجاح!');
        closeModal('transfer-modal');
        if (window.loadData) await window.loadData();
        if (typeof renderVouchers === 'function') renderVouchers();
      } catch(e) {
          alert('Error details:\n' + e.message + '\n' + e.stack);
      }
    });
}


// ------------------------------------------
// SALES RETURNS (مرتجعات المبيعات)
// ------------------------------------------
window.renderSalesReturns = function() {
  const tbody = document.querySelector('#sales-returns-table tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  
  
  const filterNo = document.getElementById('filter-view-sales-returns-no')?.value?.toLowerCase();
  const filterContact = document.getElementById('filter-view-sales-returns-contact')?.value?.toLowerCase();
  const filterFrom = document.getElementById('filter-view-sales-returns-from')?.value;
  const filterTo = document.getElementById('filter-view-sales-returns-to')?.value;

  let baseList = allInvoices.filter(inv => inv.type === 'sales_return').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;
  });

  
  finalData.forEach(r => {
    const contact = currentContacts.find(c => c.id == r.contact_id);
    const warehouse = (typeof currentWarehouses !== 'undefined' ? currentWarehouses : []).find(w => w.id == r.to_warehouse_id);
    const contactName = contact ? contact.name : 'غير محدد';
    const warehouseName = warehouse ? warehouse.name : (r.to_warehouse_id ? 'مخزن #'+r.to_warehouse_id : 'غير محدد');
    
    let statusBadge = r.status === 'draft' 
      ? '<span class="badge" style="background:#ff9800;color:#fff;">مسودة</span>' 
      : '<span class="badge" style="background:#4caf50;color:#fff;">مُرحل</span>';

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

    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${r.id}</td>
      <td>${new Date(r.date).toLocaleString('ar-EG')}</td>
      <td>${contactName}</td>
      <td>${warehouseName}</td>
      <td>${r.total_amount ? parseFloat(r.total_amount).toLocaleString('en-US') : (r.total ? parseFloat(r.total).toLocaleString('en-US') : '0')}</td>
      <td>${taxLabel}</td>
      <td>${r.created_by || ''}</td>
      <td>${statusBadge}</td>
      <td>
        <div style="display:flex; gap:5px; justify-content:center;">
          <button class="action-btn btn-edit" onclick="editSalesReturn(${r.id})" style="padding:5px 10px;">تعديل/عرض</button>
          ${currentUser && currentUser.role === 'مدير عام' ? `<button class="action-btn btn-delete" onclick="deleteInvoice(${r.id}, 'sales_return')" style="padding:5px 10px;">حذف</button>` : ''}
        </div>
      </td>
    `;
    tbody.appendChild(tr);
  });
};

window.openSalesReturnModal = function() {
  document.getElementById('sales-returns-modal-title').innerText = 'إنشاء فاتورة مرتجع مبيعات (نسخة متطورة)';
  document.getElementById('edit-sales-returns-id').value = '';
  if(document.getElementById('sales-returns-link-banner')) document.getElementById('sales-returns-link-banner').innerHTML = '';
  document.getElementById('sales-returns-date').value = new Date().toISOString().slice(0, 16);
  if(document.getElementById('sales-returns-doc-no')) document.getElementById('sales-returns-doc-no').value = '';
  if(document.getElementById('sales-returns-total')) document.getElementById('sales-returns-total').value = '';
  if(document.getElementById('sales-returns-net')) document.getElementById('sales-returns-net').value = '';
  if(document.getElementById('sales-returns-tax-rate')) document.getElementById('sales-returns-tax-rate').value = '0';
  if(document.getElementById('sales-returns-tax-amount')) document.getElementById('sales-returns-tax-amount').value = '';
  if(document.getElementById('sales-returns-notes')) document.getElementById('sales-returns-notes').value = '';
  document.getElementById('sales-returns-status').value = 'draft';
  document.getElementById('btn-save-sales-returns').style.display = 'inline-block';
  
  const contactSelect = document.getElementById('sales-returns-contact');
  contactSelect.innerHTML = '<option value="">-- اختر العميل --</option>';
  currentContacts.forEach(c => {
    if (true) { // removed type filter
      contactSelect.innerHTML += `<option value="${c.id}">${c.name} (${c.type || ''})</option>`;
    }
  });
  
  const treasurySelect = document.getElementById('sales-returns-treasury');
    if (treasurySelect) {
  const cashAccounts = currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('خزن') || a.name.includes('بنك') || a.name.includes('بنوك') || a.name.includes('صندوق') || a.name.includes('نقد'));
  treasurySelect.innerHTML = '<option value="">-- آجل / لم يتم الدفع --</option>';
  cashAccounts.forEach(a => {
    treasurySelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
  });
    }
  
  // === تعبئة المخازن ===
  const whSelect = document.getElementById('sales-returns-warehouse');
  if (whSelect) {
    const whs = typeof currentWarehouses !== 'undefined' ? currentWarehouses : [];
    whSelect.innerHTML = '<option value="">-- اختر المخزن --</option>';
    whs.forEach(w => { whSelect.innerHTML += `<option value="${w.id}">${w.name}</option>`; });
  }
  // === تعبئة المشاريع ===
  const projSelect = document.getElementById('sales-returns-project');
  if (projSelect) {
    const projs = typeof currentProjects !== 'undefined' ? currentProjects : [];
    projSelect.innerHTML = '<option value="">-- بدون مشروع --</option>';
    projs.forEach(p => { projSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`; });
  }
  // === تصفير الأصناف ===
  window.currentSalesReturnLines = [];
  if (typeof window.renderSalesReturnsLines === 'function') window.renderSalesReturnsLines();

  document.getElementById('sales-returns-modal').classList.add('active');
  setTimeout(() => { if(typeof loadSalesForReturn === 'function') loadSalesForReturn(); }, 100);
};

window.editSalesReturn = function(id) {
    const r = allInvoices.find(v => String(v.id) === String(id));
    if(!r) return;
    document.getElementById('sales-returns-modal-title').innerText = 'عرض / تعديل مرتجع مبيعات';
    document.getElementById('edit-sales-returns-id').value = r.id;
    let linkContainer = document.getElementById('sales-returns-link-banner');
    if(!linkContainer) {
        linkContainer = document.createElement('div');
        linkContainer.id = 'sales-returns-link-banner';
        document.getElementById('sales-returns-modal-title').after(linkContainer);
    }
    if (r.linked_invoice_id) {
        linkContainer.innerHTML = `<div style="margin:10px 0; background:#e3f2fd; padding:10px; border-radius:5px; border-right:4px solid #2196f3;"><a href="#" onclick="closeModal('sales-returns-modal'); openSalesModal(${r.linked_invoice_id}); return false;" style="text-decoration:none; font-weight:bold; color:#0d47a1;">🔗 الانتقال للفاتورة الأصلية رقم #${r.linked_invoice_id}</a></div>`;
    } else {
        linkContainer.innerHTML = '';
    }
    document.getElementById('sales-returns-date').value = r.date.slice(0, 16);
    document.getElementById('sales-returns-doc-no').value = r.doc_no || '';
    if(document.getElementById('sales-returns-tax-rate')) document.getElementById('sales-returns-tax-rate').value = r.tax_rate || 0;
    
    const contactSelect = document.getElementById('sales-returns-contact');
    contactSelect.innerHTML = '<option value="">-- اختر العميل --</option>';
    currentContacts.forEach(c => {
        contactSelect.innerHTML += `<option value="${c.id}" ${c.id == r.contact_id ? 'selected' : ''}>${c.name}</option>`;
    });
    window.loadSalesForReturn();
    
    setTimeout(() => {
       const invSel = document.getElementById('sales-returns-original-invoice');
       if(invSel) invSel.value = r.linked_invoice_id || '';
    }, 100);

    const treasurySelect = document.getElementById('sales-returns-treasury');
    if (treasurySelect) {
        treasurySelect.innerHTML = '<option value="">-- آجل --</option>';
    currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('بنك') || a.name.includes('نقد')).forEach(a => {
        treasurySelect.innerHTML += `<option value="${a.id}" ${a.id == r.treasury_account_id ? 'selected' : ''}>${a.name}</option>`;
    });
    }

    // === تعبئة المخزن ===
    const whSelectEdit = document.getElementById('sales-returns-warehouse');
    if (whSelectEdit) {
        const whs = typeof currentWarehouses !== 'undefined' ? currentWarehouses : [];
        whSelectEdit.innerHTML = '<option value="">-- اختر المخزن --</option>';
        whs.forEach(w => { whSelectEdit.innerHTML += `<option value="${w.id}" ${String(w.id) === String(r.to_warehouse_id) ? 'selected' : ''}>${w.name}</option>`; });
    }
    // === تعبئة المشروع ===
    const projSelectEdit = document.getElementById('sales-returns-project');
    if (projSelectEdit) {
        const projs = typeof currentProjects !== 'undefined' ? currentProjects : [];
        projSelectEdit.innerHTML = '<option value="">-- بدون مشروع --</option>';
        projs.forEach(p => { projSelectEdit.innerHTML += `<option value="${p.id}" ${String(p.id) === String(r.project_id) ? 'selected' : ''}>${p.name}</option>`; });
    }

    document.getElementById('sales-returns-notes').value = r.notes || '';
    document.getElementById('sales-returns-status').value = r.status || 'draft';
    
    document.getElementById('btn-save-sales-returns').style.display = 'inline-block';
    
    window.currentSalesReturnLines = r.items ? JSON.parse(JSON.stringify(r.items)) : [];
    window.renderSalesReturnsLines();

    document.getElementById('sales-returns-modal').classList.add('active');
    setTimeout(() => { if(typeof loadSalesForReturn === 'function') loadSalesForReturn(); }, 100);
};

const btnSaveSalesReturn = document.getElementById('btn-save-sales-returns');
if (btnSaveSalesReturn) {
  btnSaveSalesReturn.addEventListener('click', async () => {
    try {
      const id = document.getElementById('edit-sales-returns-id').value;
      const date = document.getElementById('sales-returns-date').value;
      const docNo = document.getElementById('sales-returns-doc-no').value;
      const contactId = document.getElementById('sales-returns-contact').value;
      const treasuryId = document.getElementById('sales-returns-treasury')?.value;
      const net = parseFloat(document.getElementById('sales-returns-net').value) || 0;
      const taxRate = parseFloat(document.getElementById('sales-returns-tax-rate').value) || 0;
      const taxAmount = parseFloat(document.getElementById('sales-returns-tax-amount').value) || 0;
      const amount = parseFloat(document.getElementById('sales-returns-total').value);
      const notes = document.getElementById('sales-returns-notes').value;
      const status = document.getElementById('sales-returns-status').value;
      
      const existingInv = id ? allInvoices.find(x => String(x.id) === String(id)) : null;
      const wasAlreadyPosted = existingInv && (existingInv.status === 'posted' || existingInv.status === 'financial_only');

      if (wasAlreadyPosted) {
          existingInv.notes = notes;
          await window.DB.update('transactions', existingInv);
          closeModal('sales-returns-modal');
          if (window.loadData) await window.loadData();
          alert('تم حفظ الملاحظات بنجاح (لا يمكن تعديل تفاصيل المرتجع بعد اعتماده).');
          return;
      }
      
      if (!date || !contactId || !amount) {
        alert('يرجى تعبئة الحقول الإلزامية.');
        return;
      }
      
      const r = {
        type: 'sales_return',
        date: date,
        doc_no: docNo,
        contact_id: parseInt(contactId),
        treasury_account_id: treasuryId ? parseInt(treasuryId) : null,
        linked_invoice_id: document.getElementById('sales-returns-original-invoice').value || null,
        to_warehouse_id: parseInt(document.getElementById('sales-returns-warehouse').value) || null,
        project_id: parseInt(document.getElementById('sales-returns-project')?.value) || null,
        total: amount,
        total_amount: amount,
        net_before_tax: net,
        tax_rate: taxRate,
        tax_amount: taxAmount,
        notes: notes,
        status: status,
        items: window.currentSalesReturnLines ? JSON.parse(JSON.stringify(window.currentSalesReturnLines)) : [],
        created_by: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'النظام',
        user: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'النظام'
      };
      
      if (id) {
        r.id = parseInt(id);
        await window.DB.update('transactions', r);
        
        if (status === 'pending_store' && typeof window.sendInvoiceToStore === 'function') {
            await window.sendInvoiceToStore(r.id);
        } else if (status === 'posted') {
            await generateSalesReturnJournal(r);
            if (typeof window.sendInvoiceToStore === 'function') {
                await window.sendInvoiceToStore(r.id);
            }
        } else if (status === 'financial_only') {
            await generateSalesReturnJournal(r);
        } else {
            const allJournals = await window.DB.getAll('journal_entries');
            const oldJ = allJournals.find(j => j.reference === 'sales_return_' + r.id);
            if (oldJ) {
                await window.DB.remove('journal_entries', oldJ.id);
            }
        }
      } else {
        delete r.id; // Let backend assign ID
        const newId = await window.DB.add('transactions', r);
        r.id = newId;
        if (status === 'pending_store' && typeof window.sendInvoiceToStore === 'function') {
            await window.sendInvoiceToStore(newId);
        } else if (status === 'posted') {
            await generateSalesReturnJournal(r);
            if (typeof window.sendInvoiceToStore === 'function') {
                await window.sendInvoiceToStore(newId);
            }
        }
      }
      
      closeModal('sales-returns-modal');
      if (window.loadData) await window.loadData();
    } catch(err) {
      console.error('Save error:', err);
      alert('حدث خطأ أثناء الحفظ:\n' + (err.message || err));
    }
  });
}

async function generateSalesReturnJournal(invoice) {
  const accounts = typeof currentAccounts !== 'undefined' ? currentAccounts : [];
  const amount = parseFloat(invoice.total_amount || invoice.total || 0);
  if (!amount) return;

  // === البحث عن حساب مرتجعات المبيعات ===
  let salesReturnAcc = accounts.find(a =>
    a.name.includes('مرتجع') && (a.name.includes('مبيع') || a.name.includes('بيع'))
  ) || accounts.find(a => a.name.includes('مردود') && a.name.includes('مبيع'))
    || accounts.find(a => a.name.includes('مرتجعات'))
    || accounts.find(a => a.name.includes('مردودات'));

  if (!salesReturnAcc) {
    // إنشاء الحساب تلقائياً إذا غير موجود
    const newAccId = Date.now() + 1;
    const newAcc = { id: newAccId, code: '4100', name: 'مرتجعات مبيعات', type: 'إيراد', balance: 0 };
    await window.DB.add('accounts', newAcc);
    if (window.loadData) await window.loadData();
    salesReturnAcc = newAcc;
  }

  // === البحث عن حساب العميل أو الخزينة ===
  let creditAccId = null;
  if (invoice.treasury_account_id) {
    creditAccId = invoice.treasury_account_id;
  } else {
    // حساب العملاء
    let cAcc = accounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل') || a.name.includes('مدينون'));
    if (!cAcc) {
      const newAccId2 = Date.now() + 2;
      const newAcc2 = { id: newAccId2, code: '1200', name: 'حسابات العملاء', type: 'أصل', balance: 0 };
      await window.DB.add('accounts', newAcc2);
      if (window.loadData) await window.loadData();
      cAcc = newAcc2;
    }
    creditAccId = cAcc.id;
  }

  let invAcc = accounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
  let cogsAcc = accounts.find(a => a.name.includes('تكلفة') && (a.name.includes('بضاع') || a.name.includes('مباع') || a.name.includes('مبيع')));
  let taxAcc = accounts.find(a => a.name.includes('ضريب') || a.name.includes('ضرائب'));

  if (!invAcc && typeof window.resolveSystemAccount === 'function') {
      invAcc = await window.resolveSystemAccount('مخزون البضاعة', ['أصول متداولة', 'الأصول'], 'assets');
  }
  if (!cogsAcc && typeof window.resolveSystemAccount === 'function') {
      cogsAcc = await window.resolveSystemAccount('تكلفة البضاعة المباعة', ['المصروفات', 'مصروفات'], 'expenses');
  }
  if (!taxAcc && typeof window.resolveSystemAccount === 'function') {
      taxAcc = await window.resolveSystemAccount('الضرائب', ['الخصوم', 'التزامات'], 'liabilities');
  }

  let totalCogs = 0;
  let balancesToUse = typeof window.balancesCache !== 'undefined' ? window.balancesCache : (typeof balancesCache !== 'undefined' ? balancesCache : null);
  if(balancesToUse) {
      (invoice.items || []).forEach(line => {
          const qty = parseFloat(line.qty) || 0;
          let b = balancesToUse[line.item_id];
          let avgCost = b ? b.avgCost : 0;
          totalCogs += (qty * avgCost);
      });
  }

  const taxAmount = parseFloat(invoice.tax_amount) || 0;
  const netAmount = parseFloat(invoice.net_before_tax) || (amount - taxAmount);
  const grandTotal = netAmount + taxAmount;
  let totalDebit = 0;

  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}` : '';

  const journalId = Date.now() + Math.floor(Math.random() * 10000);
  const journal = {
    id: journalId,
    date: invoice.date,
    desc: 'مرتجع مبيعات ' + (invoice.doc_no ? '#' + invoice.doc_no : '#' + invoice.id) + contactSuffix + (invoice.notes ? ' - ' + invoice.notes : ''),
    reference: 'sales_return_' + invoice.id,
    project_id: invoice.project_id || null,
    status: 'posted',
    total: 0,
    created_by: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'النظام',
    rows: []
  };

  // Debit Sales Return (Net)
  journal.rows.push({ account_id: salesReturnAcc.id, debit: netAmount, credit: 0, project_id: invoice.project_id, contact_id: invoice.contact_id || null, notes: `قيمة مرتجع مبيعات ${invoice.id}${contactSuffix}` });
  totalDebit += netAmount;

  // Debit Tax
  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;
  }

  // Credit Client/Treasury (Grand Total)
  journal.rows.push({ account_id: creditAccId, debit: 0, credit: grandTotal, project_id: invoice.project_id, contact_id: invoice.contact_id || null, notes: `دفع/رد قيمة مرتجع مبيعات ${invoice.id}${contactSuffix}` });

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

  journal.total = totalDebit;

  const allJournals = await window.DB.getAll('journal_entries');
  const existingJList = allJournals.filter(j => j.reference === 'sales_return_' + invoice.id);
  for (let ej of existingJList) {
      if (window.DB && window.DB.remove) await window.DB.remove('journal_entries', ej.id);
  }
  await window.DB.add('journal_entries', journal);
}

window.renderPurchasesReturns = function() {
  const tbody = document.querySelector('#purchases-returns-table tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  
  const returns = allInvoices.filter(t => t.type === 'purchases_return');
  
  returns.forEach(r => {
    const contact = currentContacts.find(c => c.id == r.contact_id);
    const treasury = currentAccounts.find(a => a.id == r.treasury_account_id);
    const contactName = contact ? contact.name : 'غير محدد';
    const treasuryName = treasury ? treasury.name : 'آجل / غير محدد';
    
    let statusBadge = r.status === 'draft' 
      ? '<span class="badge" style="background:#ff9800;color:#fff;">مسودة</span>'
      : r.status === 'pending_store'
        ? '<span class="badge" style="background:#2196f3;color:#fff;">بانتظار المخزن</span>'
        : '<span class="badge" style="background:#4caf50;color:#fff;">مرحلة ✓</span>';

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

    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${r.id}</td>
      <td>${new Date(r.date).toLocaleString('ar-EG')}</td>
      <td>${contactName}</td>
      <td>${treasuryName}</td>
      <td>${r.total_amount ? parseFloat(r.total_amount).toLocaleString('en-US') : '0'}</td>
      <td>${taxLabel}</td>
      <td>${r.created_by || ''}</td>
      <td>${r.notes || ''} ${statusBadge}</td>
      <td>
        <div style="display:flex; gap:5px; justify-content:center;">
          <button class="action-btn btn-edit" onclick="editPurchasesReturn(${r.id})" style="padding:5px 10px;">تعديل/عرض</button>
          ${currentUser && currentUser.role === 'مدير عام' ? `<button class="action-btn btn-delete" onclick="deleteInvoice(${r.id}, 'purchases_return')" style="padding:5px 10px;">حذف</button>` : ''}
        </div>
      </td>
    `;
    tbody.appendChild(tr);
  });
};

window.openPurchasesReturnModal = function() {
  document.getElementById('purchases-returns-modal-title').innerText = 'إنشاء فاتورة مرتجع مشتريات (نسخة متطورة)';
  document.getElementById('edit-purchases-returns-id').value = '';
  if(document.getElementById('purchases-returns-link-banner')) document.getElementById('purchases-returns-link-banner').innerHTML = '';
  document.getElementById('purchases-returns-date').value = new Date().toISOString().slice(0, 16);
  if(document.getElementById('purchases-returns-doc-no')) document.getElementById('purchases-returns-doc-no').value = '';
  if(document.getElementById('purchases-returns-total')) document.getElementById('purchases-returns-total').value = '';
  if(document.getElementById('purchases-returns-net')) document.getElementById('purchases-returns-net').value = '';
  if(document.getElementById('purchases-returns-tax-rate')) document.getElementById('purchases-returns-tax-rate').value = '0';
  if(document.getElementById('purchases-returns-tax-amount')) document.getElementById('purchases-returns-tax-amount').value = '';
  if(document.getElementById('purchases-returns-notes')) document.getElementById('purchases-returns-notes').value = '';
  document.getElementById('purchases-returns-status').value = 'draft';
  document.getElementById('btn-save-purchases-returns').style.display = 'inline-block';
  
  const contactSelect = document.getElementById('purchases-returns-contact');
  contactSelect.innerHTML = '<option value="">-- اختر المورد --</option>';
  currentContacts.forEach(c => {
    if (true) { // removed type filter
      contactSelect.innerHTML += `<option value="${c.id}">${c.name} (${c.type || ''})</option>`;
    }
  });

  const treasurySelect = document.getElementById('purchases-returns-treasury');
    if (treasurySelect) {
        treasurySelect.innerHTML = '<option value="">-- آجل (بدون سداد) --</option>';
          currentAccounts.filter(a => a.name.includes('خزينة') || a.name.includes('صندوق') || a.name.includes('بنك')).forEach(a => {
            treasurySelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
          });
    }

  

  // === تعبئة المخازن ===
  const whSelectP = document.getElementById('purchases-returns-warehouse');
  if (whSelectP) {
    const whs = typeof currentWarehouses !== 'undefined' ? currentWarehouses : [];
    whSelectP.innerHTML = '<option value="">-- اختر المخزن --</option>';
    whs.forEach(w => { whSelectP.innerHTML += `<option value="${w.id}">${w.name}</option>`; });
  }
  // === تعبئة المشاريع ===
  const projSelectP = document.getElementById('purchases-returns-project');
  if (projSelectP) {
    const projs = typeof currentProjects !== 'undefined' ? currentProjects : [];
    projSelectP.innerHTML = '<option value="">-- بدون مشروع --</option>';
    projs.forEach(p => { projSelectP.innerHTML += `<option value="${p.id}">${p.name}</option>`; });
  }
  // === تصفير الأصناف ===
  window.currentPurchasesReturnLines = [];
  if (typeof window.renderPurchasesReturnsLines === 'function') window.renderPurchasesReturnsLines();

  document.getElementById('purchases-returns-lines-tbody').innerHTML = '';

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

window.editPurchasesReturn = function(id) {
  const r = allInvoices.find(x => x.id == id && x.type === 'purchases_return');
  if(!r) return;
  openPurchasesReturnModal();
  document.getElementById('purchases-returns-modal-title').innerText = 'تعديل فاتورة مرتجع المشتريات #' + id;
  document.getElementById('edit-purchases-returns-id').value = r.id;
    let plinkContainer = document.getElementById('purchases-returns-link-banner');
    if(!plinkContainer) {
        plinkContainer = document.createElement('div');
        plinkContainer.id = 'purchases-returns-link-banner';
        document.getElementById('purchases-returns-modal-title').after(plinkContainer);
    }
    if (r.linked_invoice_id) {
        plinkContainer.innerHTML = `<div style="margin:10px 0; background:#e3f2fd; padding:10px; border-radius:5px; border-right:4px solid #2196f3;"><a href="#" onclick="closeModal('purchases-returns-modal'); openPurchasesModal(${r.linked_invoice_id}); return false;" style="text-decoration:none; font-weight:bold; color:#0d47a1;">🔗 الانتقال للفاتورة الأصلية رقم #${r.linked_invoice_id}</a></div>`;
    } else {
        plinkContainer.innerHTML = '';
    }
  document.getElementById('purchases-returns-date').value = r.date;
  document.getElementById('purchases-returns-doc-no').value = r.doc_no || '';
  document.getElementById('purchases-returns-contact').value = r.contact_id || '';
  if(document.getElementById('purchases-returns-tax-rate')) document.getElementById('purchases-returns-tax-rate').value = r.tax_rate || 0;
  if(typeof window.loadPurchasesForReturn === 'function') window.loadPurchasesForReturn();
  setTimeout(() => {
     const invSel = document.getElementById('purchases-returns-original-invoice');
     if(invSel) invSel.value = r.linked_invoice_id || '';
  }, 100);
  let pTrEl = document.getElementById('purchases-returns-treasury'); if(pTrEl) pTrEl.value = r.treasury_account_id || '';
  document.getElementById('purchases-returns-total').value = r.total_amount || r.total || '';
  
  // === تعبئة المخزن ===
  const whSelectPEdit = document.getElementById('purchases-returns-warehouse');
  if (whSelectPEdit) {
    const whs = typeof currentWarehouses !== 'undefined' ? currentWarehouses : [];
    whSelectPEdit.innerHTML = '<option value="">-- اختر المخزن --</option>';
    whs.forEach(w => { whSelectPEdit.innerHTML += `<option value="${w.id}" ${String(w.id) === String(r.from_warehouse_id || r.warehouse_id) ? 'selected' : ''}>${w.name}</option>`; });
  }
  // === تعبئة المشروع ===
  const projSelectPEdit = document.getElementById('purchases-returns-project');
  if (projSelectPEdit) {
    const projs = typeof currentProjects !== 'undefined' ? currentProjects : [];
    projSelectPEdit.innerHTML = '<option value="">-- بدون مشروع --</option>';
    projs.forEach(p => { projSelectPEdit.innerHTML += `<option value="${p.id}" ${String(p.id) === String(r.project_id) ? 'selected' : ''}>${p.name}</option>`; });
  }
  
  document.getElementById('purchases-returns-notes').value = r.notes || '';
  document.getElementById('purchases-returns-status').value = r.status || 'draft';
  
  window.currentPurchasesReturnLines = r.items ? JSON.parse(JSON.stringify(r.items)) : [];
  if(typeof window.renderPurchasesReturnsLines === 'function') window.renderPurchasesReturnsLines();
  
  if (r.status === 'posted') {
      document.getElementById('btn-save-purchases-returns').style.display = 'inline-block';
  }
};

const btnSavePurchasesReturns = document.getElementById('btn-save-purchases-returns');
if (btnSavePurchasesReturns) {
  btnSavePurchasesReturns.addEventListener('click', async () => {
    try {
      const id = document.getElementById('edit-purchases-returns-id').value;
      const net = parseFloat(document.getElementById('purchases-returns-net').value) || 0;
      
      const existingInv = id ? allInvoices.find(x => String(x.id) === String(id)) : null;
      const wasAlreadyPosted = existingInv && (existingInv.status === 'posted' || existingInv.status === 'financial_only');

      if (wasAlreadyPosted) {
          const notes = document.getElementById('purchases-returns-notes').value;
          existingInv.notes = notes;
          await window.DB.update('transactions', existingInv);
          closeModal('purchases-returns-modal');
          if (window.loadData) await window.loadData();
          alert('تم حفظ الملاحظات بنجاح (لا يمكن تعديل تفاصيل المرتجع بعد اعتماده).');
          return;
      }
      
      const taxRate = parseFloat(document.getElementById('purchases-returns-tax-rate').value) || 0;
      const taxAmount = parseFloat(document.getElementById('purchases-returns-tax-amount').value) || 0;
      const amount = parseFloat(document.getElementById('purchases-returns-total').value) || 0;
      const r = {
        date: document.getElementById('purchases-returns-date').value,
        doc_no: document.getElementById('purchases-returns-doc-no').value,
        contact_id: parseInt(document.getElementById('purchases-returns-contact').value) || null,
        treasury_account_id: parseInt(document.getElementById('purchases-returns-treasury')?.value) || null,
        linked_invoice_id: document.getElementById('purchases-returns-original-invoice').value || null,
        from_warehouse_id: parseInt(document.getElementById('purchases-returns-warehouse').value) || null,
        from_warehouse_name: (() => { const whId = parseInt(document.getElementById('purchases-returns-warehouse').value); const whs = typeof currentWarehouses !== 'undefined' ? currentWarehouses : []; return whs.find(w => w.id === whId)?.name || ''; })(),
        project_id: parseInt(document.getElementById('purchases-returns-project')?.value) || null,
        total: amount,
        total_amount: amount,
        net_before_tax: net,
        tax_rate: taxRate,
        tax_amount: taxAmount,
        notes: document.getElementById('purchases-returns-notes').value,
        status: document.getElementById('purchases-returns-status').value,
        type: 'purchases_return',
        items: window.currentPurchasesReturnLines ? JSON.parse(JSON.stringify(window.currentPurchasesReturnLines)) : [],
        created_by: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'نظام',
        user: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'نظام'
      };

      if(!r.contact_id) { alert('يرجى اختيار المورد'); return; }
      if(!r.total_amount) { alert('يرجى إدخال إجمالي المرتجع'); return; }

      if (id) {
        r.id = parseInt(id);
        await window.DB.update('transactions', r);
        if (r.status === 'pending_store') {
            if (typeof window.sendInvoiceToStore === 'function') await window.sendInvoiceToStore(r.id); else await sendPurchasesReturnToStore(r);
        } else if (r.status === 'posted') {
            await generatePurchasesReturnJournal(r);
            if (typeof window.sendInvoiceToStore === 'function') await window.sendInvoiceToStore(r.id); else await sendPurchasesReturnToStore(r);
        } else if (r.status === 'financial_only') {
            await generatePurchasesReturnJournal(r);
        } else {
            // draft - remove any old journal
            const allJournals = await window.DB.getAll('journal_entries');
            const oldJ = allJournals.find(j => j.reference === 'purchases_return_' + r.id);
            if (oldJ) await window.DB.remove('journal_entries', oldJ.id);
        }
      } else {
        delete r.id; // Let backend assign ID
        const newId = await window.DB.add('transactions', r);
        r.id = newId;
        if (r.status === 'pending_store') {
            if (typeof window.sendInvoiceToStore === 'function') await window.sendInvoiceToStore(r.id); else await sendPurchasesReturnToStore(r);
        } else if (r.status === 'posted') {
            await generatePurchasesReturnJournal(r);
            if (typeof window.sendInvoiceToStore === 'function') await window.sendInvoiceToStore(r.id); else await sendPurchasesReturnToStore(r);
        } else if (r.status === 'financial_only') {
            await generatePurchasesReturnJournal(r);
        }
      }

      closeModal('purchases-returns-modal');
      if (window.loadData) await window.loadData();
      if(typeof renderPurchasesReturns === 'function') renderPurchasesReturns();
    } catch(err) {
      console.error('Purchases return save error:', err);
      alert('حدث خطأ أثناء الحفظ:\n' + (err.message || err));
    }
  });
}

// =============================================
// إرسال مرتجع المشتريات لأمين المخزن
// =============================================
window._sendingPurchasesReturnToStore = window._sendingPurchasesReturnToStore || {};

async function sendPurchasesReturnToStore(inv) {
  if (window._sendingPurchasesReturnToStore[inv.id]) return;
  window._sendingPurchasesReturnToStore[inv.id] = true;
  try {
    const users = typeof currentUsers !== 'undefined' ? currentUsers : await window.DB.getAll('users');
    const contactName = (typeof currentContacts !== 'undefined' ? currentContacts : []).find(c => String(c.id) === String(inv.contact_id))?.name || 'مورد';
    const warehouseName = inv.from_warehouse_id
      ? ((typeof currentWarehouses !== 'undefined' ? currentWarehouses : []).find(w => String(w.id) === String(inv.from_warehouse_id))?.name || 'المخزن')
      : 'المخزن';

    // إشعار لكل أمين مخزن
    const storekeepers = users.filter(u =>
      u.role === 'أمين مخزن' || u.role === 'أمينة مخزن' || u.role === 'مدير مخازن' ||
      (u.warehouse_id && String(u.warehouse_id) === String(inv.from_warehouse_id))
    );

    const existingNotifs = await window.DB.getAll('notifications') || [];
    const sentTo = new Set();

    for (let sk of storekeepers) {
      if (sentTo.has(sk.username)) continue;
      
      const exists = existingNotifs.find(n => n.user === sk.username && String(n.invoice_id) === String(inv.id));
      if (!exists) {
        sentTo.add(sk.username);
        await window.DB.add('notifications', {
          user: sk.username,
          invoice_id: inv.id,
          message: `مرتجع مشتريات #${inv.id} من مورد (${contactName}) بانتظار اعتمادك وتسجيل خروج البضاعة من ${warehouseName}.`,
          date: new Date().toISOString(),
          read: false
        });
      }
    }

    // إشعار للمدير العام دائماً
    const managers = users.filter(u => u.role === 'مدير عام');
    for (let mg of managers) {
      if (mg.username === inv.created_by) continue;
      if (sentTo.has(mg.username)) continue;
      
      const exists = existingNotifs.find(n => n.user === mg.username && String(n.invoice_id) === String(inv.id));
      if (!exists) {
        sentTo.add(mg.username);
        await window.DB.add('notifications', {
          user: mg.username,
          invoice_id: inv.id,
          message: `تم إنشاء مرتجع مشتريات #${inv.id} بواسطة ${inv.created_by || 'النظام'} — بانتظار اعتماد المخزن.`,
          date: new Date().toISOString(),
          read: false
        });
      }
    }
  } catch(e) {
    console.error('sendPurchasesReturnToStore error:', e);
  } finally {
    delete window._sendingPurchasesReturnToStore[inv.id];
  }
  alert('تم حفظ مرتجع المشتريات وإرسال الإشعار للمخزن بنجاح.');
}

async function generatePurchasesReturnJournal(invoice) {
  const accounts = typeof currentAccounts !== 'undefined' ? currentAccounts : [];
  const amount = parseFloat(invoice.total_amount || invoice.total || 0);
  if (!amount) return;

  // === فواتير المرتجعات الاحترافية v4 ===
console.log('--- NEW VOUCHERS RETURNS LOADED (v4, Lock + Deduplication) ---');
  let purchasesReturnAcc = accounts.find(a =>
    a.name.includes('مرتجع') && (a.name.includes('مشتري') || a.name.includes('شراء'))
  ) || accounts.find(a => a.name.includes('مردود') && a.name.includes('مشتري'))
    || accounts.find(a => a.name.includes('مرتجعات') && !a.name.includes('مبيع'));

  if (!purchasesReturnAcc) {
    const newAccId = Date.now() + 3;
    const newAcc = { id: newAccId, code: '5100', name: 'مرتجعات المشتريات', type: 'مصروف', balance: 0 };
    await window.DB.add('accounts', newAcc);
    if (window.loadData) await window.loadData();
    purchasesReturnAcc = newAcc;
  }

  // === البحث عن حساب الموردين أو الخزينة ===
  let debitAccId = null;
  if (invoice.treasury_account_id) {
    debitAccId = invoice.treasury_account_id;
  } else {
    let supAcc = accounts.find(a => a.name.includes('مورد') || a.name.includes('دائنون'));
    if (!supAcc) {
      const newAccId2 = Date.now() + 4;
      const newAcc2 = { id: newAccId2, code: '2100', name: 'حسابات الموردين', type: 'التزام', balance: 0 };
      await window.DB.add('accounts', newAcc2);
      if (window.loadData) await window.loadData();
      supAcc = newAcc2;
    }
    debitAccId = supAcc.id;
  }

  let invAcc = accounts.find(a => a.name.includes('مخزون') || a.name === 'مخزون');
  let discountAcc = accounts.find(a => a.name === 'خصم مكتسب' || a.name === 'الخصم المكتسب');
  let taxAcc = accounts.find(a => a.name.includes('ضريب') || a.name.includes('ضرائب'));

  if (!invAcc && typeof window.resolveSystemAccount === 'function') {
      invAcc = await window.resolveSystemAccount('مخزون البضاعة', ['أصول متداولة', 'الأصول'], 'assets');
  }
  if (!discountAcc && typeof window.resolveSystemAccount === 'function') {
      discountAcc = await window.resolveSystemAccount('الخصم المكتسب', ['الإيرادات', 'إيرادات'], 'revenues');
  }
  if (!taxAcc && typeof window.resolveSystemAccount === 'function') {
      taxAcc = await window.resolveSystemAccount('الضرائب', ['الخصوم', 'التزامات'], 'liabilities');
  }

  let computedGross = 0;
  let totalDiscount = 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 totalDebit = 0;

  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}` : '';

  const journalId = Date.now() + Math.floor(Math.random() * 10000);
  const journal = {
    id: journalId,
    date: invoice.date,
    desc: 'مرتجع مشتريات ' + (invoice.doc_no ? '#' + invoice.doc_no : '#' + invoice.id) + contactSuffix + (invoice.notes ? ' - ' + invoice.notes : ''),
    reference: 'purchases_return_' + invoice.id,
    project_id: invoice.project_id || null,
    status: 'posted',
    total: 0,
    created_by: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'النظام',
    rows: []
  };

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

  // Debit Discount Received (reversing income)
  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;
  }

  // Credit Inventory (Gross cost)
  journal.rows.push({ account_id: invAcc.id, debit: 0, credit: grossTotal, project_id: invoice.project_id, notes: `منصرف مخزون مرتجع مشتريات ${invoice.id}` });

  // Credit Tax (reversing liability)
  if (taxAmount > 0 && taxAcc) {
      journal.rows.push({ account_id: taxAcc.id, debit: 0, credit: taxAmount, project_id: invoice.project_id, notes: `إلغاء ضريبة مرتجع مشتريات ${invoice.id}` });
  }

  journal.total = totalDebit;

  const allJournals = await window.DB.getAll('journal_entries');
  const existingJList = allJournals.filter(j => j.reference === 'purchases_return_' + invoice.id);
  for (let ej of existingJList) {
      if (window.DB && window.DB.remove) await window.DB.remove('journal_entries', ej.id);
  }
  await window.DB.add('journal_entries', journal);
}

window.loadSalesForReturn = function() {
    const contactId = document.getElementById('sales-returns-contact').value;
    const invSelect = document.getElementById('sales-returns-original-invoice');
    if(!invSelect) return;
    invSelect.innerHTML = '<option value="">-- اختر الفاتورة الأصلية --</option>';
    if (!contactId) return;

    // استخدام allInvoices مباشرة (مش window.allInvoices)
    const allInv = (typeof allInvoices !== 'undefined' ? allInvoices : []);
    const salesInv = allInv.filter(inv => inv.type === 'sales' && String(inv.contact_id) === String(contactId));
    
    if (salesInv.length === 0) {
        invSelect.innerHTML += '<option disabled>-- لا توجد فواتير مبيعات لهذه الجهة --</option>';
        return;
    }
    salesInv.forEach(inv => {
        const statusStr = inv.status === 'draft' ? ' (مسودة)' : ' (مرحلة)';
        const d = inv.date ? new Date(inv.date).toLocaleDateString('ar-EG') : '';
        const total = parseFloat(inv.total || 0).toLocaleString('en-US');
        invSelect.innerHTML += `<option value="${inv.id}">فاتورة مبيعات #${inv.id} | ${d} | ${total} ج.م${statusStr}</option>`;
    });
};

window.populateSalesReturnFromInvoice = function() {
    const invId = document.getElementById('sales-returns-original-invoice').value;
    if (!invId) {
        window.currentSalesReturnLines = [];
        if(typeof window.renderSalesReturnsLines === 'function') window.renderSalesReturnsLines();
        return;
    }

    const allInv = (typeof allInvoices !== 'undefined' ? allInvoices : []);
    const invoice = allInv.find(inv => String(inv.id) === String(invId));
    if (!invoice) return;

    if (invoice.from_warehouse_id) {
        const whSelect = document.getElementById('sales-returns-warehouse');
        if(whSelect) whSelect.value = invoice.from_warehouse_id;
    }
    if (invoice.project_id) {
        const projSelect = document.getElementById('sales-returns-project');
        if(projSelect) projSelect.value = invoice.project_id;
    }

    if (document.getElementById('sales-returns-tax-rate')) {
        document.getElementById('sales-returns-tax-rate').value = invoice.tax_rate || 0;
    }

    window.currentSalesReturnLines = JSON.parse(JSON.stringify(invoice.items || [])).map(item => {
        item.max_qty = item.qty;
        return item;
    });
    if(typeof window.renderSalesReturnsLines === 'function') window.renderSalesReturnsLines();
};

window.loadPurchasesForReturn = function() {
    const contactId = document.getElementById('purchases-returns-contact').value;
    const invSelect = document.getElementById('purchases-returns-original-invoice');
    if(!invSelect) return;
    invSelect.innerHTML = '<option value="">-- اختر الفاتورة الأصلية --</option>';
    if (!contactId) return;

    const allInv = (typeof allInvoices !== 'undefined' ? allInvoices : []);
    const purchInv = allInv.filter(inv => inv.type === 'purchases' && String(inv.contact_id) === String(contactId));

    if (purchInv.length === 0) {
        invSelect.innerHTML += '<option disabled>-- لا توجد فواتير مشتريات لهذه الجهة --</option>';
        return;
    }
    purchInv.forEach(inv => {
        const statusStr = inv.status === 'draft' ? ' (مسودة)' : ' (مرحلة)';
        const d = inv.date ? new Date(inv.date).toLocaleDateString('ar-EG') : '';
        const total = parseFloat(inv.total || 0).toLocaleString('en-US');
        invSelect.innerHTML += `<option value="${inv.id}">فاتورة مشتريات #${inv.id} | ${d} | ${total} ج.م${statusStr}</option>`;
    });
};

window.populatePurchasesReturnFromInvoice = function() {
    const invId = document.getElementById('purchases-returns-original-invoice').value;
    if (!invId) {
        window.currentPurchasesReturnLines = [];
        if(typeof window.renderPurchasesReturnsLines === 'function') window.renderPurchasesReturnsLines();
        return;
    }

    const allInv = (typeof allInvoices !== 'undefined' ? allInvoices : []);
    const invoice = allInv.find(inv => String(inv.id) === String(invId));
    if (!invoice) return;

    if (invoice.to_warehouse_id) {
        const whSelect = document.getElementById('purchases-returns-warehouse');
        if(whSelect) whSelect.value = invoice.to_warehouse_id;
    }
    if (invoice.project_id) {
        const projSelect = document.getElementById('purchases-returns-project');
        if(projSelect) projSelect.value = invoice.project_id;
    }

    if (document.getElementById('purchases-returns-tax-rate')) {
        document.getElementById('purchases-returns-tax-rate').value = invoice.tax_rate || 0;
    }

    window.currentPurchasesReturnLines = JSON.parse(JSON.stringify(invoice.items || [])).map(item => {
        item.max_qty = item.qty;
        return item;
    });
    if(typeof window.renderPurchasesReturnsLines === 'function') window.renderPurchasesReturnsLines();
};

window.renderSalesReturnsLines = function() {
    const tbody = document.getElementById('sales-returns-lines-tbody');
    if(!tbody) return;
    tbody.innerHTML = '';
    let total = 0;
    (window.currentSalesReturnLines || []).forEach((line, idx) => {
        const lineTotalBeforeDiscount = (line.qty * line.price);
        let lineDiscountValue = parseFloat(line.discount) || 0;
        if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }
        const lineTotal = lineTotalBeforeDiscount - lineDiscountValue;
        total += lineTotal;
        
        tbody.innerHTML += `<tr>
            <td>${line.item_name || ((typeof currentItems !== 'undefined' ? currentItems : (window.currentItems||[])).find(i=>i.id==line.item_id)?.name || '')}</td>
            <td>
                <input type="number" min="0" max="${line.max_qty !== undefined ? line.max_qty : ''}" step="0.01" value="${line.qty}" onchange="updateSalesReturnQty(${idx}, this.value)" style="width:60px;">
                ${line.max_qty !== undefined ? `<br><small style="color:#666">أقصى: ${line.max_qty}</small>` : ''}
            </td>
            <td>${line.price}</td>
            <td>${line.discountType === 'percent' ? line.discount + '%' : lineDiscountValue}</td>
            <td>${lineTotal.toLocaleString('en-US')}</td>
            <td><button class="action-btn btn-delete" onclick="deleteSalesReturnLine(${idx})">حذف</button></td>
        </tr>`;
    });
    
    const netEl = document.getElementById('sales-returns-net');
    if(netEl) netEl.value = total.toFixed(2);
    
    const taxRate = parseFloat(document.getElementById('sales-returns-tax-rate')?.value) || 0;
    const taxAmount = total * (taxRate / 100);
    const grandTotal = total + taxAmount;
    
    const taxAmountEl = document.getElementById('sales-returns-tax-amount');
    if(taxAmountEl) taxAmountEl.value = taxAmount.toFixed(2);
    
    const totalEl = document.getElementById('sales-returns-total');
    if(totalEl) totalEl.value = grandTotal.toFixed(2);
};

window.calculateSalesReturnsTotal = function() {
    window.renderSalesReturnsLines();
};

window.updateSalesReturnQty = function(idx, newQty) {
    let qty = parseFloat(newQty) || 0;
    const maxQty = window.currentSalesReturnLines[idx].max_qty;
    if (maxQty !== undefined && qty > maxQty) {
        alert('لا يمكن إرجاع كمية أكبر من الكمية الأصلية في الفاتورة (' + maxQty + ')');
        qty = maxQty;
    }
    window.currentSalesReturnLines[idx].qty = qty;
    window.renderSalesReturnsLines();
};

window.deleteSalesReturnLine = function(idx) {
    window.currentSalesReturnLines.splice(idx, 1);
    window.renderSalesReturnsLines();
};

window.renderPurchasesReturnsLines = function() {
    const tbody = document.getElementById('purchases-returns-lines-tbody');
    if(!tbody) return;
    tbody.innerHTML = '';
    let total = 0;
    (window.currentPurchasesReturnLines || []).forEach((line, idx) => {
        const lineTotalBeforeDiscount = (line.qty * line.price);
        let lineDiscountValue = parseFloat(line.discount) || 0;
        if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }
        const lineTotal = lineTotalBeforeDiscount - lineDiscountValue;
        total += lineTotal;
        
        tbody.innerHTML += `<tr>
            <td>${line.item_name || ((typeof currentItems !== 'undefined' ? currentItems : (window.currentItems||[])).find(i=>i.id==line.item_id)?.name || '')}</td>
            <td>
                <input type="number" min="0" max="${line.max_qty !== undefined ? line.max_qty : ''}" step="0.01" value="${line.qty}" onchange="updatePurchasesReturnQty(${idx}, this.value)" style="width:60px;">
                ${line.max_qty !== undefined ? `<br><small style="color:#666">أقصى: ${line.max_qty}</small>` : ''}
            </td>
            <td>${line.price}</td>
            <td>${line.discountType === 'percent' ? line.discount + '%' : lineDiscountValue}</td>
            <td>${lineTotal.toLocaleString('en-US')}</td>
            <td><button class="action-btn btn-delete" onclick="deletePurchasesReturnLine(${idx})">حذف</button></td>
        </tr>`;
    });
    
    const netEl = document.getElementById('purchases-returns-net');
    if(netEl) netEl.value = total.toFixed(2);
    
    const taxRate = parseFloat(document.getElementById('purchases-returns-tax-rate')?.value) || 0;
    const taxAmount = total * (taxRate / 100);
    const grandTotal = total + taxAmount;
    
    const taxAmountEl = document.getElementById('purchases-returns-tax-amount');
    if(taxAmountEl) taxAmountEl.value = taxAmount.toFixed(2);
    
    const totalEl = document.getElementById('purchases-returns-total');
    if(totalEl) totalEl.value = grandTotal.toFixed(2);
};

window.calculatePurchasesReturnsTotal = function() {
    window.renderPurchasesReturnsLines();
};

window.updatePurchasesReturnQty = function(idx, newQty) {
    let qty = parseFloat(newQty) || 0;
    const maxQty = window.currentPurchasesReturnLines[idx].max_qty;
    if (maxQty !== undefined && qty > maxQty) {
        alert('لا يمكن إرجاع كمية أكبر من الكمية الأصلية في الفاتورة (' + maxQty + ')');
        qty = maxQty;
    }
    window.currentPurchasesReturnLines[idx].qty = qty;
    window.renderPurchasesReturnsLines();
};

window.deletePurchasesReturnLine = function(idx) {
    window.currentPurchasesReturnLines.splice(idx, 1);
    window.renderPurchasesReturnsLines();
};



// Aliases for HTML buttons
window.openSalesReturnsModal = window.openSalesReturnModal;
window.openPurchasesReturnsModal = window.openPurchasesReturnModal;
