
// 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 sortedForSum = [...currentAccounts].sort((a,b) => (b.code||'').length - (a.code||'').length);
  (sortedForSum || []).forEach(a => {
    if (a.parent_id && accBalances[a.parent_id]) {
       accBalances[a.parent_id].op_debit += accBalances[a.id].op_debit;
       accBalances[a.parent_id].op_credit += accBalances[a.id].op_credit;
       accBalances[a.parent_id].mov_debit += accBalances[a.id].mov_debit;
       accBalances[a.parent_id].mov_credit += accBalances[a.id].mov_credit;
    }
  });

  window.expandedAccounts = window.expandedAccounts || {};
  
  function renderTree(parentId, level = 0, isVisible = true) {
    const children = currentAccounts.filter(a => (a.parent_id || null) === 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>`;
      if(currentUser && currentUser.role === 'مدير عام') {
        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 * 20;
      const isExpanded = window.expandedAccounts[acc.id] !== false; 
      const arrow = accChildren.length > 0 ? (isExpanded ? '🔽' : '▶️') : '📄';
      
      const displayStyle = isVisible ? '' : 'display:none;';
      const rowStyle = level === 0 ? 'background:rgba(0,0,0,0.03); font-weight:bold;' : '';
      
      const bal = accBalances[acc.id];
      const totDebit = bal.op_debit + bal.mov_debit;
      const totCredit = bal.op_credit + bal.mov_credit;
      const netDebit = totDebit > totCredit ? totDebit - totCredit : 0;
      const netCredit = totCredit > totDebit ? totCredit - totDebit : 0;
      
      const formatNum = (num) => num === 0 ? '-' : num.toLocaleString('ar-EG', {minimumFractionDigits:2});
      
      tbody.innerHTML += `<tr class="acc-row" style="${rowStyle} ${displayStyle}">
        <td>${acc.code}</td>
        <td style="padding-right: ${indent + 10}px; cursor:pointer; user-select:none;" onclick="toggleAccount(${acc.id})">${arrow} ${acc.name}</td>
        <td>${acc.type}</td>
        <td style="color:#666;">${formatNum(bal.op_debit)}</td>
        <td style="color:#666;">${formatNum(bal.op_credit)}</td>
        <td style="color:var(--primary);">${formatNum(bal.mov_debit)}</td>
        <td style="color:var(--danger);">${formatNum(bal.mov_credit)}</td>
        <td style="font-weight:bold; color:var(--primary);">${formatNum(netDebit)}</td>
        <td style="font-weight:bold; color:var(--danger);">${formatNum(netCredit)}</td>
        <td>${actions}</td>
      </tr>`;
      
      renderTree(acc.id, level + 1, isVisible && isExpanded);
    });
  }
  
  renderTree(null, 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 parentSelect = document.getElementById('acc-parent');
  parentSelect.innerHTML = '<option value="">-- كحساب رئيسي --</option>' + 
    currentAccounts.map(a => `<option value="${a.id}">${a.code} - ${a.name}</option>`).join('');

  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;
    parentSelect.value = acc.parent_id || '';
  } else {
    document.getElementById('acc-name').value = '';
    document.getElementById('acc-op-debit').value = 0;
    document.getElementById('acc-op-credit').value = 0;
    parentSelect.value = parentId || '';
  }
  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 parentIdStr = document.getElementById('acc-parent').value;
  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 = 'أصول'; 
  }

  const obj = { name, type, parent_id: parentId, op_debit: opDebit, op_credit: opCredit };
  
  if(idStr) {
    obj.id = parseInt(idStr);
    const existing = currentAccounts.find(a => a.id === obj.id);
    obj.code = existing.code; // Don't change code on edit
    await window.DB.update('accounts', obj);
  } else {
    obj.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' ? 'btn-primary' : 'btn-secondary';
  document.getElementById('tab-btn-journals').className = tab === 'journals' ? 'btn-primary' : 'btn-secondary';
};

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));
    } 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 = '') {
  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>`;
  });

  tr.innerHTML = `
    <td class="acc-cascade-td" style="min-width: 250px; vertical-align: top; padding-top: 10px;"></td>
    <td style="vertical-align: top;"><input type="number" class="je-debit" value="${debit}" min="0" onchange="calcJournalTotals()"></td>
    <td style="vertical-align: top;"><input type="number" class="je-credit" value="${credit}" min="0" onchange="calcJournalTotals()"></td>
    <td style="vertical-align: top;"><select class="je-project">${projOptions}</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.width = '100%';
    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;
    
    if (accIdStr) {
      rows.push({
        account_id: parseInt(accIdStr),
        debit,
        credit,
        project_id: projIdStr ? parseInt(projIdStr) : null
      });
    }
  });

  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();
});

function renderJournals() {
  const tbody = document.getElementById('journals-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  if (currentJournals.length === 0) {
    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; padding: 20px; color:#666;">لا توجد قيود حالياً. اضغط على "+ قيد يومية" لإضافة قيد.</td></tr>';
    return;
  }
  (currentJournals || []).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>`;
    if(currentUser && currentUser.role === 'مدير عام') {
      if(je.status === 'draft') actions += ` <button class="action-btn" style="color:var(--primary)" onclick="changeJournalStatus(${je.id}, 'approved')">✔️ اعتماد</button>`;
      if(je.status === 'approved') actions += ` <button class="action-btn" style="color:green; font-weight:bold" onclick="changeJournalStatus(${je.id}, 'posted')">🗃️ ترحيل</button>`;
      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>`;
  });
}

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();
}