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

window.resolveSystemAccount = async function(accountName, parentKeywords, accountType, alternateNames) {
    let acc = currentAccounts.find(a => a.name.trim() === accountName.trim());
    if (acc) return acc;
    
    if (alternateNames && alternateNames.length > 0) {
        acc = currentAccounts.find(a => alternateNames.includes(a.name.trim()));
        if (acc) return acc;
    }

    let parentAcc = null;
    if (parentKeywords && parentKeywords.length > 0) {
        parentAcc = currentAccounts.find(a => parentKeywords.some(k => a.name === k || a.name.includes(k)));
    }

    try {
        const newAcc = {
            code: Date.now().toString().slice(-6),
            name: accountName,
            type: accountType || (parentAcc ? parentAcc.type : 'revenues'),
            parent_id: parentAcc ? parentAcc.id : null,
            balance: 0
        };
        const addedId = await window.DB.add('accounts', newAcc);
        newAcc.id = addedId;
        currentAccounts.push(newAcc);
        if (window.loadData) window.loadData(false);
        return newAcc;
    } catch (e) {
        console.error("Failed to auto-create system account", e);
        return parentAcc;
    }
};


window.resolveContactAccount = async function(contactId, type) {
    let genericName = (type === 'sales' || type === 'receipt') ? 'حسابات العملاء' : 'حسابات الموردين';
    let accountType = (type === 'sales' || type === 'receipt') ? 'assets' : 'liabilities';
    let keywords = (type === 'sales' || type === 'receipt') ? ['عملاء', 'عميل'] : ['موردين', 'مورد'];
    
    // 1. Find generic account
    let genericAcc = currentAccounts.find(a => keywords.some(k => a.name.includes(k)));
    if (genericAcc) return genericAcc;
    
    // 2. Auto-create GENERIC account if missing
    try {
        const newAcc = {
            code: Date.now().toString().slice(-6),
            name: genericName,
            type: accountType,
            parent_id: null,
            balance: 0
        };
        const addedId = await window.DB.add('accounts', newAcc);
        newAcc.id = addedId;
        currentAccounts.push(newAcc);
        if (window.loadData) window.loadData(false);
        return newAcc;
    } catch (e) {
        console.error("Failed to auto-create generic account", e);
        return null;
    }
};
// State - معرّف في app_final.js


// Elements


// --- ACCOUNTING & JOURNALS LOGIC ---
function renderAccounts() {
  const tbody = document.getElementById('accounts-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  if (currentAccounts.length === 0) {
    tbody.innerHTML = '<tr><td colspan="10" style="text-align:center; padding: 20px; color:#666;">لا توجد حسابات حالياً. اضغط على زر "+ حساب جديد" لإضافة الحسابات.</td></tr>';
    return;
  }
  
  const accBalances = {};
  (currentAccounts || []).forEach(a => {
    accBalances[a.id] = {
       op_debit: parseFloat(a.op_debit) || 0,
       op_credit: parseFloat(a.op_credit) || 0,
       mov_debit: 0,
       mov_credit: 0
    };
  });

  currentJournals.filter(j => j.status === 'posted').forEach(j => {
    if(j.rows) {
      (j.rows || []).forEach(r => {
        if(r.account_id && accBalances[r.account_id]) {
          accBalances[r.account_id].mov_debit += (parseFloat(r.debit) || 0);
          accBalances[r.account_id].mov_credit += (parseFloat(r.credit) || 0);
        }
      });
    }
  });

  const depths = {};
  function getDepth(id) {
    if (depths[id] !== undefined) return depths[id];
    const acc = currentAccounts.find(a => String(a.id) === String(id));
    if (!acc || !acc.parent_id || String(acc.parent_id) === 'null') return 0;
    depths[id] = 0;
    depths[id] = 1 + getDepth(acc.parent_id);
    return depths[id];
  }
  const sortedForSum = [...currentAccounts].sort((a, b) => getDepth(b.id) - getDepth(a.id));
  (sortedForSum || []).forEach(a => {
    let pid = a.parent_id ? String(a.parent_id) : null;
    let myid = a.id ? String(a.id) : null;
    if (pid && pid !== 'null' && accBalances[pid] && accBalances[myid]) {
      accBalances[pid].op_debit += accBalances[myid].op_debit;
      accBalances[pid].op_credit += accBalances[myid].op_credit;
      accBalances[pid].mov_debit += accBalances[myid].mov_debit;
      accBalances[pid].mov_credit += accBalances[myid].mov_credit;
    }
  });

  window.expandedAccounts = window.expandedAccounts || {};
  
  function renderTree(parentId, level = 0, isVisible = true) {
    const children = currentAccounts.filter(a => String(a.parent_id || '') === String(parentId || '')).sort((a,b) => (a.code || '').localeCompare(b.code || ''));
    (children || []).forEach(acc => {
      let actions = `<button class="action-btn" style="background:#17a2b8; color:#fff; padding:5px 10px;" onclick="openAccountStatement(${acc.id})">📄 كشف حساب</button>`;
      let canManageAccounts = false;
      if (currentUser) {
          if (currentUser.role === 'مدير عام' || currentUser.role === 'مدير نظام') canManageAccounts = true;
          if (currentUser.allowed_actions && currentUser.allowed_actions.includes('manage-accounts')) canManageAccounts = true;
      }
      if(canManageAccounts) {
          actions += `<button class="action-btn btn-edit" onclick="openAccountModal(${acc.id})">✏️ تعديل</button>
                   <button class="action-btn btn-view" onclick="openAccountModal(null, ${acc.id})">➕ فرعي</button>
                   <button class="action-btn btn-delete" onclick="deleteAccount(${acc.id})">🗑️ حذف</button>`;
      }
      
      const accChildren = currentAccounts.filter(a => a.parent_id === acc.id);
      const indent = level * 30;
      const isExpanded = window.expandedAccounts[acc.id] !== false; 
      const hasChildren = accChildren.length > 0;
      
      let isRoot = (level === 0);
      let icon = '';
      if (hasChildren) {
          let folderColor = isRoot ? '#00a896' : '#f39c12';
          icon = isExpanded ? `<i class="fas fa-folder-open" style="color:${folderColor}; margin-left:8px; font-size:1.1em;"></i>` : `<i class="fas fa-folder" style="color:${folderColor}; margin-left:8px; font-size:1.1em;"></i>`;
      } else {
          icon = '<i class="fas fa-file-invoice" style="color:#95a5a6; margin-left:8px;"></i>';
      }
      
      const displayStyle = isVisible ? '' : 'display:none;';
      
      let rowStyle = '';
      let nameStyle = '';
      let codeStyle = '';
      
      if (level === 0) {
          rowStyle = 'background: rgba(0, 168, 150, 0.1); border-bottom: 2px solid #00a896;';
          nameStyle = `padding-right: ${indent + 10}px; cursor:pointer; user-select:none; color: #00a896; font-size: 1.15em; font-weight: 900;`;
          codeStyle = 'font-weight:bold; color:#00a896; font-size: 1.1em;';
      } else if (level === 1) {
          rowStyle = 'background: rgba(44, 62, 80, 0.04); border-bottom: 1px solid rgba(44, 62, 80, 0.1);';
          nameStyle = `padding-right: ${indent + 10}px; cursor:pointer; user-select:none; color: #2c3e50; font-size: 1.05em; font-weight: 800; border-right: 4px solid #2c3e50;`;
          codeStyle = 'font-weight:bold; color:#2c3e50;';
      } else if (level === 2) {
          rowStyle = 'background: rgba(52, 152, 219, 0.02); border-bottom: 1px solid rgba(52, 152, 219, 0.05);';
          nameStyle = `padding-right: ${indent + 10}px; cursor:pointer; user-select:none; color: #34495e; font-weight: 700; border-right: 3px solid #3498db;`;
          codeStyle = 'font-weight:bold; color:#34495e;';
      } else {
          rowStyle = 'background: #fff; border-bottom: 1px dashed #eee;';
          nameStyle = `padding-right: ${indent + 10}px; cursor:pointer; user-select:none; color: #7f8c8d; font-weight: 600; border-right: 2px solid #bdc3c7;`;
          codeStyle = 'font-weight:normal; color:#95a5a6;';
      }
      
      // Draw tree branch line for sub-accounts
      let branchHtml = '';
      if (level > 0) {
          branchHtml = '<div style="position:absolute; right:' + (indent - 10) + 'px; top:50%; width:15px; border-top:1px dashed #ccc;"></div>' +
                       '<div style="position:absolute; right:' + (indent - 10) + 'px; top:0; height:50%; border-right:1px dashed #ccc;"></div>';
      }
      
      tbody.innerHTML += `<tr class="acc-row" style="${rowStyle} ${displayStyle}">
        <td style="${codeStyle}">${acc.code}</td>
        <td style="position:relative; ${nameStyle}" onclick="toggleAccount(${acc.id})">${branchHtml}${icon} ${acc.name}</td>
        <td><span style="background:#e8f4f8; color:#2980b9; padding:3px 8px; border-radius:12px; font-size:0.9em;">${acc.type}</span></td>
        <td>${actions}</td>
      </tr>`;
      
      renderTree(acc.id, level + 1, isVisible && isExpanded);
    });
  }
  
  renderTree('', 0, true);

}

window.toggleAccount = function(id) {
  window.expandedAccounts[id] = window.expandedAccounts[id] === false ? true : false;
  renderAccounts();
}

window.openAccountModal = function(id = null, parentId = null) {
  document.getElementById('acc-modal-title').innerText = id ? 'تعديل حساب' : 'إضافة حساب جديد';
  document.getElementById('edit-acc-id').value = id || '';
  
  const datalist = document.getElementById('acc-parent-list');
  if (datalist) {
    datalist.innerHTML = currentAccounts.map(a => `<option data-id="${a.id}" value="${a.code} - ${a.name}"></option>`).join('');
  }
  const inputEl = document.getElementById('acc-parent-input');

  if(id) {
    const acc = currentAccounts.find(x => String(x.id) === String(id));
    document.getElementById('acc-name').value = acc.name;
    document.getElementById('acc-op-debit').value = acc.op_debit || 0;
    document.getElementById('acc-op-credit').value = acc.op_credit || 0;
    if (inputEl) {
        const parentAcc = currentAccounts.find(x => String(x.id) === String(acc.parent_id));
        inputEl.value = parentAcc ? `${parentAcc.code} - ${parentAcc.name}` : '';
    }
  } else {
    document.getElementById('acc-name').value = '';
    document.getElementById('acc-op-debit').value = 0;
    document.getElementById('acc-op-credit').value = 0;
    if (inputEl) {
        const parentAcc = currentAccounts.find(x => String(x.id) === String(parentId));
        inputEl.value = parentAcc ? `${parentAcc.code} - ${parentAcc.name}` : '';
    }
  }
  showModal('account-modal');
}

document.getElementById('btn-save-account')?.addEventListener('click', async () => {
  const name = document.getElementById('acc-name').value;
  const opDebit = parseFloat(document.getElementById('acc-op-debit').value) || 0;
  const opCredit = parseFloat(document.getElementById('acc-op-credit').value) || 0;
  const parentInputVal = document.getElementById('acc-parent-input') ? document.getElementById('acc-parent-input').value : '';
  const parentAccMatch = currentAccounts.find(a => `${a.code} - ${a.name}` === parentInputVal);
  const parentIdStr = parentAccMatch ? parentAccMatch.id : null;
  const idStr = document.getElementById('edit-acc-id').value;
  if(!name) { alert('أدخل اسم الحساب'); return; }
  
  let parentId = parentIdStr ? parseInt(parentIdStr) : null;
  let code = '';
  let type = '';

  if (parentId) {
    const parent = currentAccounts.find(a => String(a.id) === String(parentId));
    type = parent.type;
    const children = currentAccounts.filter(a => a.parent_id === parentId);
    code = parent.code + (children.length + 1).toString();
  } else {
    const roots = currentAccounts.filter(a => !a.parent_id);
    code = (roots.length + 1).toString();
    type = 'أصول'; 
  }

  if(idStr) {
    const existing = currentAccounts.find(a => String(a.id) === idStr);
    if (existing) {
        // Update code if parent changed
        if (parentId && existing.parent_id !== parentId) {
            existing.code = code;
        }
        Object.assign(existing, { name, type, parent_id: parentId, op_debit: opDebit, op_credit: opCredit });
        await window.DB.update('accounts', existing);
    }
  } else {
    const obj = { name, type, parent_id: parentId, op_debit: opDebit, op_credit: opCredit, balance: 0, code: code };
    await window.DB.add('accounts', obj);
  }
  closeModal('account-modal');
  await loadData();
});

window.deleteAccount = async function(id) {
  if(!confirm('هل أنت متأكد من حذف الحساب؟ سيتم حذف جميع الحسابات الفرعية التابعة له أيضاً.')) return;
  
  async function deleteRecursively(accId) {
    const children = currentAccounts.filter(a => a.parent_id === accId);
    for(let child of children) {
      await deleteRecursively(child.id);
    }
    await window.DB.remove('accounts', accId);
  }
  
  await deleteRecursively(id);
  await loadData();
}

window.showAccountingTab = function(tab) {
  document.getElementById('tab-chart').style.display = tab === 'chart' ? 'block' : 'none';
  document.getElementById('tab-journals').style.display = tab === 'journals' ? 'block' : 'none';
  document.getElementById('tab-btn-chart').className = tab === 'chart' ? 'modern-tab-btn active' : 'modern-tab-btn';
  document.getElementById('tab-btn-journals').className = tab === 'journals' ? 'modern-tab-btn active' : 'modern-tab-btn';
};

window.openJournalModal = function(id = null) {
  document.getElementById('je-modal-title').innerText = id ? 'تعديل قيد' : 'إنشاء قيد يومية';
  document.getElementById('edit-je-id').value = id || '';
  const tbody = document.getElementById('je-tbody');
  if(tbody) tbody.innerHTML = '';
  
  if(id) {
    const je = currentJournals.find(x => String(x.id) === String(id));
    document.getElementById('je-date').value = je.date;
    document.getElementById('je-ref').value = je.reference || '';
    document.getElementById('je-desc').value = je.desc || '';
    document.getElementById('je-status').value = je.status || 'draft';
    if(typeof renderRelatedLinks === 'function') renderRelatedLinks('journal', id, 'journal-related-links');
    if(je.rows && je.rows.length > 0) {
      (je.rows || []).forEach(r => window.addJournalLine(r.account_id, r.debit, r.credit, r.project_id, r.notes || r.desc || '', r.contact_id || ''));
    } else {
      window.addJournalLine(); window.addJournalLine();
    }
  } else {
    document.getElementById('je-date').value = new Date().toISOString().split('T')[0];
    document.getElementById('je-ref').value = '';
    document.getElementById('je-desc').value = '';
    document.getElementById('je-status').value = 'draft';
    if (document.getElementById('journal-related-links')) document.getElementById('journal-related-links').style.display = 'none';
    window.addJournalLine(); window.addJournalLine();
  }
  window.calcJournalTotals();
  showModal('journal-modal');
}

window.addJournalLine = function(accountId = '', debit = 0, credit = 0, projectId = '', notes = '', contactId = '') {
  const tbody = document.getElementById('je-tbody');
  const tr = document.createElement('tr');
  
  let projOptions = '<option value="">بدون مشروع</option>';
  (currentProjects || []).forEach(p => {
    projOptions += `<option value="${p.id}" ${projectId==p.id?'selected':''}>${p.name}</option>`;
  });

  let contactOptions = '<option value="">بدون جهة</option>';
  if(typeof currentContacts !== 'undefined') {
      (currentContacts || []).forEach(c => {
          contactOptions += `<option value="${c.id}" ${String(contactId)===String(c.id)?'selected':''}>${c.name}</option>`;
      });
  }

  tr.innerHTML = `
    <td class="acc-cascade-td" style="min-width: 400px; max-width: 600px; vertical-align: top; padding-top: 10px; display: flex; flex-wrap: nowrap; gap: 5px;"></td>
    <td style="vertical-align: top;"><input type="number" class="je-debit" value="${debit}" min="0" onchange="calcJournalTotals()" style="width: 100px;"></td>
    <td style="vertical-align: top;"><input type="number" class="je-credit" value="${credit}" min="0" onchange="calcJournalTotals()" style="width: 100px;"></td>
    <td style="vertical-align: top;"><input type="text" class="je-notes" value="${notes}" placeholder="البيان" style="width: 100%; padding: 6px; box-sizing: border-box;"></td>
    <td style="vertical-align: top;"><select class="je-project">${projOptions}</select></td>
    <td style="vertical-align: top;"><select class="je-contact">${contactOptions}</select></td>
    <td style="vertical-align: top;"><button class="action-btn btn-delete" onclick="this.closest('tr').remove(); calcJournalTotals()">🗑️</button></td>
  `;
  
  tbody.appendChild(tr);
  
  const accContainer = tr.querySelector('.acc-cascade-td');
  
  const hiddenInput = document.createElement('input');
  hiddenInput.type = 'hidden';
  hiddenInput.className = 'je-account-id';
  hiddenInput.value = accountId || '';
  accContainer.appendChild(hiddenInput);

  let path = [];
  if (accountId) {
    let curr = currentAccounts.find(a => String(a.id) === String(accountId));
    while(curr) {
      path.unshift(curr);
      curr = currentAccounts.find(a => a.id === curr.parent_id);
    }
  }

  function renderSelect(parentId, level, selectedValue) {
    const children = currentAccounts.filter(a => (a.parent_id || null) === parentId).sort((a,b)=>(a.code||'').localeCompare(b.code||''));
    if (children.length === 0) return; 

    const sel = document.createElement('select');
    sel.className = 'je-account-level';
    sel.style.marginBottom = '5px';
    sel.style.flex = '1';
    sel.style.minWidth = '100px';
    sel.style.padding = '6px';
    sel.innerHTML = `<option value="">-- اختر ${level===0?'الحساب الرئيسي':'تفرع'} --</option>` + children.map(c => `<option value="${c.id}">${c.code} - ${c.name}</option>`).join('');
    
    if (selectedValue) sel.value = selectedValue;

    sel.addEventListener('change', (e) => {
      while(sel.nextSibling) sel.nextSibling.remove();
      const val = e.target.value;
      if (val) {
        hiddenInput.value = val;
        renderSelect(parseInt(val), level + 1, null);
      } else {
        hiddenInput.value = parentId || '';
      }
    });

    accContainer.appendChild(sel);
  }

  if (path.length > 0) {
    let currentParent = null;
    for(let i=0; i<path.length; i++) {
       renderSelect(currentParent, i, path[i].id);
       currentParent = path[i].id;
    }
    renderSelect(currentParent, path.length, null);
  } else {
    renderSelect(null, 0, null);
  }
}

window.calcJournalTotals = function() {
  let totDebit = 0, totCredit = 0;
  document.querySelectorAll('#je-tbody tr').forEach(tr => {
    totDebit += parseFloat(tr.querySelector('.je-debit').value) || 0;
    totCredit += parseFloat(tr.querySelector('.je-credit').value) || 0;
  });
  document.getElementById('je-total-debit').innerText = totDebit.toLocaleString('en-US');
  document.getElementById('je-total-credit').innerText = totCredit.toLocaleString('en-US');
  document.getElementById('je-diff').innerText = Math.abs(totDebit - totCredit).toLocaleString('en-US');
}

document.getElementById('btn-save-journal')?.addEventListener('click', async () => {
  const date = document.getElementById('je-date').value;
  const reference = document.getElementById('je-ref').value;
  const desc = document.getElementById('je-desc').value;
  const status = document.getElementById('je-status').value || 'draft';
  const idStr = document.getElementById('edit-je-id').value;
  
  const rows = [];
  document.querySelectorAll('#je-tbody tr').forEach(tr => {
    const accInput = tr.querySelector('.je-account-id');
    if(!accInput) return;
    const accIdStr = accInput.value;
    const debit = parseFloat(tr.querySelector('.je-debit').value) || 0;
    const credit = parseFloat(tr.querySelector('.je-credit').value) || 0;
    const projIdStr = tr.querySelector('.je-project').value;
    const contactIdStr = tr.querySelector('.je-contact') ? tr.querySelector('.je-contact').value : '';
    const notesStr = tr.querySelector('.je-notes') ? tr.querySelector('.je-notes').value : '';
    
    if (accIdStr) {
      rows.push({
        account_id: parseInt(accIdStr),
        debit,
        credit,
        project_id: projIdStr ? parseInt(projIdStr) : null,
        contact_id: contactIdStr ? parseInt(contactIdStr) : null,
        notes: notesStr
      });
    }
  });

  let totDebit = 0, totCredit = 0;
  (rows || []).forEach(r => { totDebit += r.debit; totCredit += r.credit; });
  
  if(rows.length === 0) { alert('يجب إضافة أسطر للقيد!'); return; }
  if(Math.abs(totDebit - totCredit) > 0.01) { alert('القيد غير متزن!'); return; }
  
  const obj = { date, reference, desc, status, rows, created_by: currentUser.username, total: totDebit };
  
  if(idStr) {
    obj.id = parseInt(idStr);
    await window.DB.update('journal_entries', obj);
  } else {
    await window.DB.add('journal_entries', obj);
  }
  closeModal('journal-modal');
  await loadData();
});

window.currentJournalPage = window.currentJournalPage || 1;
function renderJournals() {
  const tbody = document.getElementById('journals-tbody');
  const paginationDiv = document.getElementById('journals-pagination');
  if(!tbody) return;
  tbody.innerHTML = '';
  if (paginationDiv) paginationDiv.innerHTML = '';
  
  if (currentJournals.length === 0) {
    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; padding: 20px; color:#666;">لا توجد قيود حالياً. اضغط على "+ قيد يومية" لإضافة قيد.</td></tr>';
    return;
  }
  const fProj = document.getElementById('filter-project') ? document.getElementById('filter-project').value : '';
  const fAcc = document.getElementById('filter-account') ? document.getElementById('filter-account').value : '';
  const fContact = document.getElementById('filter-contact') ? document.getElementById('filter-contact').value : '';
  const fDesc = document.getElementById('filter-desc') ? document.getElementById('filter-desc').value.toLowerCase().trim() : '';
  const fFrom = document.getElementById('filter-from') ? document.getElementById('filter-from').value : '';
  const fTo = document.getElementById('filter-to') ? document.getElementById('filter-to').value : '';

  let filtered = (currentJournals || []).filter(j => {
      let match = true;
      if (fFrom && j.date && String(j.date).substring(0,10) < fFrom) match = false;
      if (fTo && j.date && String(j.date).substring(0,10) > fTo) match = false;
      
      if (match && (fProj || fAcc || fContact || fDesc)) {
            let hasProj = fProj ? false : true;
            let hasAcc = fAcc ? false : true;
            let hasContact = fContact ? false : true;
            let hasDesc = fDesc ? false : true;
            
            if (fDesc) {
                let descMain = String(j.desc || '').toLowerCase();
                let refMain = String(j.reference || '').toLowerCase();
                if (descMain.includes(fDesc) || refMain.includes(fDesc)) {
                    hasDesc = true;
                }
            }
  
            if (j.rows && Array.isArray(j.rows)) {
                for (let r of j.rows) {
                    if (fProj && String(r.project_id) === String(fProj)) hasProj = true;
                    if (fAcc && String(r.account_id) === String(fAcc)) hasAcc = true;
                    if (fContact && String(r.contact_id) === String(fContact)) hasContact = true;
                    if (fDesc && String(r.description || '').toLowerCase().includes(fDesc)) hasDesc = true;
                }
            }
            if (!(hasProj && hasAcc && hasContact && hasDesc)) match = false;
        }
      return match;
  });

  let sortedJournals = filtered.slice().sort((a, b) => {
      let idA = parseInt(String(a.id).replace(/\D/g, ''), 10) || 0;
      let idB = parseInt(String(b.id).replace(/\D/g, ''), 10) || 0;
      return idB - idA;
  });
  const pageSize = 50;
  const totalItems = sortedJournals.length;
  const totalPages = Math.ceil(totalItems / pageSize);
  if (window.currentJournalPage > totalPages && totalPages > 0) window.currentJournalPage = totalPages;
  const startIndex = (window.currentJournalPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const pageData = sortedJournals.slice(startIndex, endIndex);

  pageData.forEach(je => {
    let statusSpan = `<span style="color:gray;">مسودة</span>`;
    if(je.status === 'approved') statusSpan = `<span style="color:var(--primary);">معتمد</span>`;
    if(je.status === 'posted') statusSpan = `<span style="color:green; font-weight:bold;">مُرحّل</span>`;
    
    let actions = `<button class="action-btn btn-view" onclick="openJournalModal(${je.id})">🔍 عرض/تعديل</button>`;
    let canApprove = false;
      let canPost = false;
      if (currentUser) {
          if (currentUser.role === 'مدير عام' || currentUser.role === 'مدير نظام') {
              canApprove = true; canPost = true;
          }
          if (currentUser.allowed_actions) {
              if (currentUser.allowed_actions.includes('approve-journals')) canApprove = true;
              if (currentUser.allowed_actions.includes('post-journals')) canPost = true;
          }
      }
      
      if (canApprove || canPost) {
        if(je.status === 'draft' && canApprove) actions += ` <button class="action-btn" style="color:var(--primary)" onclick="changeJournalStatus(${je.id}, 'approved')">✔️ اعتماد</button>`;
        if(je.status === 'approved' && canPost) actions += ` <button class="action-btn" style="color:green; font-weight:bold" onclick="changeJournalStatus(${je.id}, 'posted')">✅ ترحيل</button>`;
        if(canApprove && canPost) actions += ` <button class="action-btn btn-delete" onclick="deleteJournal(${je.id})">🗑️ حذف</button>`;
      }
    
    tbody.innerHTML += `<tr><td>#${je.id}</td><td>${je.date}</td><td>${je.desc || je.reference || '-'}</td><td style="font-weight:bold">${(je.total||0).toLocaleString('en-US')}</td><td>${statusSpan}</td><td>${actions}</td></tr>`;
  });

  if (paginationDiv && totalPages > 1) {
     for (let i = 1; i <= totalPages; i++) {
         const btn = document.createElement('button');
         btn.innerText = i;
         btn.style.padding = '5px 10px';
         btn.style.border = '1px solid #ccc';
         btn.style.borderRadius = '4px';
         btn.style.cursor = 'pointer';
         if (i === window.currentJournalPage) {
             btn.style.backgroundColor = 'var(--primary)';
             btn.style.color = '#fff';
         } else {
             btn.style.backgroundColor = '#fff';
             btn.style.color = '#333';
         }
         btn.onclick = () => { window.currentJournalPage = i; renderJournals(); };
         paginationDiv.appendChild(btn);
     }
  }
}

window.changeJournalStatus = async function(id, newStatus) {
  const msg = newStatus === 'approved' ? 'اعتماد' : 'ترحيل';
  if(!confirm(`هل أنت متأكد من ${msg} القيد؟`)) return;
  const je = currentJournals.find(x => String(x.id) === String(id));
  if(je) {
    je.status = newStatus;
    await window.DB.update('journal_entries', je);
    await loadData();
  }
}

window.deleteJournal = async function(id) {
  if(!confirm('هل أنت متأكد من حذف القيد؟')) return;
  await window.DB.remove('journal_entries', id);
  await loadData();
}

window.exportJournalsToCSV = async function() {
    if(!window.DB) return;
    const journals = await window.DB.getAll('journal_entries') || [];
    const accounts = await window.DB.getAll('accounts') || [];
    const projects = await window.DB.getAll('projects') || [];
    const contacts = await window.DB.getAll('contacts') || [];

    const getAccName = id => { const a = accounts.find(x => String(x.id) === String(id)); return a ? a.name : id; };
    const getProjName = id => { if(!id) return ''; const p = projects.find(x => String(x.id) === String(id)); return p ? p.name : id; };
    const getContactName = id => { if(!id) return ''; const c = contacts.find(x => String(x.id) === String(id)); return c ? c.name : id; };

    journals.sort((a,b) => new Date(b.date) - new Date(a.date));

    let html = '<html dir="rtl" lang="ar"><head><meta charset="utf-8"></head><body>';
    html += '<table border="1" style="font-family: Arial, sans-serif;"><thead><tr>';
    html += '<th style="background-color: #217346; color: #fff; font-weight: bold;">رقم القيد</th>';
    html += '<th style="background-color: #217346; color: #fff; font-weight: bold;">التاريخ</th>';
    html += '<th style="background-color: #217346; color: #fff; font-weight: bold;">الحساب</th>';
    html += '<th style="background-color: #217346; color: #fff; font-weight: bold;">البيان</th>';
    html += '<th style="background-color: #217346; color: #fff; font-weight: bold;">مدين</th>';
    html += '<th style="background-color: #217346; color: #fff; font-weight: bold;">دائن</th>';
    html += '<th style="background-color: #217346; color: #fff; font-weight: bold;">المشروع</th>';
    html += '<th style="background-color: #217346; color: #fff; font-weight: bold;">جهة التعامل</th>';
    html += '</tr></thead><tbody>';

    journals.forEach(j => {
        if(j.rows && j.rows.length > 0) {
            j.rows.forEach(r => {
                const jRef = j.reference || j.id || '';
                const jDate = j.date || '';
                const acc = getAccName(r.account_id);
                // Safe description for HTML
                const desc = (r.desc || j.desc || '').toString().replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n|\r/g, '<br>');
                const deb = r.debit || 0;
                const cred = r.credit || 0;
                const proj = getProjName(r.project_id);
                const cont = getContactName(r.contact_id);

                html += `<tr>
                    <td>${jRef}</td>
                    <td>${jDate}</td>
                    <td>${acc}</td>
                    <td>${desc}</td>
                    <td>${deb}</td>
                    <td>${cred}</td>
                    <td>${proj}</td>
                    <td>${cont}</td>
                </tr>`;
            });
        }
    });

    html += '</tbody></table></body></html>';

    const blob = new Blob([html], { type: 'application/vnd.ms-excel;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.setAttribute("href", url);
    link.setAttribute("download", `قيود_اليومية_${new Date().toISOString().slice(0,10)}.xls`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};
