window.getInvoiceItemId = function() {
    const val = document.getElementById('invoice-item')?.value;
    if (!val) return null;
    const item = currentItems.find(i => i.name === val || i.code === val || String(i.id) === val);
    return item ? item.id : null;
};


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
let currentUser = null;
let currentItems = [];
let currentProjects = [];
let currentWarehouses = [];
let currentUsers = [];
let currentContacts = [];
let currentUnits = [];
let allInvoices = [];
let allNotifications = [];
let currentClientAbstracts = [];
let currentInvoiceItems = [];
let currentItemBom = [];
let currentAccounts = [];
let currentJournals = [];
let currentJournalLines = [];
let allConcreteInvoices = [];

let balancesCache = {};

window.getAllowedWarehouses = function() {
  let allowed = currentWarehouses;
  if (typeof currentUser !== 'undefined' && currentUser) {
    if (currentUser.role === 'أمين مخزن' && currentUser.warehouse_id) {
      allowed = currentWarehouses.filter(w => String(w.id) === String(currentUser.warehouse_id));
    } else if (currentUser.role === 'موظف مخصص' && currentUser.allowed_warehouses && currentUser.allowed_warehouses.length > 0) {
      allowed = currentWarehouses.filter(w => currentUser.allowed_warehouses.some(aw => String(aw) === String(w.id)));
    } else if (currentUser.warehouse_id) {
      allowed = currentWarehouses.filter(w => String(w.id) === String(currentUser.warehouse_id));
    }
  }
  if (!allowed || allowed.length === 0) allowed = currentWarehouses;
  return allowed;
};

window.getAllowedWarehousesHtml = function(defaultText = 'اختر المخزن...') {
  const allowed = window.getAllowedWarehouses();
  let html = `<option value="">${defaultText}</option>`;
  html += allowed.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  return html;
};

// Elements
const loginScreen = document.getElementById('login-screen');
const appScreen = document.getElementById('app-screen');
const navItems = document.querySelectorAll('.nav-menu li[data-view]');
const views = document.querySelectorAll('.view');

// Initialize
window.addEventListener('load', async () => {
  try {
    await window.DB.initDB();
    const savedUser = sessionStorage.getItem('currentUser');
    if (savedUser) {
      currentUser = JSON.parse(savedUser);
      loginScreen.classList.remove('active');
      appScreen.classList.add('active');
      setupUserUI();
      
      // Auto-refresh user permissions in the background
      window.DB.getAll('users').then(users => {
          const updatedUser = users.find(u => String(u.id) === String(currentUser.id));
          if (updatedUser) {
              currentUser = updatedUser;
              sessionStorage.setItem('currentUser', JSON.stringify(currentUser));
              setupUserUI();
          }
      });
      
      await loadData();
    }
  } catch (e) {
    console.error("Initialization Error: ", e);
    alert("حدث خطأ أثناء تحميل قاعدة البيانات: " + e.message);
  }
});

function setupUserUI() {
  // عرض صورة الملف الشخصي لو موجودة
  if (currentUser && currentUser.avatar) {
    const navAvatar = document.getElementById('nav-user-avatar');
    if (navAvatar) { navAvatar.src = currentUser.avatar; navAvatar.style.display = 'block'; }
  }
  document.getElementById('current-user-name').innerText = currentUser.username;
  document.getElementById('current-user-role').innerText = currentUser.role;

  const allNavs = ['nav-users', 'nav-warehouses', 'nav-decisions', 'nav-contacts', 'nav-units', 'nav-items',
    'nav-item-card', 'nav-projects', 'nav-project-reports', 'nav-balances', 'nav-transactions', 'nav-accounting',
    'nav-sales', 'nav-purchases', 'nav-vouchers', 'nav-settlements', 'nav-sales-returns', 'nav-purchases-returns',
    'nav-project-costs', 'nav-subcontracts', 'nav-subcontract-abstracts', 'nav-client-abstracts', 'nav-audit-logs', 'nav-settings', 'nav-custody-requests', 'nav-rm', 'nav-hr', 'nav-pos'];
  (allNavs || []).forEach(nav => {
    const el = document.getElementById(nav);
    if (el) el.style.display = 'none';
  });
  document.getElementById('btn-add-item-modal').style.display = 'none';

  if (currentUser.role === 'مدير عام') {
    (allNavs || []).forEach(nav => {
      const el = document.getElementById(nav);
      if (el) el.style.display = 'block';
    });
    document.getElementById('btn-add-item-modal').style.display = 'inline-block';
    document.getElementById('current-user-warehouse').innerText = 'كل المخازن';
    const btnReset = document.getElementById('btn-reset-system');
    if (btnReset) btnReset.style.display = 'inline-block';
  } else {
    const btnReset = document.getElementById('btn-reset-system');
    if (btnReset) btnReset.style.display = 'none';
    const mods = currentUser.allowed_modules || [];
    if (mods.includes('users')) document.getElementById('nav-users').style.display = 'block';
    if (mods.includes('warehouses')) document.getElementById('nav-warehouses').style.display = 'block';
    if (mods.includes('contacts')) document.getElementById('nav-contacts').style.display = 'block';
    if (mods.includes('units')) document.getElementById('nav-units').style.display = 'block';

    if (mods.includes('items')) {
      document.getElementById('nav-items').style.display = 'block';
      document.getElementById('nav-item-card').style.display = 'block';
      document.getElementById('btn-add-item-modal').style.display = 'inline-block';
    }

    if (mods.includes('projects')) {
      document.getElementById('nav-projects').style.display = 'block';
      document.getElementById('nav-project-costs').style.display = 'block';
      document.getElementById('nav-client-abstracts').style.display = 'block';
    }
    if (mods.includes('project-reports')) document.getElementById('nav-project-reports').style.display = 'block';
    if (mods.includes('balances')) document.getElementById('nav-balances').style.display = 'block';
    if (mods.includes('transactions')) {
      document.getElementById('nav-transactions').style.display = 'block';
      document.getElementById('nav-decisions').style.display = 'block';
    }

    if (mods.includes('sales')) {
      document.getElementById('nav-sales').style.display = 'block';
      document.getElementById('nav-sales-returns').style.display = 'block';
      document.getElementById('nav-pos').style.display = 'block';
    }

    if (mods.includes('purchases')) {
      document.getElementById('nav-purchases').style.display = 'block';
      document.getElementById('nav-purchases-returns').style.display = 'block';
    }

    if (mods.includes('accounting')) {
      document.getElementById('nav-accounting').style.display = 'block';
      document.getElementById('nav-custody-requests').style.display = 'block';
    }

    if (mods.includes('contractors')) {
      document.getElementById('nav-subcontracts').style.display = 'block';
      document.getElementById('nav-subcontract-abstracts').style.display = 'block';
    }

    if (mods.includes('settlements')) {
      document.getElementById('nav-settlements').style.display = 'block';
    }

    if (mods.includes('vouchers')) {
      document.getElementById('nav-vouchers').style.display = 'block';
    }

    if (mods.includes('readymix')) {
      const el = document.getElementById('nav-rm');
      if(el) el.style.display = 'block';
      const rmL = document.querySelectorAll('.rm-link');
      rmL.forEach(l => l.style.display = 'block');
    }

    if (mods.includes('hr')) {
      const el = document.getElementById('nav-hr');
      if(el) el.style.display = 'block';
      const hrL = document.querySelectorAll('.hr-link');
      hrL.forEach(l => l.style.display = 'block');
    }

    let whText = '';
    if (currentUser.allowed_warehouses && currentUser.allowed_warehouses.length > 0) whText = currentUser.allowed_warehouses.length + ' مخزن';
    else whText = 'لا يوجد مخازن';
    document.getElementById('current-user-warehouse').innerText = whText;
  }
}

// --- 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') {
        depths[id] = 0;
        return 0;
    }
    depths[id] = 0; // temporary to prevent infinite loop
    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>`;
      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 => String(a.parent_id || '') === String(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('', 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();
});


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;
  }
  
  let sortedJournals = (currentJournals || []).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>`;
    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>`;
  });

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

// Listeners
document.getElementById('btn-login').addEventListener('click', async () => {
  const user = document.getElementById('login-username').value;
  const pass = document.getElementById('login-password').value;
  const error = document.getElementById('login-error');

  const res = await window.DB.login(user, pass);
  if (res) {
    currentUser = res;
    sessionStorage.setItem('currentUser', JSON.stringify(res));
    loginScreen.classList.remove('active');
    appScreen.classList.add('active');
    setupUserUI();
    await loadData();
  } else {
    error.innerText = 'بيانات الدخول غير صحيحة';
  }
});

document.getElementById('btn-logout').addEventListener('click', () => {
  currentUser = null;
  sessionStorage.removeItem('currentUser');
  appScreen.classList.remove('active');
  loginScreen.classList.add('active');
});

(navItems || []).forEach(item => {
  item.addEventListener('click', (e) => {
    if (item.id === 'btn-logout') return;
    (navItems || []).forEach(n => n.classList.remove('active'));
    item.classList.add('active');
    (views || []).forEach(v => v.classList.remove('active'));
    
    const viewEl = document.getElementById(`view-${item.dataset.view}`);
    if (viewEl) viewEl.classList.add('active');
    
    if (item.dataset.view === 'project-reports') renderProjectReports();
    if (item.dataset.view === 'client-abstracts' && typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
    if (item.dataset.view === 'settlements' && typeof window.renderSettlements === 'function') window.renderSettlements();
    if (item.dataset.view === 'subcontracts' && typeof window.renderSubcontracts === 'function') window.renderSubcontracts();
    if (item.dataset.view === 'subcontract-abstracts' && typeof window.renderAbstracts === 'function') window.renderAbstracts();
    if (item.dataset.view === 'vouchers' && typeof window.renderVouchers === 'function') window.renderVouchers();
    if (item.dataset.view === 'sales-returns' && typeof window.renderSalesReturns === 'function') window.renderSalesReturns();
    if (item.dataset.view === 'purchases-returns' && typeof window.renderPurchasesReturns === 'function') window.renderPurchasesReturns();
    if (item.dataset.view === 'settings' && typeof window.renderSettings === 'function') window.renderSettings();
  });
});

function showModal(id) { document.getElementById(id).classList.add('active'); }
function closeModal(id) { document.getElementById(id).classList.remove('active'); }

// --- CALCULATIONS ---

// --- STOREKEEPERS DASHBOARD ---
window.renderStorekeepersDashboard = function () {
  const section = document.getElementById('storekeepers-dashboard-section');
  const tbody = document.getElementById('storekeepers-dashboard-tbody');
  if (!section || !tbody) return;

  // --- My Custody Card Logic (For the logged-in user) ---
  const myCustodyCard = document.getElementById('my-custody-card');
  if (myCustodyCard) {
    if (currentUser && currentUser.custody_account_id) {
      myCustodyCard.style.display = 'block';
      let myRunningBalance = 0;
      currentJournals.forEach(j => {
        if (j.status !== 'posted') return;
        if (j.rows) {
          j.rows.forEach(r => {
            if (r.account_id == currentUser.custody_account_id) {
              myRunningBalance += (parseFloat(r.debit) || 0) - (parseFloat(r.credit) || 0);
            }
          });
        }
      });
      const myOpAcc = currentAccounts.find(a => a.id == currentUser.custody_account_id);
      if (myOpAcc) myRunningBalance += (parseFloat(myOpAcc.op_debit) || 0) - (parseFloat(myOpAcc.op_credit) || 0);
      document.getElementById('my-custody-balance').innerText = Math.abs(myRunningBalance).toLocaleString('ar-EG', { minimumFractionDigits: 2 }) + (myRunningBalance >= 0 ? ' مدين' : ' دائن');
    } else {
      myCustodyCard.style.display = 'none';
    }
  }

  // Only general manager should see all storekeepers
  if (currentUser.role !== 'مدير عام') {
    section.style.display = 'none';
    return;
  }

  // Find storekeepers
  const storekeepers = currentUsers.filter(u => (u && u.role) === 'أمين مخزن' || (u && u.role) === 'أمينة مخزن' || (u && u.role) === 'مدير مخازن' || (u && u.username).includes('امين'));

  // Also include anyone who has a custody account that has the word عهدة in it
  currentUsers.forEach(u => {
    if (u.custody_account_id && !storekeepers.find(sk => sk.id === u.id)) {
      const acc = currentAccounts.find(a => a.id === u.custody_account_id);
      if (acc && acc.name.includes('عهد')) {
        storekeepers.push(u);
      }
    }
  });

  if (storekeepers.length === 0) {
    section.style.display = 'none';
    return;
  }

  section.style.display = 'block';
  tbody.innerHTML = '';

  storekeepers.forEach(sk => {
    let accName = 'لا يوجد';
    let balanceStr = '0';
    let balanceHtml = '<span>0</span>';

    if (sk.custody_account_id) {
      const acc = currentAccounts.find(a => a.id === sk.custody_account_id);
      if (acc) {
        accName = acc.name;

        // Calculate balance
        let runningBalance = 0;
        currentJournals.forEach(j => {
          if (j.status !== 'posted') return;
          if (j.rows) {
            j.rows.forEach(r => {
              if (r.account_id == sk.custody_account_id) {
                runningBalance += (parseFloat(r.debit) || 0) - (parseFloat(r.credit) || 0);
              }
            });
          }
        });

        balanceStr = Math.abs(runningBalance).toLocaleString('en-US');
        if (runningBalance > 0) balanceHtml = `<span style="color:var(--danger); font-weight:bold;">${balanceStr} مدين</span>`;
        else if (runningBalance < 0) balanceHtml = `<span style="color:var(--success); font-weight:bold;">${balanceStr} دائن</span>`;
        else balanceHtml = `<span>0</span>`;
      }
    }

    let actionBtn = `<button class="btn btn-sm btn-secondary" disabled>📄 كشف حساب</button>`;
    if (sk.custody_account_id) {
      actionBtn = `<button class="btn btn-sm btn-primary" onclick="openAccountStatement(${sk.custody_account_id})">📄 كشف حساب</button>`;
    }

    tbody.innerHTML += `
            <tr>
                <td>${sk.username}</td>
                <td>${accName}</td>
                <td style="font-size: 16px;">${balanceHtml}</td>
                <td>${actionBtn}</td>
            </tr>
        `;
  });
};

function calculateBalances() {
  balancesCache = {};
  (currentItems || []).forEach(i => {
    balancesCache[i.id] = { globalQty: 0, totalValue: 0, avgCost: 0, warehouses: {} };
  });

  const sortedInvoices = [...allInvoices].sort((a, b) => new Date(a.date) - new Date(b.date));

  (sortedInvoices || []).forEach(inv => {
    (inv.items || []).forEach(item => {
      const b = balancesCache[item.item_id];
      if (!b) return;

      const fromWh = inv.from_warehouse_id;
      const toWh = inv.to_warehouse_id;

      if (fromWh && !b.warehouses[fromWh]) b.warehouses[fromWh] = 0;
      if (toWh && !b.warehouses[toWh]) b.warehouses[toWh] = 0;

      if ((inv.type === 'in' || inv.type === 'opening_balance') || ((inv.type === 'purchases' || inv.type === 'sales_return') && inv.status === 'posted')) {
        b.globalQty += item.qty;
        if (inv.type === 'sales_return') {
          if (fromWh) b.warehouses[fromWh] += item.qty;
        } else {
          if (toWh) b.warehouses[toWh] += item.qty;
        }
        b.totalValue += (item.qty * item.price);
        b.avgCost = b.globalQty > 0 ? (b.totalValue / b.globalQty) : 0;
      }
      else if (inv.type === 'out_project' || inv.type === 'depreciate_asset' || ((inv.type === 'sales' || inv.type === 'purchases_return') && inv.status === 'posted')) {
        b.globalQty -= item.qty;
        if (inv.type === 'purchases_return') {
          if (fromWh) b.warehouses[fromWh] -= item.qty;
        } else {
          if (fromWh) b.warehouses[fromWh] -= item.qty;
        }
        b.totalValue -= (item.qty * b.avgCost);
      }
      else if (inv.type === 'transfer') {
        if (inv.status === 'pending_receipt' || inv.status === 'pending_decision') {
          if (fromWh) b.warehouses[fromWh] -= item.qty;
        }
        else if (inv.status === 'completed') {
          const deducted = item.deducted_qty !== undefined ? item.deducted_qty : item.qty;
          const received = item.received_qty !== undefined ? item.received_qty : item.qty;
          if (fromWh) b.warehouses[fromWh] -= deducted;
          if (toWh) b.warehouses[toWh] += received;
          if (deducted > received) {
            const deficit = deducted - received;
            b.globalQty -= deficit;
            b.totalValue -= (deficit * b.avgCost);
          }
        }
      }
    });

    if (inv.type === 'manufacture') {
      let totalRawCost = 0;
      (inv.items || []).forEach(raw => {
        let b = balancesCache[raw.item_id];
        if (b) {
          let fromWh = inv.from_warehouse_id;
          b.globalQty -= raw.qty;
          if (fromWh) {
            if (b.warehouses[fromWh] === undefined) b.warehouses[fromWh] = 0;
            b.warehouses[fromWh] -= raw.qty;
          }
          let consumedCost = raw.qty * b.avgCost;
          b.totalValue -= consumedCost;
          totalRawCost += consumedCost;
        }
      });

      let producedId = inv.product_id || inv.produced_item_id;
      let prodB = balancesCache[producedId];

      if (prodB) {
        let toWh = inv.from_warehouse_id;
        prodB.globalQty += inv.produced_qty;
        if (toWh) {
          if (prodB.warehouses[toWh] === undefined) prodB.warehouses[toWh] = 0;
          prodB.warehouses[toWh] += inv.produced_qty;
        }
        prodB.totalValue += totalRawCost;
        prodB.avgCost = prodB.globalQty > 0 ? (prodB.totalValue / prodB.globalQty) : 0;
      }
      inv.produced_cost = totalRawCost;
    }
  });
  window.balancesCache = balancesCache;
  try { localStorage.setItem('shared_balances_cache', JSON.stringify(balancesCache)); } catch(e) {}
}

// --- MODALS OPENING LOGIC ---
window.openUserModal = function (id = null) {
  const isEdit = id !== null;
  document.getElementById('user-modal-title').innerText = isEdit ? 'تعديل مستخدم' : 'إضافة مستخدم جديد';
  document.getElementById('edit-user-id').value = id || '';

  const whContainer = document.getElementById('custom-warehouses-list');
  whContainer.innerHTML = currentWarehouses.map(w => `<label class="perm-card"><input type="checkbox" class="perm-warehouse" value="${w.id}"> ${w.name}</label>`).join('');

  const projContainer = document.getElementById('custom-projects-list');
  projContainer.innerHTML = currentProjects.map(p => `<label class="perm-card"><input type="checkbox" class="perm-project" value="${p.id}"> ${p.name}</label>`).join('');

  const custodySel = document.getElementById('user-custody');
  if (custodySel) {
    custodySel.innerHTML = '<option value="">-- إنشاء حساب عهدة تلقائياً --</option>' +
      currentAccounts.filter(a => a.name.includes('عهد')).map(a => `<option value="${a.id}">${a.name}</option>`).join('');
  }
  if (isEdit) {
    const u = currentUsers.find(x => String(x.id) === String(id));
    document.getElementById('user-username').value = (u && u.username);
    document.getElementById('user-password').value = u.password;
    document.getElementById('user-role').value = (u && u.role);

    if (u.warehouse_id) document.getElementById('user-warehouse').value = u.warehouse_id;
    if (u.project_id) document.getElementById('user-project').value = u.project_id;
    else document.getElementById('user-project').value = '';
    if (u.custody_account_id && document.getElementById('user-custody')) document.getElementById('user-custody').value = u.custody_account_id;
    else if (document.getElementById('user-custody')) document.getElementById('user-custody').value = '';

    document.querySelectorAll('.perm-module').forEach(cb => {
      cb.checked = u.allowed_modules && u.allowed_modules.includes(cb.value);
    });
    document.querySelectorAll('.perm-warehouse').forEach(cb => {
      cb.checked = u.allowed_warehouses && u.allowed_warehouses.includes(parseInt(cb.value));
    });
    document.querySelectorAll('.perm-project').forEach(cb => {
      cb.checked = u.allowed_projects && u.allowed_projects.includes(parseInt(cb.value));
    });

    document.getElementById('user-role').dispatchEvent(new Event('change'));
  } else {
    document.getElementById('user-username').value = '';
    document.getElementById('user-password').value = '';
    document.getElementById('user-role').value = 'مدير عام';
    document.getElementById('user-project').value = '';

    document.querySelectorAll('.perm-module').forEach(cb => cb.checked = false);
    document.querySelectorAll('.perm-warehouse').forEach(cb => cb.checked = false);

    document.getElementById('user-role').dispatchEvent(new Event('change'));
  }
  showModal('user-modal');
}

window.openWarehouseModal = function (id = null) {
  const isEdit = id !== null;
  document.getElementById('wh-modal-title').innerText = isEdit ? 'تعديل مخزن' : 'إضافة مخزن جديد';
  document.getElementById('edit-warehouse-id').value = id || '';
  if (isEdit) {
    const w = currentWarehouses.find(x => String(x.id) === String(id));
    document.getElementById('warehouse-name').value = w.name;
    document.getElementById('warehouse-location').value = w.location;
  } else {
    document.getElementById('warehouse-name').value = '';
    document.getElementById('warehouse-location').value = '';
  }
  showModal('warehouse-modal');
}

window.openContactModal = function (id = null) {
  const isEdit = id !== null;
  document.getElementById('contact-modal-title').innerText = isEdit ? 'تعديل جهة اتصال' : 'إضافة جهة اتصال';
  document.getElementById('edit-contact-id').value = id || '';
  if (isEdit) {
    const c = currentContacts.find(x => String(x.id) === String(id));
    document.getElementById('contact-name').value = c.name;
    document.getElementById('contact-phone').value = c.phone || '';
    document.getElementById('contact-type').value = c.type;
    document.getElementById('contact-tag').value = c.tag || '';
  } else {
    document.getElementById('contact-name').value = '';
    document.getElementById('contact-phone').value = '';
    document.getElementById('contact-type').value = 'مورد';
    document.getElementById('contact-tag').value = '';
  }
  showModal('contact-modal');
}

window.openUnitModal = function (id = null) {
  const isEdit = id !== null;
  document.getElementById('unit-modal-title').innerText = isEdit ? 'تعديل وحدة' : 'إضافة وحدة قياسية';
  document.getElementById('edit-unit-id').value = id || '';
  if (isEdit) {
    const u = currentUnits.find(x => String(x.id) === String(id));
    document.getElementById('unit-name').value = u.name;
  } else {
    document.getElementById('unit-name').value = '';
  }
  showModal('unit-modal');
}

window.openItemModal = function (id = null) {
  const isEdit = id !== null;
  document.getElementById('item-modal-title').innerText = isEdit ? 'تعديل صنف' : 'إضافة صنف جديد';
  document.getElementById('edit-item-id').value = id || '';
  currentItemBom = [];

  if (isEdit) {
    const i = currentItems.find(x => String(x.id) === String(id));
    // [FIXED] Removed debug alert that was showing on every item edit
    document.getElementById('item-code').value = i.code;
    document.getElementById('item-name').value = i.name;
    document.getElementById('item-category').value = i.category || 'مادة مستهلكة';
    document.getElementById('item-unit').value = i.unit;
    if(document.getElementById('item-alt-unit')) document.getElementById('item-alt-unit').value = i.alt_unit||'';
    if(document.getElementById('item-conv-factor')) document.getElementById('item-conv-factor').value = i.conv_factor||1;
    if(document.getElementById('item-alt-unit')) document.getElementById('item-alt-unit').value = i.alt_unit || '';
    if(document.getElementById('item-conv-factor')) document.getElementById('item-conv-factor').value = i.conv_factor || 1;
    document.getElementById('item-tag').value = i.tag || '';
    if(document.getElementById('item-sales-price')) document.getElementById('item-sales-price').value = i.sales_price || 0;
    currentItemBom = i.bom || [];
    document.getElementById('bom-produced-qty').value = i.bom_produced_qty || 1;
  } else {
    document.getElementById('item-code').value = '';
    document.getElementById('item-name').value = '';
    document.getElementById('item-tag').value = '';
    if(document.getElementById('item-sales-price')) document.getElementById('item-sales-price').value = 0;
    document.getElementById('item-category').value = 'مادة مستهلكة';
    document.getElementById('item-unit').value = currentUnits[0]?.name || '';
    if(document.getElementById('item-alt-unit')) document.getElementById('item-alt-unit').value = '';
    if(document.getElementById('item-conv-factor')) document.getElementById('item-conv-factor').value = 1;
    document.getElementById('bom-produced-qty').value = 1;
  }

  const bomItemSelect = document.getElementById('bom-item');
  bomItemSelect.innerHTML = currentItems.filter(x => !isEdit || x.id !== id).map(i => `<option value="${i.id}">${i.name}</option>`).join('');

  document.getElementById('item-category').dispatchEvent(new Event('change'));
  renderBomTable();
  showModal('item-modal');
}

document.getElementById('item-category').addEventListener('change', (e) => {
  document.getElementById('item-bom-group').style.display = e.target.value === 'منتج تام' ? 'block' : 'none';
});

document.getElementById('btn-add-bom').addEventListener('click', () => {
  const item_id = parseInt(document.getElementById('bom-item').value);
  const qty = parseFloat(document.getElementById('bom-qty').value);
  if (!item_id || !qty || qty <= 0) return;
  const itemDef = currentItems.find(i => String(i.id) === String(item_id));
  if (currentItemBom.find(b => b.item_id === item_id)) { alert('المادة مضافة مسبقاً!'); return; }
  currentItemBom.push({ item_id, item_name: itemDef.name, qty, unit: itemDef.unit });
  renderBomTable();
});

function renderBomTable() {
  const tbody = document.getElementById('bom-tbody'); tbody.innerHTML = '';
  if (currentItemBom.length === 0) {
    tbody.innerHTML = `<tr><td colspan="3" style="text-align:center; color:#888; padding: 15px;">لم يتم إضافة أي مواد خام بعد. (أضف المكونات من الأعلى)</td></tr>`;
    return;
  }
  (currentItemBom || []).forEach((b, idx) => {
    tbody.innerHTML += `<tr><td>${b.item_name}</td><td><strong>${b.qty}</strong> <small>${b.unit}</small></td><td style="text-align:center;"><button onclick="currentItemBom.splice(${idx}, 1); renderBomTable();" class="action-btn btn-delete" style="width:30px;height:30px;padding:0;"><i class="fas fa-trash"></i></button></td></tr>`;
  });
}

window.dismissNotification = async function (notifId) {
  const notif = allNotifications.find(n => String(n.id) === String(notifId));
  if (notif) {
    notif.read = true;
    await window.DB.update('notifications', notif);
    await loadData();
  }
};

let currentProjectBoqItems = [];
let currentProjectAttachments = [];

window.addProjectBoqRow = function () {
  currentProjectBoqItems.push({ name: '', unit: 'متر', qty: 1, price: 0 });
  renderProjectBoqTable();
};

window.removeProjectBoqRow = function (index) {
  currentProjectBoqItems.splice(index, 1);
  renderProjectBoqTable();
};

window.updateProjectBoqRow = function (index, field, value) {
  currentProjectBoqItems[index][field] = value;
  renderProjectBoqTable();
};

function renderProjectBoqTable() {
  const tbody = document.getElementById('project-boq-tbody');
  tbody.innerHTML = '';
  let total = 0;
  (currentProjectBoqItems || []).forEach((it, idx) => {
    const rowTotal = (it.qty || 0) * (it.price || 0);
    total += rowTotal;
    tbody.innerHTML += `
      <tr>
        <td><input type="text" value="${it.name || ''}" onchange="updateProjectBoqRow(${idx}, 'name', this.value)"></td>
        <td><input type="text" style="width: 80px;" value="${it.unit || ''}" onchange="updateProjectBoqRow(${idx}, 'unit', this.value)"></td>
        <td><input type="number" style="width: 80px;" value="${it.qty || 1}" onchange="updateProjectBoqRow(${idx}, 'qty', parseFloat(this.value))"></td>
        <td><input type="number" style="width: 100px;" value="${it.price || 0}" onchange="updateProjectBoqRow(${idx}, 'price', parseFloat(this.value))"></td>
        <td>${rowTotal.toLocaleString('en-US')}</td>
        <td><button class="action-btn btn-delete" onclick="removeProjectBoqRow(${idx})">❌</button></td>
      </tr>
    `;
  });
  document.getElementById('project-boq-total').innerText = total.toLocaleString('en-US');
}

// Project attachments logic
document.getElementById('project-attachment-upload')?.addEventListener('change', function (e) {
  const files = e.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const reader = new FileReader();
    reader.onload = function (evt) {
      currentProjectAttachments.push({ name: file.name, data: evt.target.result });
      renderProjectAttachments();
    };
    reader.readAsDataURL(file);
  }
  this.value = ''; // Reset input
});

window.removeProjectAttachment = function (index) {
  currentProjectAttachments.splice(index, 1);
  renderProjectAttachments();
};

function renderProjectAttachments() {
  const list = document.getElementById('project-attachments-list');
  list.innerHTML = '';
  (currentProjectAttachments || []).forEach((att, idx) => {
    list.innerHTML += `
      <div style="display: flex; justify-content: space-between; background: rgba(0,0,0,0.05); padding: 5px 10px; border-radius: 4px; align-items: center;">
        <a href="${att.data}" download="${att.name}" style="color: var(--primary); text-decoration: none;"><i class="fas fa-file"></i> ${att.name}</a>
        <button class="action-btn btn-delete" style="padding: 2px 5px;" onclick="removeProjectAttachment(${idx})">❌</button>
      </div>
    `;
  });
}

window.openProjectModal = function (id = null) {
  const isEdit = id !== null;
  document.getElementById('proj-modal-title').innerText = isEdit ? 'تعديل مشروع' : 'إضافة مشروع جديد';
  document.getElementById('edit-project-id').value = id || '';
  if (isEdit) {
    const p = currentProjects.find(x => String(x.id) === String(id));
    document.getElementById('project-name').value = p.name || '';
    document.getElementById('project-desc').value = p.desc || '';
    document.getElementById('project-client').value = p.client || '';
    document.getElementById('project-client-consultant').value = p.client_consultant || '';
    document.getElementById('project-contractor-consultant').value = p.contractor_consultant || '';
    document.getElementById('project-duration').value = p.duration || '';
    document.getElementById('project-axes').value = p.axes || '';
    currentProjectBoqItems = p.boq_items ? JSON.parse(JSON.stringify(p.boq_items)) : [];
    currentProjectAttachments = p.attachments ? JSON.parse(JSON.stringify(p.attachments)) : [];
  } else {
    document.getElementById('project-name').value = '';
    document.getElementById('project-desc').value = '';
    document.getElementById('project-client').value = '';
    document.getElementById('project-client-consultant').value = '';
    document.getElementById('project-contractor-consultant').value = '';
    document.getElementById('project-duration').value = '';
    document.getElementById('project-axes').value = '';
    currentProjectBoqItems = [];
    currentProjectAttachments = [];
  }
  renderProjectBoqTable();
  renderProjectAttachments();
  showModal('project-modal');
}

window.openInvoiceModal = function () {
  currentInvoiceItems = [];
  document.getElementById('edit-invoice-id').value = '';
  document.getElementById('inv-modal-title').innerText = 'إنشاء مستند مخزني';
  document.getElementById('invoice-type').dispatchEvent(new Event('change'));
  renderInvoiceDraftTable();
  setTimeout(() => { if (window.updateAvailableBalance) window.updateAvailableBalance(); }, 200);
  showModal('invoice-modal');
}

// --- DYNAMIC FORM HANDLERS ---
document.getElementById('user-role').addEventListener('change', (e) => {
  const role = e.target.value;
  const wh = document.getElementById('user-warehouse-group');
  const proj = document.getElementById('user-project-group');
  const customPerms = document.getElementById('custom-permissions-group');

  if (role === 'مدير عام') {
    wh.style.display = 'none';
    proj.style.display = 'none';
    customPerms.style.display = 'none';
  } else {
    // Show permissions, warehouses, and projects for ALL other roles
    wh.style.display = 'block';
    proj.style.display = 'block';
    customPerms.style.display = 'block';
  }
});

document.getElementById('invoice-warehouse').addEventListener('change', (e) => {
  if (window.updateAvailableBalance) window.updateAvailableBalance();
});

document.getElementById('invoice-type').addEventListener('change', (e) => {
  const type = e.target.value;
  const toWh = document.getElementById('invoice-to-wh-group');
  const proj = document.getElementById('invoice-project-group');
  const contact = document.getElementById('invoice-contact-group');
  const price = document.getElementById('invoice-price-group');
  const lblWh = document.getElementById('lbl-invoice-wh');

  toWh.style.display = 'none'; proj.style.display = 'none'; price.style.display = 'none'; contact.style.display = 'none';
  lblWh.innerText = 'المخزن';

  if (type === 'out_project' || type === 'depreciate_asset') {
    proj.style.display = 'block'; lblWh.innerText = 'صرف من مخزن';
  } else if (type === 'transfer') {
    toWh.style.display = 'block'; lblWh.innerText = 'صرف من مخزن';
  } else if (type === 'in') {
    price.style.display = 'block'; contact.style.display = 'block'; lblWh.innerText = 'استلام في مخزن';
  } else {
    price.style.display = 'block'; lblWh.innerText = 'مخزن الجرد الأولي';
  }
  renderInvoiceDraftTable();
});

document.getElementById('invoice-item').addEventListener('change', (e) => {
  if (window.updateAvailableBalance) window.updateAvailableBalance();
  const item_id = window.getInvoiceItemId();
  const itemDef = currentItems.find(i => String(i.id) === String(item_id));
  const assetGroup = document.getElementById('invoice-asset-code-group');
  const unitWrap = document.getElementById('invoice-item-unit-wrap');
  const unitSel = document.getElementById('invoice-item-unit-sel');
  
  
  
  if (itemDef) {
    if (itemDef.name.includes('\u062E\u0634\u0628') || itemDef.name.includes('\u0623\u062E\u0634\u0627\u0628')) {
        document.getElementById('wood-modal-item-id').value = item_id;
        document.getElementById('wood-modal-item-name').innerText = '\u0625\u062F\u062E\u0627\u0644 \u0645\u0642\u0627\u0633\u0627\u062A: ' + itemDef.name;
        document.getElementById('wood-entries-tbody').innerHTML = '';
        if(typeof window.addWoodEntryRow === 'function') window.addWoodEntryRow();
        document.getElementById('wood-modal').style.display = 'flex';
    }
    if (itemDef.category === 'أصل') {
      assetGroup.style.display = 'block';
    } else {
      assetGroup.style.display = 'none';
      document.getElementById('invoice-asset-code').value = '';
    }
    
    unitSel.innerHTML = `<option value="${itemDef.unit}">${itemDef.unit}</option>`;
    if (itemDef.alt_unit && itemDef.conv_factor) {
      unitSel.innerHTML += `<option value="${itemDef.alt_unit}">${itemDef.alt_unit} (معامل: ${itemDef.conv_factor})</option>`;
      unitSel.value = itemDef.alt_unit; // Default to larger unit
      unitWrap.style.display = 'flex';
    } else {
      unitWrap.style.display = 'none';
    }
  } else {
    assetGroup.style.display = 'none';
    unitWrap.style.display = 'none';
  }
});

// --- INVOICE DRAFTING ---
document.getElementById('btn-add-invoice-item').addEventListener('click', () => {
  const item_id = window.getInvoiceItemId();
  let qty = parseFloat(document.getElementById('invoice-qty').value);
  const price = parseFloat(document.getElementById('invoice-price').value) || 0;
  const asset_code = document.getElementById('invoice-asset-code').value || '';
  const selectedUnit = document.getElementById('invoice-item-unit-sel') ? document.getElementById('invoice-item-unit-sel').value : null;

  if (!item_id || !qty || qty <= 0) { alert('البيانات غير صحيحة'); return; }
  const itemDef = currentItems.find(i => String(i.id) === String(item_id));
  if (!itemDef) { alert('الصنف غير موجود'); return; }
  if (currentInvoiceItems.find(i => i.item_id === item_id && i.asset_code === asset_code)) { alert('الصنف مضاف مسبقاً للفاتورة'); return; }

  let displayQtyStr = qty + ' ' + (selectedUnit || itemDef.unit);
  let finalPrice = price;

  // Only multiply if they selected the alternative unit
  if (selectedUnit && selectedUnit === itemDef.alt_unit && parseFloat(itemDef.conv_factor || 1) > 1) {
    const factor = parseFloat(itemDef.conv_factor);
    displayQtyStr = qty + ' ' + itemDef.alt_unit + ' = ' + (qty * factor) + ' ' + itemDef.unit;
    qty = qty * factor;
    finalPrice = price / factor; // The price they entered is for the big unit, we need price per small unit
  }

  currentInvoiceItems.push({ item_id, item_name: itemDef.name, category: itemDef.category, unit: itemDef.unit, qty, price: finalPrice, asset_code, alt_unit: itemDef.alt_unit, conv_factor: itemDef.conv_factor, display_qty: displayQtyStr });
  renderInvoiceDraftTable();
});

window.removeDraftItem = function (index) {
  currentInvoiceItems.splice(index, 1);
  renderInvoiceDraftTable();
}

function renderInvoiceDraftTable() {
  const tbody = document.getElementById('invoice-items-tbody');
  tbody.innerHTML = '';
  const type = document.getElementById('invoice-type').value;
  const showPrice = (type === 'in' || type === 'opening_balance');

  document.querySelector('#invoice-modal .col-price').style.display = showPrice ? 'table-cell' : 'none';

  (currentInvoiceItems || []).forEach((it, idx) => {
    const altDisplay = it.alt_unit && parseFloat(it.conv_factor||1)!==1 ? ` <small style="color:var(--text-secondary)">(${(it.qty/parseFloat(it.conv_factor)).toFixed(4).replace(/\.?0+$/,'')} ${it.alt_unit})</small>` : '';
    
    let notesDisplay = it.notes ? `<br><small style="color: #666;">${it.notes}</small>` : '';
    let row = `<tr><td>${it.item_name}${notesDisplay}</td><td>${it.asset_code || '-'}</td><td>${it.qty} ${it.unit}${altDisplay}</td>`;

    if (showPrice) {
      row += `<td>${it.price}</td><td>${it.qty * it.price}</td>`;
    } else {
      row += `<td style="display:none"></td><td>-</td>`;
    }
    row += `<td><button onclick="removeDraftItem(${idx})" class="action-btn btn-delete">X</button></td></tr>`;
    tbody.innerHTML += row;
  });
}

window._saveInvoiceHandler = async function() {
  try {
    if (currentInvoiceItems.length === 0) { alert('يجب إضافة صنف واحد على الأقل للمستند!'); return; }

    const editIdStr = document.getElementById('edit-invoice-id').value;
    const isEdit = editIdStr !== '';
    const type = document.getElementById('invoice-type').value;
    const primary_wh = parseInt(document.getElementById('invoice-warehouse').value);
    const to_wh = document.getElementById('invoice-to-warehouse').value ? parseInt(document.getElementById('invoice-to-warehouse').value) : null;
    const proj = document.getElementById('invoice-project').value ? parseInt(document.getElementById('invoice-project').value) : null;
    const contact_id = document.getElementById('invoice-contact').value ? parseInt(document.getElementById('invoice-contact').value) : null;

    if (!primary_wh) { alert('حدد المخزن الأساسي'); return; }

    if (type === 'depreciate_asset' || (type === 'out_project' && currentInvoiceItems.some(it => it.category === 'أصل'))) {
      if (currentUser.role === 'أمين مخزن') {
        alert('تحذير الأمان: لا تملك الصلاحية لإهلاك (أصول ومعدات) على المشاريع. يرجى الرجوع للإدارة.');
        return;
      } else {
        const confirm1 = confirm('تحذير (1/2): أنت على وشك إهلاك أصل/معدة على هذا المشروع بالكامل وتكليفه مالياً! هل تريد الاستمرار؟');
        if (!confirm1) return;
        const confirm2 = confirm('تأكيد نهائي (2/2): عملية الإهلاك ستُخرج الأصل من العهدة المخزنية نهائياً لتصبح تالفة أو مستهلكة على المشروع. هل أنت متأكد؟');
        if (!confirm2) return;
      }
    }

    if (!isEdit && (type === 'out_project' || type === 'depreciate_asset' || type === 'transfer')) {
      if (type === 'transfer' && primary_wh === to_wh) { alert('لا يمكن التحويل لنفس المخزن'); return; }
      for (let it of currentInvoiceItems) {
        const bal = (balancesCache[it.item_id] && balancesCache[it.item_id].warehouses[primary_wh]) || 0;
        if (it.qty > bal) {
          alert(`رصيد الصنف "${it.item_name}" غير كافٍ في المخزن. المتاح: ${bal}`);
          return;
        }
      }
    }

    const attachInput = document.getElementById('invoice-attachment');
    let attachmentBase64 = null;
    if (attachInput && attachInput.files && attachInput.files[0]) {
      attachmentBase64 = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.readAsDataURL(attachInput.files[0]);
      });
    }

    const invoice = {
      date: new Date().toISOString(),
      type: type,
      items: currentInvoiceItems,
      user: currentUser ? currentUser.username : 'غير معروف',
      attachment: attachmentBase64,
      status: 'completed'
    };
    if (isEdit) {
      const oldInv = allInvoices.find(x => x.id === parseInt(editIdStr));
      invoice.id = oldInv.id;
      invoice.date = oldInv.date;
    }

    if (type === 'in' || type === 'opening_balance') {
      invoice.to_warehouse_id = primary_wh;
      const toWh = currentWarehouses.find(w => String(w.id) === String(primary_wh));
      if (!toWh) { alert('المخزن المحدد غير موجود، يرجى اختيار مخزن صحيح'); return; }
      invoice.to_warehouse_name = toWh.name;
      if (type === 'in' && contact_id) {
        invoice.contact_id = contact_id;
        invoice.contact_name = currentContacts.find(c => String(c.id) === String(contact_id))?.name;
      }
    } else if (type === 'out_project' || type === 'depreciate_asset') {
      invoice.from_warehouse_id = primary_wh;
      const fromWh = currentWarehouses.find(w => String(w.id) === String(primary_wh));
      if (!fromWh) { alert('المخزن المحدد غير موجود، يرجى اختيار مخزن صحيح'); return; }
      invoice.from_warehouse_name = fromWh.name;
      invoice.project_id = proj;
      const projDef = currentProjects.find(p => String(p.id) === String(proj));
      if (!projDef) { alert('يرجى اختيار مشروع أولاً'); return; }
      invoice.project_name = projDef.name;
      (invoice.items || []).forEach(it => { const b = balancesCache[it.item_id]; it.price = b ? b.avgCost : 0; });
    } else if (type === 'transfer') {
      invoice.from_warehouse_id = primary_wh;
      const fromWh2 = currentWarehouses.find(w => String(w.id) === String(primary_wh));
      if (!fromWh2) { alert('مخزن المصدر غير موجود'); return; }
      invoice.from_warehouse_name = fromWh2.name;
      invoice.to_warehouse_id = to_wh;
      const toWh2 = currentWarehouses.find(w => String(w.id) === String(to_wh));
      if (!toWh2) { alert('مخزن الوجهة غير موجود، يرجى تحديد مخزن الوجهة'); return; }
      invoice.to_warehouse_name = toWh2.name;
      invoice.status = 'pending_receipt';
    }

    let invId;
    if (isEdit) { await window.DB.update('transactions', invoice); invId = invoice.id; }
    else { invId = await window.DB.add('transactions', invoice); }

    // SYNC JOURNAL ENTRIES FOR STORE ISSUE
    await window.syncStoreJournalEntry(invId);

    if (!isEdit && type === 'transfer') {
      const receiverUsers = currentUsers.filter(u => u.warehouse_id === to_wh || (u && u.role) === 'مدير عام');
      for (let ru of receiverUsers) {
        await window.DB.add('notifications', {
          user: r(u && u.username), warehouse_id: to_wh,
          message: `يوجد إذن تحويل قادم من ${invoice.from_warehouse_name} بانتظار استلامك واعتمادك.`,
          invoice_id: invId, date: new Date().toISOString(), read: false
        });
      }
    }

    closeModal('invoice-modal');
    await loadData();
    alert('تم حفظ المستند بنجاح!');
  } catch (e) {
    alert("خطأ أثناء حفظ المستند: " + e.message);
    console.error(e);
  }
};
// ربط زرار الحفظ بعد تحميل كل الملفات
window.addEventListener('load', function() {
  var btn = document.getElementById('btn-save-invoice');
  if (btn) {
    btn.addEventListener('click', window._saveInvoiceHandler);
  }
});
// --- MANUFACTURE MODAL ---
window.openManufactureModal = function () {
  document.getElementById('manufacture-date').value = new Date().toISOString().slice(0, 16);

  const whSelect = document.getElementById('manufacture-warehouse');
  const allWhOptions = currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  if (currentUser.role === 'مدير عام') { whSelect.innerHTML = allWhOptions; }
  else {
    const myWh = currentWarehouses.find(w => w.id === currentUser.warehouse_id);
    if (myWh) whSelect.innerHTML = `<option value="${myWh.id}">${myWh.name}</option>`;
  }

  const prods = currentItems.filter(i => i.category === 'منتج تام' && i.bom && i.bom.length > 0);
  document.getElementById('manufacture-product').innerHTML = prods.length > 0 ? prods.map(p => `<option value="${p.id}">${p.name}</option>`).join('') : '<option value="">-- لا يوجد منتجات تامة لها مكونات --</option>';

  document.getElementById('manufacture-qty').value = 1;
  renderManufactureTable();
  showModal('manufacture-modal');
}

function renderManufactureTable() {
  const tbody = document.getElementById('manufacture-items-tbody'); tbody.innerHTML = '';
  const prodId = parseInt(document.getElementById('manufacture-product').value);
  const targetQty = parseFloat(document.getElementById('manufacture-qty').value) || 0;
  const whId = parseInt(document.getElementById('manufacture-warehouse').value);

  if (!prodId || targetQty <= 0) return;
  const prodDef = currentItems.find(i => String(i.id) === String(prodId));
  if (!prodDef || !prodDef.bom) return;

  const bomProducedQty = prodDef.bom_produced_qty || 1;

  (prodDef.bom || []).forEach((b, idx) => {
    const requiredQty = (b.qty / bomProducedQty) * targetQty;
    const bal = (balancesCache[b.item_id] && balancesCache[b.item_id].warehouses[whId]) || 0;
    const isOk = bal >= requiredQty;
    const status = `<span id="man-status-${idx}" style="color:${isOk ? 'var(--success)' : 'var(--danger)'}">${isOk ? 'متوفر' : 'عجز'} (${bal})</span>`;

    tbody.innerHTML += `<tr>
      <td>${b.item_name}</td>
      <td>${b.qty} <small>${b.unit}</small></td>
      <td>
        <div style="display:flex; align-items:center; gap:5px; justify-content:flex-end;">
          <input type="number" id="man-qty-${idx}" data-idx="${idx}" data-item="${b.item_id}" class="man-editable-qty" min="0" step="0.001" value="${requiredQty.toFixed(3)}" style="width:100px; margin:0; text-align:center;">
          <small>${b.unit}</small>
        </div>
      </td>
      <td>${status}</td>
    </tr>`;
  });
}

document.getElementById('manufacture-items-tbody').addEventListener('input', (e) => {
  if (e.target.classList.contains('man-editable-qty')) {
    const idx = e.target.getAttribute('data-idx');
    const itemId = e.target.getAttribute('data-item');
    const whId = parseInt(document.getElementById('manufacture-warehouse').value);
    const newQty = parseFloat(e.target.value) || 0;
    const bal = (balancesCache[itemId] && balancesCache[itemId].warehouses[whId]) || 0;
    const isOk = bal >= newQty;
    const statusSpan = document.getElementById(`man-status-${idx}`);
    if (statusSpan) {
      statusSpan.style.color = isOk ? 'var(--success)' : 'var(--danger)';
      statusSpan.innerText = `${isOk ? 'متوفر' : 'عجز'} (${bal})`;
    }
  }
});

document.getElementById('manufacture-product').addEventListener('change', renderManufactureTable);
document.getElementById('manufacture-qty').addEventListener('input', renderManufactureTable);
document.getElementById('manufacture-warehouse').addEventListener('change', renderManufactureTable);

document.getElementById('btn-save-manufacture').addEventListener('click', async () => {
  try {
    const prodId = parseInt(document.getElementById('manufacture-product').value);
    const targetQty = parseFloat(document.getElementById('manufacture-qty').value);
    const whId = parseInt(document.getElementById('manufacture-warehouse').value);
    const dateStr = document.getElementById('manufacture-date').value;

    if (!prodId || !targetQty || targetQty <= 0 || !whId || !dateStr) { alert('تأكد من إدخال جميع البيانات!'); return; }
    const prodDef = currentItems.find(i => String(i.id) === String(prodId));
    const bomProducedQty = prodDef.bom_produced_qty || 1;

    // Check balances from inputs
    let rawItems = [];
    let hasError = false;

    (prodDef.bom || []).forEach((b, idx) => {
      const inputEl = document.getElementById(`man-qty-${idx}`);
      if (!inputEl) return;
      const consumedQty = parseFloat(inputEl.value) || 0;
      if (consumedQty <= 0) return; // Skip zero usage

      const bal = (balancesCache[b.item_id] && balancesCache[b.item_id].warehouses[whId]) || 0;
      if (bal < consumedQty) {
        alert(`لا يوجد رصيد كافٍ من المادة: ${b.item_name} في هذا المخزن! المطلوب: ${consumedQty}، المتاح: ${bal}`);
        hasError = true;
      } else {
        rawItems.push({ item_id: b.item_id, item_name: b.item_name, qty: consumedQty, unit: b.unit });
      }
    });

    if (hasError) return;
    if (rawItems.length === 0) { alert('يجب استهلاك مادة واحدة على الأقل للتصنيع!'); return; }

    const attachInput = document.getElementById('manufacture-attachment');
    let attachmentBase64 = null;
    if (attachInput && attachInput.files && attachInput.files[0]) {
      attachmentBase64 = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.readAsDataURL(attachInput.files[0]);
      });
    }

    const invoice = {
      type: 'manufacture', date: dateStr,
      from_warehouse_id: whId, from_warehouse_name: currentWarehouses.find(w => String(w.id) === String(whId)).name,
      product_id: prodId, produced_item_name: prodDef.name, produced_qty: targetQty,
      items: rawItems, user: currentUser.username, created_at: new Date().toISOString(),
      attachment: attachmentBase64
    };

    await window.DB.add('transactions', invoice);
    closeModal('manufacture-modal'); await loadData();
  } catch (e) { alert("خطأ: " + e.message); }
});

// --- DELETE LOGIC ---
function isEntityReferenced(entityType, id) {
  if (entityType === 'item') return allInvoices.some(inv => inv.items && inv.items.some(it => String(it.item_id) === String(id)));
  if (entityType === 'warehouse') return allInvoices.some(inv => inv.from_warehouse_id === id || inv.to_warehouse_id === id);
  if (entityType === 'project') return allInvoices.some(inv => inv.project_id === id);
  if (entityType === 'user') return allInvoices.some(inv => inv.user === id);
  if (entityType === 'contact') return allInvoices.some(inv => inv.contact_id === id);
  return false;
}



window.deleteItem = async function (id) {
  if (isEntityReferenced('item', id)) { alert('لا يمكن حذف الصنف لاستخدامه في حركات سابقة!'); return; }
  if (confirm('متأكد من حذف الصنف؟')) { await window.DB.remove('items', id); await loadData(); }
}
window.deleteWarehouse = async function (id) {
  if (isEntityReferenced('warehouse', id)) { alert('لا يمكن حذف المخزن لاستخدامه في حركات!'); return; }
  if (confirm('متأكد من حذف المخزن؟')) { await window.DB.remove('warehouses', id); await loadData(); }
}
window.deleteProject = async function (id) {
  if (isEntityReferenced('project', id)) { alert('لا يمكن حذف المشروع لاستخدامه في صرفيات!'); return; }
  if (confirm('متأكد من الحذف؟')) { await window.DB.remove('projects', id); await loadData(); }
}
window.deleteContact = async function (id) {
  if (isEntityReferenced('contact', id)) { alert('لا يمكن حذف جهة الاتصال لوجود فواتير مسجلة باسمه!'); return; }
  if (confirm('متأكد من الحذف؟')) { await window.DB.remove('contacts', id); await loadData(); }
}
window.deleteUnit = async function (id) {
  const u = currentUnits.find(x => String(x.id) === String(id));
  if (currentItems.some(i => i.unit === u.name)) { alert('لا يمكن حذف الوحدة لارتباطها بأصناف مسجلة!'); return; }
  if (confirm('متأكد من الحذف؟')) { await window.DB.remove('units', id); await loadData(); }
}
window.deleteUser = async function (id) {
  const u = currentUsers.find(x => String(x.id) === String(id));
  if (allInvoices.some(inv => inv.user === (u && u.username))) { alert('لا يمكن حذفه لوجود حركات باسمه!'); return; }
  if (confirm('متأكد من حذف المستخدم؟')) { await window.DB.remove('users', id); await loadData(); }
}
window.deleteInvoice = async function (id) {
  if (confirm('تنبيه: سيتم حذف الحركة والقيد المحاسبي المرتبط بها إن وجد! تأكيد؟')) {
    // Attempt to delete associated journal entries
    try {
      const allJ = await window.DB.getAll('journal_entries') || [];
      const possibleRefs = [
        `فاتورة مبيعات #${id}`, `فاتورة مشتريات #${id}`,
        `voucher_${id}`, `transfer_${id}`,
        `sales_return_${id}`, `purchases_return_${id}`,
        `pay_abstract_${id}`, `settlement_${id}`,
        `subcontract_abstract_${id}`, `pay_subcontract_abstract_${id}`
      ];

      // Find journal entries that match this transaction ID
      const jToDelete = allJ.filter(j =>
        (j.reference && possibleRefs.includes(j.reference)) ||
        (j.ref_id === id) ||
        (j.reference && j.reference.includes(`#${id}`))
      );

      for (let j of jToDelete) {
        await window.DB.remove('journal_entries', j.id);
      }
    } catch (e) {
      console.error('Error deleting related journal entry:', e);
    }

    // Delete linked vouchers
    try {
      const allTransactions = await window.DB.getAll('transactions');
      const linkedVouchers = allTransactions.filter(t => t.linked_invoice_id == id);
      for (let v of linkedVouchers) {
        // Also delete journal entries for these vouchers
        const vJournals = allJ.filter(j => j.reference && j.reference.includes(`${v.id}`));
        for (let j of vJournals) {
          await window.DB.remove('journal_entries', j.id);
        }
        // DELETE STORE JOURNAL IF EXISTS
        const _jrnls3 = await window.DB.getAll('journal_entries') || [];
        const _sJrnls3 = _jrnls3.filter(j => j.source_type === 'store_out' && String(j.source_id) === String(v.id));
        for(let _j3 of _sJrnls3) await window.DB.remove('journal_entries', _j3.id);
        
        await window.DB.remove('transactions', v.id);
      }
    } catch (e) { console.error("Failed to delete linked vouchers", e); }

    // DELETE STORE JOURNAL IF EXISTS
        const _jrnls = await window.DB.getAll('journal_entries') || [];
        const _sJrnls = _jrnls.filter(j => j.source_type === 'store_out' && String(j.source_id) === String(id));
        for(let _j of _sJrnls) await window.DB.remove('journal_entries', _j.id);
        
        await window.DB.remove('transactions', id);
    await loadData();
    if (typeof closeModal === 'function') closeModal('details-modal');
  }
}

// --- BASIC SAVE LOGIC (CRUD) ---
/* listener moved to saveUserDebug */

document.getElementById('btn-save-warehouse').addEventListener('click', async () => {
  try {
    const editIdStr = document.getElementById('edit-warehouse-id').value;
    const name = document.getElementById('warehouse-name').value;
    const location = document.getElementById('warehouse-location').value;
    if (name) {
      const obj = { name, location };
      if (editIdStr) { obj.id = parseInt(editIdStr); await window.DB.update('warehouses', obj); }
      else { await window.DB.add('warehouses', obj); }
      closeModal('warehouse-modal'); await loadData();
    } else { alert('أدخل اسم المخزن!'); }
  } catch (e) { alert("خطأ: " + e.message); }
});

document.getElementById('btn-save-contact').addEventListener('click', async () => {
  try {
    const editIdStr = document.getElementById('edit-contact-id').value;
    const name = document.getElementById('contact-name').value;
    const phone = document.getElementById('contact-phone').value;
    const type = document.getElementById('contact-type').value;
    const tag = document.getElementById('contact-tag').value;
    if (name) {
      const obj = { name, phone, type, tag };
      if (editIdStr) { obj.id = parseInt(editIdStr); await window.DB.update('contacts', obj); }
      else { await window.DB.add('contacts', obj); }
      closeModal('contact-modal'); await loadData();
    } else { alert('أدخل اسم جهة الاتصال!'); }
  } catch (e) { alert("خطأ: " + e.message); }
});

document.getElementById('btn-save-unit').addEventListener('click', async () => {
  try {
    const editIdStr = document.getElementById('edit-unit-id').value;
    const name = document.getElementById('unit-name').value;
    if (name) {
      const isDup = currentUnits.some(u => u.name === name && u.id !== parseInt(editIdStr));
      if (isDup) { alert('الوحدة مسجلة بالفعل!'); return; }
      const obj = { name };
      if (editIdStr) { obj.id = parseInt(editIdStr); await window.DB.update('units', obj); }
      else { await window.DB.add('units', obj); }
      closeModal('unit-modal'); await loadData();
    } else { alert('أدخل اسم الوحدة!'); }
  } catch (e) { alert("خطأ: " + e.message); }
});

document.getElementById('btn-save-item').addEventListener('click', async () => {
  try {
    const editIdStr = document.getElementById('edit-item-id').value;
    const code = document.getElementById('item-code').value;
    const name = document.getElementById('item-name').value;
    const unit = document.getElementById('item-unit').value;
    const altUnit = document.getElementById('item-alt-unit')?.value || '';
    const convFactor = parseFloat(document.getElementById('item-conv-factor')?.value) || 1;
    const category = document.getElementById('item-category').value;

    const isDup = currentItems.some(i => (i.code === code || i.name === name) && i.id !== parseInt(editIdStr));
    if (isDup) { alert('الصنف مسجل بالفعل!'); return; }

    if (code && name) {
      const bomProducedQty = parseFloat(document.getElementById('bom-produced-qty').value) || 1;
      const tag = document.getElementById('item-tag').value;
      const salesPrice = parseFloat(document.getElementById('item-sales-price')?.value) || 0;
      const baseObj = { code, name, unit, alt_unit: altUnit, conv_factor: convFactor, category, tag, sales_price: salesPrice, bom: category === 'منتج تام' ? currentItemBom : [], bom_produced_qty: category === 'منتج تام' ? bomProducedQty : 1 };
      if (editIdStr) { 
         const existing = currentItems.find(i => String(i.id) === String(editIdStr));
         const obj = existing ? { ...existing, ...baseObj } : baseObj;
         obj.id = parseInt(editIdStr); 
         await window.DB.update('items', obj); 
      }
      else { await window.DB.add('items', baseObj); }
      closeModal('item-modal'); 
      await loadData();
      if(typeof renderItems === 'function') renderItems();
    } else { alert('أدخل كود واسم الصنف!'); }
  } catch (e) { alert("خطأ: " + e.message); }
});

document.getElementById('btn-save-project').addEventListener('click', async () => {
  try {
    const editIdStr = document.getElementById('edit-project-id').value;
    const name = document.getElementById('project-name').value;
    const desc = document.getElementById('project-desc').value;
    const client = document.getElementById('project-client').value;
    const client_consultant = document.getElementById('project-client-consultant').value;
    const contractor_consultant = document.getElementById('project-contractor-consultant').value;
    const duration = document.getElementById('project-duration').value;
    const axes = document.getElementById('project-axes').value;
    const boq_value = currentProjectBoqItems.reduce((sum, item) => sum + ((item.qty || 0) * (item.price || 0)), 0);

    if (name) {
      const obj = {
        name, desc, client, client_consultant, contractor_consultant, duration, axes, boq_value,
        boq_items: currentProjectBoqItems, attachments: currentProjectAttachments
      };
      if (editIdStr) { obj.id = parseInt(editIdStr); await window.DB.update('projects', obj); }
      else { await window.DB.add('projects', obj); }
      closeModal('project-modal'); await loadData();
    } else { alert('أدخل اسم المشروع!'); }
  } catch (e) { alert("خطأ: " + e.message); }
});

// --- RECEIVE & DECISION MODALS ---
window.openReceiveModal = function (invoiceId) {
  const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
  document.getElementById('receive-invoice-id').value = invoiceId;
  document.getElementById('receive-info').innerText = `إذن تحويل رقم #${inv.id} من مخزن ${inv.from_warehouse_name}`;
  const tbody = document.getElementById('receive-items-tbody'); tbody.innerHTML = '';
  let newTotal = 0;
  (inv.items || []).forEach((it, idx) => {
    tbody.innerHTML += `<tr><td>${it.item_name}</td><td>${it.qty} ${it.unit}</td><td><input type="number" id="rec-qty-${idx}" min="0" max="${it.qty}" value="${it.qty}"></td></tr>`;
  });
  showModal('receive-modal');
}
document.getElementById('btn-confirm-receipt').addEventListener('click', async () => {
  try {
    const invoiceId = parseInt(document.getElementById('receive-invoice-id').value);
    const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
    let hasDeficit = false;
    inv.receiver_user = currentUser.username;
    (inv.items || []).forEach((it, idx) => {
      const recQty = parseFloat(document.getElementById(`rec-qty-${idx}`).value);
      it.received_qty = recQty; if (recQty < it.qty) hasDeficit = true;
    });

    if (hasDeficit) {
      inv.status = 'pending_decision';
      const managers = currentUsers.filter(u => (u && u.role) === 'مدير عام');
      for (let m of managers) { await window.DB.add('notifications', { user: m.username, message: `عجز في التحويل #${inv.id}. بانتظار قرارك.`, invoice_id: inv.id, date: new Date().toISOString(), read: false }); }
    } else {
      inv.status = 'completed'; (inv.items || []).forEach(it => {
        it.deducted_qty = it.qty; it.received_qty = it.qty;
      });
    }
    await window.DB.update('transactions', inv);
    const myNotif = allNotifications.find(n => n.invoice_id === inv.id && n.user === currentUser.username);
    if (myNotif) { myNotif.read = true; await window.DB.update('notifications', myNotif); }
    closeModal('receive-modal'); await loadData(); alert('تم تأكيد الاستلام!');
  } catch (e) { alert("خطأ: " + e.message); }
});

window.openDecisionModal = function (invoiceId) {
  const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
  document.getElementById('decision-invoice-id').value = invoiceId;
  document.getElementById('decision-info').innerText = `إذن تحويل #${inv.id} من (${inv.from_warehouse_name}) إلى (${inv.to_warehouse_name})`;
  const tbody = document.getElementById('decision-items-tbody'); tbody.innerHTML = '';
  (inv.items || []).forEach((it) => {
    const diff = it.qty - it.received_qty;
    if (diff > 0) tbody.innerHTML += `<tr><td>${it.item_name}</td><td>${it.qty}</td><td>${it.received_qty}</td><td style="color:var(--danger); font-weight:bold;">${diff}</td></tr>`;
  });
  showModal('decision-modal');
}
document.getElementById('btn-execute-decision').addEventListener('click', async () => {
  try {
    const invoiceId = parseInt(document.getElementById('decision-invoice-id').value);
    const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
    const action = document.getElementById('decision-action').value;

    inv.status = 'completed'; inv.manager_user = currentUser.username;
    (inv.items || []).forEach(it => {

      if (it.received_qty < it.qty) {
        if (action === 'charge_sender') it.deducted_qty = it.received_qty;
        else if (action === 'charge_receiver') { it.received_qty = it.qty; it.deducted_qty = it.qty; }
        else if (action === 'log_deficit') it.deducted_qty = it.qty;
      } else { it.deducted_qty = it.qty; }
    });
    await window.DB.update('transactions', inv);

    // Find all related notifications and mark them as read
    const relatedNotifs = allNotifications.filter(n =>
      n.user === currentUser.username &&
      !n.read &&
      (n.invoice_id === inv.id || String(n.message).includes('#' + inv.id))
    );
    for (let notif of relatedNotifs) {
      notif.read = true;
      await window.DB.update('notifications', notif);
    }

    closeModal('decision-modal'); await loadData(); alert('تم اعتماد القرار وتحديث الأرصدة!');
  } catch (e) { alert("خطأ: " + e.message); }
});

// --- INVOICE VIEW & PRINT ---
window.viewDetails = function (invId) {
  const inv = allInvoices.find(i => String(i.id) === String(invId));

  let typeStr = inv.type === 'in' ? 'إضافة/مشتريات' :
    inv.type === 'out_project' ? 'منصرف لمشروع' :
      inv.type === 'depreciate_asset' ? 'إهلاك أصل' :
        inv.type === 'transfer' ? 'تحويل بين مخازن' :
          inv.type === 'manufacture' ? 'تصنيع' :
            inv.type === 'opening_balance' ? 'رصيد أول المدة' : inv.type;

  let extraInfo = '';
  if (inv.from_warehouse_name) extraInfo += `<strong>من مخزن:</strong> ${inv.from_warehouse_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if (inv.to_warehouse_name) extraInfo += `<strong>إلى مخزن:</strong> ${inv.to_warehouse_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if (inv.contact_name) extraInfo += `<strong>المورد/المقاول:</strong> ${inv.contact_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if (inv.project_name) extraInfo += `<strong>المشروع:</strong> ${inv.project_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if (inv.driver_name) extraInfo += `<br><strong>السائق:</strong> ${inv.driver_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if (inv.car_number) extraInfo += `<strong>رقم السيارة:</strong> ${inv.car_number}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if (inv.receiver_name) extraInfo += `<strong>المستلم:</strong> ${inv.receiver_name}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if (inv.user) extraInfo += `<br><strong>بواسطة:</strong> ${inv.user}&nbsp;&nbsp;&nbsp;&nbsp;`;
  if (inv.notes) extraInfo += `<br><strong>ملاحظات:</strong> ${inv.notes}`;

  document.getElementById('details-info').innerHTML = `
    <div style="background: var(--bg); padding: 15px; border-radius: 8px; line-height: 1.8; border: 1px solid var(--border);">
      <strong>رقم المستند:</strong> #${inv.id} &nbsp;&nbsp;|&nbsp;&nbsp; 
      <strong>التاريخ:</strong> ${new Date(inv.date).toLocaleString('ar-EG')} &nbsp;&nbsp;|&nbsp;&nbsp; 
      <strong>النوع:</strong> <span style="color:var(--primary); font-weight:bold;">${typeStr}</span><br>
      ${extraInfo}
    </div>
  `;
  const tbody = document.getElementById('details-items-tbody'); tbody.innerHTML = '';

  if (inv.type === 'manufacture') {
    const prod = currentItems.find(i => i.id === inv.product_id);
    const pName = prod ? prod.name : (inv.produced_item_name || 'غير معروف');
    const pQty = inv.product_qty || inv.produced_qty || 0;
    const pCost = inv.produced_cost || inv.items.reduce((sum, it) => sum + (it.qty * (balancesCache[it.item_id]?.avgCost || 0)), 0);
    tbody.innerHTML += `<tr style="background:rgba(255,255,255,0.05); color:var(--primary); font-weight:bold;"><td colspan="4">المنتج التام: ${pName} | الكمية المنتجة: ${pQty} | التكلفة الإجمالية: ${pCost.toLocaleString()}</td></tr>`;
  }

  (inv.items || []).forEach(it => {

    let itemName = it.item_name;
    let itemUnit = it.unit;
    if (!itemName && it.item_id) {
      const dbItem = currentItems.find(x => x.id === it.item_id);
      if (dbItem) { itemName = dbItem.name; itemUnit = dbItem.unit || ''; }
    }
    const fmtQty = !isNaN(it.qty) ? Number(it.qty).toLocaleString(undefined, {maximumFractionDigits: 3}) : it.qty;
    const fmtPrice = !isNaN(it.price) && it.price !== null && it.price !== '' ? Number(it.price).toLocaleString(undefined, {maximumFractionDigits: 2}) : '-';
    tbody.innerHTML += `<tr><td>${itemName || '-'}</td><td>${it.asset_code || '-'}</td><td>${fmtQty} ${itemUnit || ''}</td><td>${fmtPrice}</td></tr>`;
  });


  const attachDiv = document.getElementById('details-attachment-section');
  const attachLink = document.getElementById('details-attachment-link');
  if (inv.attachment) {
    attachLink.href = inv.attachment;
    attachDiv.style.display = 'block';
  } else {
    attachDiv.style.display = 'none';
  }

  window.currentViewingInvoiceId = inv.id;
  if (window.renderComments) window.renderComments(inv);
  const commentInput = document.getElementById('details-new-comment');
  if (commentInput) commentInput.value = '';

  const actions = document.getElementById('details-action-buttons');
  let btnHtml = `<button class="btn-primary" onclick="printInvoice(${inv.id})">🖨️ طباعة الإذن</button>`;
  if (currentUser.role === 'مدير عام') btnHtml += `<button class="btn-secondary" style="background:var(--danger);" onclick="deleteInvoice(${inv.id})">🗑️ حذف</button>`;
  btnHtml += `<button class="btn-secondary" onclick="closeModal('details-modal')">إغلاق</button>`;
  actions.innerHTML = btnHtml;
  if (typeof renderRelatedLinks === 'function') renderRelatedLinks('invoice', inv.id, 'details-related-links');
  showModal('details-modal');
}
window.printInvoice = function (invId) {
  const inv = allInvoices.find(i => String(i.id) === String(invId));
  const hasAsset = inv.items && inv.items.some(it => it.category === 'أصل');
  document.getElementById('print-doc-title').innerText = inv.type === 'in' ? 'إذن إضافة (استلام)' : inv.type === 'depreciate_asset' ? 'إذن إهلاك أصل على مشروع' : inv.type === 'out_project' ? (hasAsset ? 'إذن إهلاك أصل على مشروع' : 'إذن صرف مخزني لمشروع') : inv.type === 'transfer' ? 'إذن تحويل بين المخازن' : inv.type === 'manufacture' ? 'أمر تصنيع وإنتاج' : 'مستند أول المدة';

  let info = `<strong>رقم المستند:</strong> #${inv.id} <br><strong>التاريخ:</strong> ${new Date(inv.date).toLocaleString('ar-EG')} <br>`;
  if (inv.from_warehouse_name && inv.type !== 'manufacture') info += `<strong>المنصرف من:</strong> ${inv.from_warehouse_name} <br>`;
  if (inv.type === 'manufacture') info += `<strong>مخزن السحب والإنتاج:</strong> ${inv.from_warehouse_name} <br>`;
  if (inv.to_warehouse_name) info += `<strong>المستلم:</strong> ${inv.to_warehouse_name} <br>`;
  if (inv.project_name) info += `<strong>المشروع:</strong> ${inv.project_name} <br>`;
  if (inv.contact_name) info += `<strong>الجهة (المورد/العميل):</strong> ${inv.contact_name} <br>`;
  info += `<br><strong>تم الإنشاء/الإرسال بواسطة:</strong> ${inv.user} <br>`;
  if (inv.type === 'transfer') {
    info += `<strong>تم الاستلام بواسطة:</strong> ${inv.receiver_user ? inv.receiver_user : 'لم يتم الاستلام بعد'} <br>`;
    if (inv.manager_user) info += `<strong>قرار العجز بواسطة المدير:</strong> ${inv.manager_user} <br>`;
  }
  document.getElementById('print-doc-info').innerHTML = info;

  const tbody = document.getElementById('print-items-tbody'); tbody.innerHTML = '';

  if (inv.type === 'manufacture') {
    tbody.innerHTML += `<tr style="background:#e8f4f8; font-weight:bold;"><td></td><td>المنتج التام (الإنتاج): ${inv.produced_item_name}</td><td>-</td><td>${inv.produced_qty}</td><td>-</td><td>${inv.produced_cost ? inv.produced_cost.toLocaleString('en-US') : '-'}</td></tr>`;
    tbody.innerHTML += `<tr style="background:#eee; text-align:center;"><td colspan="6">المواد الخام المستهلكة في أمر التصنيع أعلاه</td></tr>`;
  }

  (inv.items || []).forEach(it => {

    const total = it.price ? (it.qty * it.price) : 0;
    tbody.innerHTML += `<tr><td>${currentItems.find(x => x.id === it.item_id)?.code || ''}</td><td>${it.item_name}</td><td>${it.asset_code || '-'}</td><td>${it.qty} ${it.unit}</td><td>${it.price ? it.price.toLocaleString('en-US') : '-'}</td><td>${total ? total.toLocaleString('en-US') : '-'}</td></tr>`;
  });
  window.print();
}

// --- PROJECT REPORTS ---
document.getElementById('report-project-filter').addEventListener('change', renderProjectReports);
function renderProjectReports() {
  const projId = document.getElementById('report-project-filter').value;
  const catFilter = document.getElementById('report-category-filter')?.value || 'all';
  const filterFrom = document.getElementById('report-date-from')?.value;
  const filterTo = document.getElementById('report-date-to')?.value;
  const tbody = document.getElementById('project-reports-tbody'); tbody.innerHTML = '';

  if (!projId) { document.getElementById('report-project-total').innerText = '0 ج.م'; return; }
  let totalCost = 0;

  let projInvoices = allInvoices.filter(inv =>
    (inv.type === 'out_project' || inv.type === 'depreciate_asset') && inv.project_id === parseInt(projId)
  );

  // إضافة بنود المخزون من تسويات العهدة المرتبطة بالمشروع
  const settlementItems = [];
  allInvoices.filter(inv => inv.type === 'petty_cash_settlement' && inv.status === 'completed').forEach(s => {
    (s.items || []).forEach(it => {
      const isInventory = it.item_type === 'inventory';
      // project_id بيكون على مستوى البند أو على مستوى التسوية كلها
      const itProjId = it.project_id || s.project_id;
      if (isInventory && String(itProjId) === String(projId)) {
        settlementItems.push({ _fromSettlement: true, _settlement: s, _item: it });
      }
    });
  });

  if (filterFrom) {
    const fromDate = new Date(filterFrom); fromDate.setHours(0, 0, 0, 0);
    projInvoices = projInvoices.filter(t => new Date(t.date) >= fromDate);
  }
  if (filterTo) {
    const toDate = new Date(filterTo); toDate.setHours(23, 59, 59, 999);
    projInvoices = projInvoices.filter(t => new Date(t.date) <= toDate);
  }

  (projInvoices || []).forEach(inv => {
    (inv.items || []).forEach(it => {

      if (catFilter !== 'all' && (it.category || 'مادة مستهلكة') !== catFilter) return;
      const itemTotal = it.qty * (it.price || 0); totalCost += itemTotal;
      tbody.innerHTML += `<tr><td>${new Date(inv.date).toLocaleDateString('ar-EG')}</td><td>#${inv.id}</td><td>${it.item_name}</td><td style="font-weight:bold;">${it.qty} ${it.unit}</td><td>${(it.price || 0).toLocaleString('ar-EG')}</td><td style="color:var(--danger);">${itemTotal.toLocaleString('ar-EG')} ج.م</td></tr>`;
    });
  });

  // إضافة بنود تسويات العهدة
  settlementItems.forEach(({ _settlement: s, _item: it }) => {
    const filterDate = new Date(s.date);
    if (filterFrom) { const fd = new Date(filterFrom); fd.setHours(0, 0, 0, 0); if (filterDate < fd) return; }
    if (filterTo) { const td = new Date(filterTo); td.setHours(23, 59, 59, 999); if (filterDate > td) return; }
    if (catFilter !== 'all' && (it.category || 'مادة مستهلكة') !== catFilter) return;
    const itemTotal = (it.qty || 0) * (it.price || it.unit_price || 0);
    totalCost += itemTotal;
    tbody.innerHTML += `<tr style="background:rgba(33,150,243,0.07)"><td>${new Date(s.date).toLocaleDateString('ar-EG')}</td><td>تسوية #${s.id}</td><td>${it.item_name || it.name}</td><td style="font-weight:bold;">${it.qty || 0} ${it.unit || ''}</td><td>${(it.price || it.unit_price || 0).toLocaleString('ar-EG')}</td><td style="color:var(--danger);">${itemTotal.toLocaleString('ar-EG')} ج.م</td></tr>`;
  });
  document.getElementById('report-project-total').innerText = totalCost.toLocaleString('en-US') + ' ج.م';
}


// ===== تكاليف المشاريع المجمع =====
window.generateProjectCostsReport = function() {
  const table = document.getElementById('project-costs-table');
  const custodiesTable = document.getElementById('custodies-table');
  const subTable = document.getElementById('subcontractors-table');
  if (!table) return;

  const fmtN = n => (parseFloat(n)||0).toLocaleString('en-US', {minimumFractionDigits:2});

  // ===== جدول المشاريع =====
  let thead = `<thead><tr style="background:var(--primary);color:#fff;">
    <th>المشروع</th><th>الحالة</th>
    <th>مواد (إذن صرف)</th><th>مواد (تسوية عهدة)</th>
    <th>مصاريف تسوية</th><th>مستخلصات مقاولين</th>
    <th>إجمالي التكاليف</th><th>قيمة العقد</th><th>الربح / الخسارة</th>
  </tr></thead>`;
  let tbody = '<tbody>';
  let grandTotal = 0;

  (currentProjects || []).forEach(proj => {
    // مواد من أذونات الصرف
    const outInvs = (allInvoices || []).filter(inv =>
      inv.type === 'out_project' && String(inv.project_id) === String(proj.id)
    );
    let materialsCost = 0;
    outInvs.forEach(inv => (inv.items||[]).forEach(it => { materialsCost += (it.qty||0)*(it.price||0); }));

    // مواد + مصاريف من تسويات العهدة
    let settlementMaterials = 0, settlementExpenses = 0;
    (allInvoices || []).filter(inv =>
      inv.type === 'petty_cash_settlement' && inv.status === 'completed'
    ).forEach(s => {
      (s.items || []).forEach(it => {
        const itProjId = it.project_id || s.project_id;
        if (String(itProjId) !== String(proj.id)) return;
        const lineTotal = (it.qty||0) * (it.price||0);
        if (it.item_type === 'inventory') settlementMaterials += lineTotal;
        else settlementExpenses += lineTotal;
      });
    });

    // مستخلصات مقاولي الباطن
    let subcontractorsCost = 0;
    if (window.allSubAbstracts) {
      window.allSubAbstracts.filter(a =>
        String(a.project_id) === String(proj.id) && a.status !== 'cancelled'
      ).forEach(a => { subcontractorsCost += parseFloat(a.net_value)||0; });
    }

    const total = materialsCost + settlementMaterials + settlementExpenses + subcontractorsCost;
    grandTotal += total;
    const contractVal = parseFloat(proj.contract_value || proj.budget || 0);
    const profit = contractVal - total;
    const profitColor = profit >= 0 ? 'color:#388e3c;' : 'color:#d32f2f;';
    const statusColor = proj.status === 'active' ? '#1976d2' : proj.status === 'completed' ? '#388e3c' : '#9e9e9e';

    tbody += `<tr>
      <td style="font-weight:bold;text-align:right;">${proj.name}</td>
      <td><span style="background:${statusColor};color:#fff;padding:2px 8px;border-radius:4px;font-size:12px;">${proj.status==='active'?'نشط':proj.status==='completed'?'مكتمل':'معلق'}</span></td>
      <td>${fmtN(materialsCost)} ج.م</td>
      <td>${fmtN(settlementMaterials)} ج.م</td>
      <td>${fmtN(settlementExpenses)} ج.م</td>
      <td>${fmtN(subcontractorsCost)} ج.م</td>
      <td style="font-weight:bold;background:rgba(0,0,0,0.1);">${fmtN(total)} ج.م</td>
      <td style="color:var(--primary);">${contractVal ? fmtN(contractVal)+' ج.م' : '-'}</td>
      <td style="${profitColor}font-weight:bold;">${contractVal ? (profit>=0?'+':'')+fmtN(profit)+' ج.م' : '-'}</td>
    </tr>`;
  });

  tbody += `<tr style="background:rgba(0,0,0,0.2);font-weight:bold;">
    <td colspan="6">الإجمالي الكلي</td>
    <td>${fmtN(grandTotal)} ج.م</td><td></td><td></td>
  </tr></tbody>`;
  table.innerHTML = thead + tbody;

  // ===== جدول عهد الموظفين =====
  if (custodiesTable) {
    let cHead = `<thead><tr style="background:var(--secondary);color:#fff;">
      <th>الموظف</th><th>المشروع</th><th>إجمالي العهدة</th><th>المُسوَّى</th><th>المتبقي</th>
    </tr></thead>`;
    let cBody = '<tbody>';
    const custodies = (allInvoices||[]).filter(inv => inv.type === 'petty_cash');
    custodies.forEach(c => {
      const settled = (allInvoices||[]).filter(inv =>
        inv.type === 'petty_cash_settlement' && inv.status === 'completed' &&
        String(inv.custody_id) === String(c.id)
      ).reduce((s,inv) => s + (inv.items||[]).reduce((ss,it) => ss+(it.qty||0)*(it.price||0), 0), 0);
      const remaining = (parseFloat(c.amount)||0) - settled;
      const proj = (currentProjects||[]).find(p => String(p.id) === String(c.project_id));
      cBody += `<tr>
        <td>${c.employee_name || c.contact_name || '-'}</td>
        <td>${proj?.name || '-'}</td>
        <td>${fmtN(c.amount)} ج.م</td>
        <td>${fmtN(settled)} ج.م</td>
        <td style="${remaining>0?'color:#d32f2f;':'color:#388e3c;'}font-weight:bold;">${fmtN(remaining)} ج.م</td>
      </tr>`;
    });
    if (!custodies.length) cBody += '<tr><td colspan="5" style="text-align:center;">لا توجد عهد</td></tr>';
    cBody += '</tbody>';
    custodiesTable.innerHTML = cHead + cBody;
  }

  // ===== جدول مستخلصات مقاولين =====
  if (subTable && window.allSubAbstracts && window.allSubContracts) {
    let sHead = `<thead><tr style="background:var(--accent);color:#fff;">
      <th>المقاول</th><th>المشروع</th><th>قيمة العقد</th><th>المستخلصات</th><th>المتبقي</th>
    </tr></thead>`;
    let sBody = '<tbody>';
    (window.allSubContracts||[]).forEach(sc => {
      const abstracts = (window.allSubAbstracts||[]).filter(a =>
        String(a.contract_id) === String(sc.id) && a.status !== 'cancelled'
      );
      const totalAbstracts = abstracts.reduce((s,a) => s+(parseFloat(a.net_value)||0), 0);
      const remaining = (parseFloat(sc.contract_value)||0) - totalAbstracts;
      const proj = (currentProjects||[]).find(p => String(p.id) === String(sc.project_id));
      const contractor = (currentContacts||[]).find(c => String(c.id) === String(sc.subcontractor_id));
      sBody += `<tr>
        <td>${contractor?.name || '-'}</td>
        <td>${proj?.name || '-'}</td>
        <td>${fmtN(sc.contract_value)} ج.م</td>
        <td style="color:#d32f2f;">${fmtN(totalAbstracts)} ج.م</td>
        <td style="${remaining<0?'color:#d32f2f;':'color:#388e3c;'}font-weight:bold;">${fmtN(remaining)} ج.م</td>
      </tr>`;
    });
    if (!(window.allSubContracts||[]).length) sBody += '<tr><td colspan="5" style="text-align:center;">لا توجد عقود مقاولين</td></tr>';
    sBody += '</tbody>';
    subTable.innerHTML = sHead + sBody;
  }
};

// ===== تحويل الوحدات =====
window.unitConversions = {
  // وزن
  'كيلو':   { 'طن': 0.001,   'جرام': 1000,  'كيلو': 1 },
  'طن':     { 'كيلو': 1000,  'جرام': 1e6,   'طن': 1 },
  'جرام':   { 'كيلو': 0.001, 'طن': 0.000001,'جرام': 1 },
  // طول
  'متر':    { 'سم': 100,     'مم': 1000,    'متر': 1 },
  'سم':     { 'متر': 0.01,   'مم': 10,      'سم': 1 },
  'مم':     { 'متر': 0.001,  'سم': 0.1,     'مم': 1 },
  // حجم
  'لتر':    { 'مل': 1000,    'م3': 0.001,   'لتر': 1 },
  'مل':     { 'لتر': 0.001,  'م3': 0.000001,'مل': 1 },
};

window.convertUnit = function(qty, fromUnit, toUnit) {
  if (!fromUnit || !toUnit || fromUnit === toUnit) return qty;
  const map = window.unitConversions[fromUnit];
  if (!map || map[toUnit] === undefined) return null; // لا يمكن التحويل
  return qty * map[toUnit];
};

window.openUnitConverter = function() {
  const existing = document.getElementById('unit-converter-modal');
  if (existing) { existing.style.display = 'flex'; return; }

  const modal = document.createElement('div');
  modal.id = 'unit-converter-modal';
  modal.className = 'modal';
  modal.style.display = 'flex';
  modal.innerHTML = `
    <div class="modal-content" style="width:420px;">
      <h3>🔄 تحويل الوحدات</h3>
      <div class="flex-row" style="gap:10px;margin-bottom:15px;">
        <div class="flex-col" style="flex:1">
          <label>الكمية</label>
          <input type="number" id="uc-qty" value="1" oninput="window.calcUnitConvert()" style="width:100%;">
        </div>
        <div class="flex-col" style="flex:1">
          <label>من وحدة</label>
          <select id="uc-from" onchange="window.calcUnitConvert()" style="width:100%;">
            <optgroup label="وزن"><option>كيلو</option><option>طن</option><option>جرام</option></optgroup>
            <optgroup label="طول"><option>متر</option><option>سم</option><option>مم</option></optgroup>
            <optgroup label="حجم"><option>لتر</option><option>مل</option></optgroup>
          </select>
        </div>
        <div class="flex-col" style="flex:1">
          <label>إلى وحدة</label>
          <select id="uc-to" onchange="window.calcUnitConvert()" style="width:100%;">
            <optgroup label="وزن"><option>كيلو</option><option>طن</option><option>جرام</option></optgroup>
            <optgroup label="طول"><option>متر</option><option>سم</option><option>مم</option></optgroup>
            <optgroup label="حجم"><option>لتر</option><option>مل</option></optgroup>
          </select>
        </div>
      </div>
      <div id="uc-result" style="font-size:24px;font-weight:bold;color:var(--success);text-align:center;padding:15px;background:rgba(0,0,0,0.2);border-radius:8px;margin-bottom:15px;">
        النتيجة ستظهر هنا
      </div>
      <div class="modal-actions">
        <button class="btn-secondary" onclick="document.getElementById('unit-converter-modal').style.display='none'">إغلاق</button>
      </div>
    </div>`;
  document.body.appendChild(modal);
  window.calcUnitConvert();
};

window.calcUnitConvert = function() {
  const qty = parseFloat(document.getElementById('uc-qty').value) || 0;
  const from = document.getElementById('uc-from').value;
  const to = document.getElementById('uc-to').value;
  const result = window.convertUnit(qty, from, to);
  const el = document.getElementById('uc-result');
  if (result === null) {
    el.innerHTML = '<span style="color:var(--danger)">لا يمكن التحويل بين هاتين الوحدتين</span>';
  } else {
    el.innerHTML = qty + ' ' + from + ' = <strong>' + result.toLocaleString('en-US', {maximumFractionDigits:6}) + ' ' + to + '</strong>';
  }
};


// ===== شاشة إعدادات الموظف =====
window.openProfileSettings = function() {
  const existing = document.getElementById('profile-modal');
  if (existing) {
    // Refresh data
    document.getElementById('profile-username-display').innerText = currentUser.username;
    document.getElementById('profile-role-display').innerText = currentUser.role || '-';
    if (currentUser.avatar) document.getElementById('profile-avatar-preview').src = currentUser.avatar;
    existing.style.display = 'flex';
    return;
  }

  const modal = document.createElement('div');
  modal.id = 'profile-modal';
  modal.className = 'modal';
  modal.style.display = 'flex';
  modal.innerHTML = `
    <div class="modal-content" style="width:480px;">
      <h3>👤 إعدادات الحساب الشخصي</h3>

      <div style="text-align:center;margin-bottom:20px;">
        <img id="profile-avatar-preview" src="" onerror="this.style.display='none'"
          style="width:100px;height:100px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);margin-bottom:10px;display:block;margin:0 auto 10px;">
        <div style="font-size:18px;font-weight:bold;" id="profile-username-display">${currentUser.username}</div>
        <div style="color:var(--text-secondary);font-size:14px;" id="profile-role-display">${currentUser.role || ''}</div>
      </div>

      <div style="margin-bottom:15px;">
        <label style="display:block;margin-bottom:6px;">📷 الصورة الشخصية</label>
        <input type="file" id="profile-avatar-input" accept="image/*" onchange="window.previewProfileAvatar(this)" style="width:100%;">
      </div>

      <hr style="border-color:rgba(255,255,255,0.1);margin:15px 0;">
      <h4 style="margin-bottom:12px;">🔐 تغيير كلمة المرور</h4>

      <div class="flex-col" style="margin-bottom:10px;">
        <label>كلمة المرور الحالية</label>
        <input type="password" id="profile-old-pass" placeholder="أدخل كلمة المرور الحالية" style="width:100%;padding:8px;border-radius:5px;">
      </div>
      <div class="flex-col" style="margin-bottom:10px;">
        <label>كلمة المرور الجديدة</label>
        <input type="password" id="profile-new-pass" placeholder="أدخل كلمة المرور الجديدة" style="width:100%;padding:8px;border-radius:5px;">
      </div>
      <div class="flex-col" style="margin-bottom:15px;">
        <label>تأكيد كلمة المرور الجديدة</label>
        <input type="password" id="profile-confirm-pass" placeholder="أعد إدخال كلمة المرور الجديدة" style="width:100%;padding:8px;border-radius:5px;">
      </div>

      <div class="modal-actions" style="margin-top:10px;">
        <button class="btn-secondary" onclick="document.getElementById('profile-modal').style.display='none'">إغلاق</button>
        <button class="btn-primary" onclick="window.saveProfileSettings()">💾 حفظ التغييرات</button>
      </div>
    </div>`;
  document.body.appendChild(modal);
  if (currentUser.avatar) {
    document.getElementById('profile-avatar-preview').src = currentUser.avatar;
    document.getElementById('profile-avatar-preview').style.display = 'block';
  }
};

window.previewProfileAvatar = function(input) {
  if (!input.files || !input.files[0]) return;
  const reader = new FileReader();
  reader.onload = function(e) {
    const img = document.getElementById('profile-avatar-preview');
    img.src = e.target.result;
    img.style.display = 'block';
  };
  reader.readAsDataURL(input.files[0]);
};

window.saveProfileSettings = async function() {
  try {
    const oldPass = document.getElementById('profile-old-pass').value;
    const newPass = document.getElementById('profile-new-pass').value;
    const confirmPass = document.getElementById('profile-confirm-pass').value;
    const avatarInput = document.getElementById('profile-avatar-input');

    // Load user from DB
    const users = await window.DB.getAll('users');
    const userObj = users.find(u => (u && u.username) === currentUser.username);
    if (!userObj) { alert('خطأ: المستخدم غير موجود'); return; }

    // Handle password change
    if (oldPass || newPass || confirmPass) {
      if (!oldPass) { alert('يرجى إدخال كلمة المرور الحالية'); return; }
      if (userObj.password !== oldPass) { alert('كلمة المرور الحالية غير صحيحة'); return; }
      if (!newPass) { alert('يرجى إدخال كلمة المرور الجديدة'); return; }
      if (newPass !== confirmPass) { alert('كلمة المرور الجديدة غير متطابقة'); return; }
      if (newPass.length < 4) { alert('كلمة المرور يجب أن تكون 4 أحرف على الأقل'); return; }
      userObj.password = newPass;
    }

    // Handle avatar
    if (avatarInput && avatarInput.files && avatarInput.files[0]) {
      const avatarBase64 = await new Promise(resolve => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.readAsDataURL(avatarInput.files[0]);
      });
      userObj.avatar = avatarBase64;
      currentUser.avatar = avatarBase64;
      // Update avatar in nav
      const navAvatar = document.getElementById('nav-user-avatar');
      if (navAvatar) { navAvatar.src = avatarBase64; navAvatar.style.display = 'inline-block'; }
    }

    await window.DB.update('users', userObj);
    sessionStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Clear password fields
    document.getElementById('profile-old-pass').value = '';
    document.getElementById('profile-new-pass').value = '';
    document.getElementById('profile-confirm-pass').value = '';

    alert('✅ تم حفظ التغييرات بنجاح');
    document.getElementById('profile-modal').style.display = 'none';
  } catch(e) {
    alert('خطأ: ' + e.message);
  }
};


// --- LOAD DATA & RENDER ---
async function loadData() {
  const loader = document.getElementById('loading-overlay');
  if (loader) loader.style.display = 'flex';
  
  try {
    const allData = await window.DB.getAllStores() || {};

  currentItems = (allData.items || []).filter(Boolean);
  currentProjects = (allData.projects || []).filter(Boolean);
  currentWarehouses = (allData.warehouses || []).filter(Boolean);
  currentUsers = (allData.users || []).filter(Boolean);
  currentContacts = (allData.contacts || []).filter(Boolean);
  currentUnits = (allData.units || []).filter(Boolean);
  allInvoices = (allData.transactions || []).filter(Boolean);
  allNotifications = (allData.notifications || []).filter(Boolean);
  
  window.currentSettingsArray = allData.settings || [];
        const dbLogoSetting = window.currentSettingsArray.find(s => s.key === 'company_logo');
        if (dbLogoSetting && dbLogoSetting.value) {
            localStorage.setItem('company_logo', dbLogoSetting.value);
            if(typeof applyLogo === 'function') applyLogo(dbLogoSetting.value);
        }
  if(window.currentSettingsArray.length > 0) window.currentSettings = window.currentSettingsArray[0];
  
  window.currentAuditLogs = (allData.activity_logs || []).filter(Boolean);
  currentClientAbstracts = (allData.client_abstracts || []).filter(Boolean);
  currentAccounts = (allData.accounts || []).filter(Boolean);
  currentJournals = (allData.journal_entries || []).filter(Boolean);
  allConcreteInvoices = (allData.concrete_invoices || []).filter(Boolean);

  if (currentAccounts.length < 5 || !currentAccounts.find(a => a.name === 'الأصول')) {
    const defaultAccounts = [
      { code: '1', name: 'الأصول', type: 'أصول', parent_id: null },
      { code: '2', name: 'الخصوم', type: 'خصوم', parent_id: null },
      { code: '3', name: 'حقوق الملكية', type: 'حقوق الملكية', parent_id: null },
      { code: '4', name: 'الإيرادات', type: 'إيرادات', parent_id: null },
      { code: '5', name: 'المصروفات', type: 'مصروفات', parent_id: null },
    ];
    for (let acc of defaultAccounts) {
      if (!currentAccounts.find(a => a.name === acc.name)) {
        await window.DB.add('accounts', acc);
      }
    }
    currentAccounts = await window.DB.getAll('accounts');
  }

  // --- AUTO-CREATE ESSENTIAL ACCOUNTS ---
  const essentialAccounts = [
    { name: 'حسابات العملاء', keywords: ['عميل', 'عملاء'], parentKeywords: ['صول'], type: 'فرعي' },
    { name: 'حسابات الموردين', keywords: ['مورد'], parentKeywords: ['خصوم', 'التزام'], type: 'فرعي' },
    { name: 'المخزون', keywords: ['مخزون'], parentKeywords: ['صول'], type: 'رئيسي' },
    { name: 'تكلفة المبيعات', keywords: ['تكلفة المبيعات'], parentKeywords: ['مصروف'], type: 'رئيسي' },
    { name: 'المبيعات', keywords: ['مبيعات', 'إيرادات مبيعات'], parentKeywords: ['إيراد'], type: 'رئيسي' },
    { name: 'ضريبة القيمة المضافة', keywords: ['ضريب', 'قيمة مضافة'], parentKeywords: ['خصوم', 'التزام'], type: 'فرعي' },
    { name: 'الخصم المسموح به', keywords: ['مسموح به'], parentKeywords: ['مصروف'], type: 'فرعي' },
    { name: 'الخصم المكتسب', keywords: ['مكتسب'], parentKeywords: ['إيراد'], type: 'فرعي' }
  ];

  for (let ess of essentialAccounts) {
    if (!currentAccounts.some(a => ess.keywords.some(k => a.name.includes(k)))) {
      const parent = currentAccounts.find(a => ess.parentKeywords.some(k => a.name.includes(k)));
      const newAcc = {
        id: Date.now() + Math.floor(Math.random() * 10000),
        code: '',
        name: ess.name,
        type: ess.type,
        parent_id: parent ? parent.id : null,
        op_debit: 0,
        op_credit: 0
      };
      await window.DB.add('accounts', newAcc);
      currentAccounts.push(newAcc);
      // Wait a tiny bit to avoid ID collision
      await new Promise(r => setTimeout(r, 2));
    }
  }
  // -------------------------------------

  if (currentUnits.length === 0) {
    const defaultUnits = ['حبة', 'كرتونة', 'كجم', 'جرام', 'طن', 'متر', 'لتر', 'عبوة', 'طقم'];
    for (let u of defaultUnits) await window.DB.add('units', { name: u });
    currentUnits = await window.DB.getAll('units');
  }

  calculateBalances();
  populateDropdowns();
  renderAccounts();
  renderJournals();

  let totalInventoryValue = 0;
  for (let id in balancesCache) totalInventoryValue += balancesCache[id].totalValue;

  document.getElementById('stat-items').innerText = currentItems.length;
  const today = new Date().toISOString().split('T')[0];
  document.getElementById('stat-transactions').innerText = allInvoices.filter(t => t.date && String(t.date).startsWith(today)).length;
  document.getElementById('stat-inventory-value').innerText = totalInventoryValue.toLocaleString('ar-EG', { maximumFractionDigits: 2 }) + ' ج.م';

  // Case-insensitive username match + role-based fallback for managers
  const myNotifs = allNotifications.filter(n => {
    if (n.read) return false;
    // Direct username match (case-insensitive, trimmed)
    if ((n.user || '').trim().toLowerCase() === (currentUser.username || '').trim().toLowerCase()) return true;
    // Role-based: مدير عام sees all warehouse/return notifications
    if (currentUser.role === 'مدير عام' && (n.message || '').match(/مشتريات|مبيعات|مرتجع|مخزن/)) return true;
    // Role-based: أمين مخزن sees all warehouse notifications if no specific user assigned
    if ((currentUser.role || '').includes('مخزن') && !n.user && (n.message || '').match(/مشتريات|مبيعات|مرتجع/)) return true;
    return false;
  });
  document.getElementById('stat-pending').innerText = myNotifs.length;
  document.getElementById('notif-count').style.display = myNotifs.length > 0 ? 'inline-block' : 'none';
  document.getElementById('notif-count').innerText = myNotifs.length;

  renderWarehouses(); renderContacts(); renderUnits(); renderUsers(); renderItems(); renderProjects();
  renderInvoices(); renderBalances(); renderNotifications(myNotifs); renderDecisions(); renderStorekeepersDashboard();
  renderProjectReports();
  if (typeof renderSales === 'function') renderSales();
  if (typeof renderPurchases === 'function') renderPurchases();
  if (typeof renderVouchers === 'function') renderVouchers();
  if (typeof renderSalesReturns === 'function') renderSalesReturns();
  if (typeof renderPurchasesReturns === 'function') renderPurchasesReturns();
  if (typeof window.renderAuditLogs === 'function') window.renderAuditLogs();
  } finally {
    const loader = document.getElementById('loading-overlay');
    if (loader) loader.style.display = 'none';
  }
}

function populateDropdowns() {
  const uniqueTags = [...new Set(currentItems.map(i => i.tag).filter(t => t && t.trim() !== ''))];
  let tagOpts = '<option value="">-- كل التاجات --</option>';
  uniqueTags.forEach(t => tagOpts += `<option value="${t}">${t}</option>`);
  
  let tagSel = document.getElementById('invoice-item-tag');
  const iItem = document.getElementById('invoice-item');
  
  if (iItem && !tagSel) {
      const container = iItem.parentElement;
      if (container && container.parentElement) {
          const tagDiv = document.createElement('div');
          tagDiv.className = 'flex-col';
          tagDiv.style.maxWidth = '150px';
          tagDiv.innerHTML = '<label>التاج (الفلتر)</label><select id="invoice-item-tag" onchange="filterInvoiceItemsByTag()" style="padding: 10px; border-radius: 5px; border: 1px solid var(--border);">' + tagOpts + '</select>';
          container.parentElement.insertBefore(tagDiv, container);
          tagSel = document.getElementById('invoice-item-tag');
      }
  } else if (tagSel) {
      tagSel.innerHTML = tagOpts;
  }

  if (iItem) iItem.innerHTML = '<option value="">-- اختر الصنف --</option>' + currentItems.map(i => `<option value="${i.id}">${i.name}</option>`).join('');
  document.getElementById('invoice-contact').innerHTML = currentContacts.map(c => `<option value="${c.id}">${c.name} (${c.type || ''})</option>`).join('');
  document.getElementById('item-unit').innerHTML = currentUnits.map(u => `<option value="${u.name}">${u.name}</option>`).join('');
  const altUnitEl = document.getElementById('item-alt-unit');
  if (altUnitEl) {
    altUnitEl.innerHTML = `<option value="">بدون وحدة بديلة</option>` + currentUnits.map(u => `<option value="${u.name}">${u.name}</option>`).join('');
  }

  const pc = document.getElementById('project-client');
  if (pc) {
    pc.innerHTML = `<option value="">اختر العميل...</option>` + currentContacts.map(c => `<option value="${c.name}">${c.name}</option>`).join('');
  }

  let userProjs = currentProjects;
  if (currentUser.role === 'موظف مخصص' && currentUser.allowed_projects) {
    userProjs = currentProjects.filter(p => currentUser.allowed_projects.includes(p.id));
  } else if (currentUser.role === 'أمين مخزن' && currentUser.project_id) {
    userProjs = currentProjects.filter(p => p.id === currentUser.project_id);
  }

  const userProjOptions = userProjs.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  const userProjReportOptions = `<option value="">-- إختر المشروع --</option>` + userProjOptions;

  document.getElementById('invoice-project').innerHTML = userProjOptions;
  document.getElementById('report-project-filter').innerHTML = userProjReportOptions;

  if (currentUser.role === 'أمين مخزن' && currentUser.project_id) {
    document.getElementById('invoice-project').value = currentUser.project_id;
    document.getElementById('report-project-filter').value = currentUser.project_id;
  } else if (currentUser.role === 'موظف مخصص' && userProjs.length === 1) {
    document.getElementById('invoice-project').value = userProjs[0].id;
    document.getElementById('report-project-filter').value = userProjs[0].id;
  } else if (currentUser.project_id) {
    document.getElementById('invoice-project').value = currentUser.project_id;
    document.getElementById('report-project-filter').value = currentUser.project_id;
  }

  document.getElementById('user-project').innerHTML = `<option value="">-- بدون مشروع محدد --</option>` + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  document.getElementById('user-warehouse').innerHTML = currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');

  let userWhs = currentWarehouses;
  if (currentUser.role === 'موظف مخصص' && currentUser.allowed_warehouses) {
    userWhs = currentWarehouses.filter(w => currentUser.allowed_warehouses.includes(w.id));
  } else if (currentUser.role === 'أمين مخزن' && currentUser.warehouse_id) {
    userWhs = currentWarehouses.filter(w => w.id === currentUser.warehouse_id);
  }

  const allWhOptions = currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  const userWhOptions = userWhs.map(w => `<option value="${w.id}">${w.name}</option>`).join('');

  document.getElementById('invoice-to-warehouse').innerHTML = allWhOptions; // Always all for transfer destination

  let filterOptions = '';
  if (currentUser.role === 'مدير عام' || (currentUser.role === 'موظف مخصص' && userWhs.length !== 1)) {
    filterOptions = `<option value="all">كل المخازن المسموحة</option>` + userWhOptions;
  } else {
    filterOptions = userWhOptions;
  }
  const filterBalance = document.getElementById('filter-warehouse-balance');
  if (filterBalance) filterBalance.innerHTML = filterOptions;

  const transWhSelect = document.getElementById('invoice-warehouse');
  transWhSelect.innerHTML = userWhOptions;

  if (currentUser.role === 'أمين مخزن' && currentUser.warehouse_id) {
    transWhSelect.value = currentUser.warehouse_id;
    if (filterBalance) filterBalance.value = currentUser.warehouse_id;
  } else if (currentUser.role === 'موظف مخصص' && userWhs.length === 1) {
    transWhSelect.value = userWhs[0].id;
    if (filterBalance) filterBalance.value = userWhs[0].id;
  }
}

// --- RENDER TABLES ---
function renderContacts() {
  const tbody = document.getElementById('contacts-tbody'); tbody.innerHTML = '';
  const rawFilter = document.getElementById('filter-contact-tag')?.value.toLowerCase() || '';

  let filtered = currentContacts;
  if (rawFilter) {
    const searchTerms = rawFilter.split(/[,،]/).map(t => t.trim()).filter(t => t);
    if (searchTerms.length > 0) {
      filtered = filtered.filter(c => {
        const itemTag = (c.tag || '').toLowerCase();
        return searchTerms.some(st => itemTag.includes(st));
      });
    }
  }

  (filtered || []).forEach(c => {
    let actions = `<button class="action-btn btn-view" onclick="openContactStatement(${c.id})" style="background:#17a2b8; color:white;">📄 كشف حساب</button> `;
    let waLink = c.phone ? `<a href="https://wa.me/${c.phone}" target="_blank" style="color:#25D366; font-weight:bold; text-decoration:none;">💬 واتساب</a>` : '-';
    if (currentUser.role === '\u0645\u062F\u064A\u0631 \u0639\u0627\u0645' || (currentUser.allowed_modules && currentUser.allowed_modules.includes('contacts'))) actions += `<button class="action-btn btn-edit" onclick="openContactModal(${c.id})">✏️ تعديل</button> <button class="action-btn btn-delete" onclick="deleteContact(${c.id})">🗑️ حذف</button>`;
    tbody.innerHTML += `<tr><td>${c.name}</td><td>${c.type}</td><td><span style="background:rgba(255,255,255,0.1); padding:2px 5px; border-radius:3px;">${c.tag || '-'}</span></td><td>${c.phone || '-'} ${waLink !== '-' ? ' | ' + waLink : ''}</td><td>${actions}</td></tr>`;
  });
}
function renderUnits() {
  const tbody = document.getElementById('units-tbody'); tbody.innerHTML = '';
  (currentUnits || []).forEach(u => {
    let actions = '';
    if (currentUser.role === '\u0645\u062F\u064A\u0631 \u0639\u0627\u0645' || (currentUser.allowed_modules && currentUser.allowed_modules.includes('units'))) actions = `<button class="action-btn btn-edit" onclick="openUnitModal(${u.id})">✏️ تعديل</button> <button class="action-btn btn-delete" onclick="deleteUnit(${u.id})">🗑️ حذف</button>`;
    tbody.innerHTML += `<tr><td>${u.name}</td><td>${actions}</td></tr>`;
  });
}
function renderWarehouses() {
  const tbody = document.getElementById('warehouses-tbody'); tbody.innerHTML = '';
  (currentWarehouses || []).forEach(w => {
    let actions = '';
    if (currentUser.role === '\u0645\u062F\u064A\u0631 \u0639\u0627\u0645' || (currentUser.allowed_modules && currentUser.allowed_modules.includes('warehouses'))) actions = `<button class="action-btn btn-edit" onclick="openWarehouseModal(${w.id})">✏️ تعديل</button> <button class="action-btn btn-delete" onclick="deleteWarehouse(${w.id})">🗑️ حذف</button>`;
    tbody.innerHTML += `<tr><td>${w.name}</td><td>${w.location || '-'}</td><td>${actions}</td></tr>`;
  });
}
function renderUsers() {
  const tbody = document.getElementById('users-tbody'); tbody.innerHTML = '';
  (currentUsers || []).forEach(u => {
    const wh = currentWarehouses.find(w => w.id === u.warehouse_id);
    const proj = currentProjects.find(p => p.id === u.project_id);
    let actions = '';
    if (currentUser.role === '\u0645\u062F\u064A\u0631 \u0639\u0627\u0645' || (currentUser.allowed_modules && currentUser.allowed_modules.includes('users'))) actions = `<button class="action-btn btn-edit" onclick="openUserModal(${u.id})">✏️ تعديل</button> <button class="action-btn btn-delete" onclick="deleteUser(${u.id})">🗑️ حذف</button>`;
    tbody.innerHTML += `<tr><td>${(u && u.username)}</td><td>${(u && u.role)}</td><td>${wh ? wh.name : 'الكل'}</td><td>${proj ? proj.name : 'بدون'}</td><td>${actions}</td></tr>`;
  });
}
window.currentItemsPage = 1;
window.itemsPerPage = 50;

window.nextItemsPage = function() {
  const rawFilter = document.getElementById('filter-item-tag')?.value.toLowerCase() || '';
  let filtered = currentItems;
  if (rawFilter) {
    const searchTerms = rawFilter.split(/[,،]/).map(t => t.trim()).filter(t => t);
    if (searchTerms.length > 0) {
      filtered = filtered.filter(i => searchTerms.some(st => (i.tag || '').toLowerCase().includes(st)));
    }
  }
  const maxPage = Math.ceil((filtered.length || 1) / window.itemsPerPage);
  if (window.currentItemsPage < maxPage) {
    window.currentItemsPage++;
    renderItems();
  }
};

window.prevItemsPage = function() {
  if (window.currentItemsPage > 1) {
    window.currentItemsPage--;
    renderItems();
  }
};

function renderItems(resetPage = false) {
  if (resetPage === true) window.currentItemsPage = 1;
  const tbody = document.getElementById('items-tbody'); tbody.innerHTML = '';
  const rawFilter = document.getElementById('filter-item-tag')?.value.toLowerCase() || '';

  let filtered = currentItems;
  if (rawFilter) {
    const searchTerms = rawFilter.split(/[,،]/).map(t => t.trim()).filter(t => t);
    if (searchTerms.length > 0) {
      filtered = filtered.filter(i => {
        const itemTag = (i.tag || '').toLowerCase();
        return searchTerms.some(st => itemTag.includes(st));
      });
    }
  }

  const maxPage = Math.ceil((filtered.length || 1) / window.itemsPerPage) || 1;
  if (window.currentItemsPage > maxPage) window.currentItemsPage = maxPage;
  if (window.currentItemsPage < 1) window.currentItemsPage = 1;

  const startIndex = (window.currentItemsPage - 1) * window.itemsPerPage;
  const paginated = filtered.slice(startIndex, startIndex + window.itemsPerPage);

  (paginated || []).forEach(i => {
    let actions = '';
    if (currentUser.role === '\u0645\u062F\u064A\u0631 \u0639\u0627\u0645' || (currentUser.allowed_modules && currentUser.allowed_modules.includes('items'))) actions = `<button class="action-btn btn-edit" onclick="openItemModal(${i.id})">\u062A\u0639\u062F\u064A\u0644</button> <button class="action-btn btn-delete" onclick="deleteItem(${i.id})">\u062D\u0630\u0641</button>`;
    tbody.innerHTML += `<tr><td>${i.code}</td><td>${i.name}</td><td><span style="font-size:12px; padding:3px 5px; background:var(--panel-bg); border-radius:5px;">${i.category || 'مادة مستهلكة'}</span></td><td>${i.unit}</td><td><span style="background:rgba(255,255,255,0.1); padding:2px 5px; border-radius:3px;">${i.tag || '-'}</span></td><td>${actions}</td></tr>`;
  });

  const pageInfo = document.getElementById('items-page-info');
  if (pageInfo) {
    pageInfo.innerText = `صفحة ${window.currentItemsPage} من ${maxPage}`;
  }
}
window.openProjectDetails = function (id) {
  const p = currentProjects.find(x => String(x.id) === String(id));
  if (!p) return;
  document.getElementById('pd-name').innerText = p.name || '';
  document.getElementById('pd-desc').innerText = p.desc || '';
  document.getElementById('pd-client').innerText = p.client || '-';
  document.getElementById('pd-duration').innerText = p.duration || '-';
  document.getElementById('pd-client-consultant').innerText = p.client_consultant || '-';
  document.getElementById('pd-contractor-consultant').innerText = p.contractor_consultant || '-';
  document.getElementById('pd-axes').innerText = p.axes || '-';

  const boqTbody = document.getElementById('pd-boq-tbody');
  boqTbody.innerHTML = '';
  let total = 0;
  if (p.boq_items) {
    (p.boq_items || []).forEach(it => {
      const rowTotal = (it.qty || 0) * (it.price || 0);
      total += rowTotal;
      boqTbody.innerHTML += `<tr><td>${it.name || ''}</td><td>${it.unit || ''}</td><td>${it.qty || 1}</td><td>${it.price || 0}</td><td>${rowTotal.toLocaleString('ar-EG')}</td></tr>`;
    });
  }
  document.getElementById('pd-boq-total').innerText = total.toLocaleString('ar-EG');

  const attList = document.getElementById('pd-attachments-list');
  attList.innerHTML = '';
  if (p.attachments && p.attachments.length > 0) {
    (p.attachments || []).forEach(att => {
      attList.innerHTML += `<a href="${att.data}" download="${att.name}" style="color: var(--primary); text-decoration: none; display: block; padding: 5px; background: rgba(0,0,0,0.05); border-radius: 4px; margin-bottom: 5px;"><i class="fas fa-file"></i> ${att.name}</a>`;
    });
  } else {
    attList.innerHTML = '<span style="color:#999; font-size:13px;">لا توجد مرفقات</span>';
  }
  showModal('project-details-modal');
};

function renderProjects() {
  const tbody = document.getElementById('projects-tbody'); tbody.innerHTML = '';

  let userProjs = currentProjects;
  if (currentUser.role === 'موظف مخصص' && currentUser.allowed_projects) {
    userProjs = currentProjects.filter(p => currentUser.allowed_projects.includes(p.id));
  } else if (currentUser.role === 'أمين مخزن' && currentUser.project_id) {
    userProjs = currentProjects.filter(p => p.id === currentUser.project_id);
  }

  (userProjs || []).forEach(p => {
    let actions = `<button class="action-btn btn-view" onclick="openProjectDetails(${p.id})">🔍 عرض</button> <button class="action-btn btn-view" style="background:#6c757d;" onclick="window.openProjectStatement(${p.id})">كشف حساب</button> `;
    if (currentUser.role === '\u0645\u062F\u064A\u0631 \u0639\u0627\u0645' || (currentUser.allowed_modules && currentUser.allowed_modules.includes('projects'))) actions += `<button class="action-btn btn-edit" onclick="openProjectModal(${p.id})">✏️ تعديل</button> <button class="action-btn btn-delete" onclick="deleteProject(${p.id})">\u062D\u0630\u0641</button>`;
    const val = p.boq_value ? p.boq_value.toLocaleString('ar-EG') + ' ج.م' : '-';
    tbody.innerHTML += `<tr><td>${p.name}</td><td>${p.client || '-'}</td><td style="color:var(--primary); font-weight:bold;">${val}</td><td>${actions}</td></tr>`;
  });
}
function renderInvoices() {
  const tbody = document.getElementById('transactions-tbody'); tbody.innerHTML = '';
  const filterType = document.getElementById('filter-invoice-type')?.value || 'all';
  const filterFrom = document.getElementById('filter-invoice-from')?.value;
  const filterTo = document.getElementById('filter-invoice-to')?.value;

  let filtered = [...allInvoices].reverse();

  // Exclude draft and pending_store sales/purchases/returns from the official inventory transactions view
  filtered = filtered.filter(t => {
    if ((t.type === 'sales' || t.type === 'purchases' || t.type === 'sales_return' || t.type === 'purchases_return') && (t.status === 'draft' || t.status === 'pending_store')) return false;
    if (t.type === 'receipt' || t.type === 'payment' || t.type === 'money_transfer' || t.type === 'pay_client_abstract') return false;

    // Exclude sales/purchases/returns that do not contain any inventory items (e.g. only services)
    if (['sales', 'purchases', 'sales_return', 'purchases_return'].includes(t.type)) {
      let hasInventory = false;
      if (t.items && t.items.length > 0) {
        for (let line of t.items) {
          const it = currentItems.find(i => String(i.id) === String(line.item_id));
          if (it && it.category !== 'خدمة') {
            hasInventory = true;
            break;
          }
        }
      }
      if (!hasInventory) return false;
    }

    // Exclude petty_cash_settlement that don't have inventory type items
    if (t.type === 'petty_cash_settlement') {
      let hasInventory = false;
      if (t.items && t.items.length > 0) {
        for (let line of t.items) {
          if (line.item_type === 'inventory') {
            hasInventory = true;
            break;
          }
        }
      }
      if (!hasInventory) return false;
    }
    return true;
  });

  if (currentUser.role === 'أمين مخزن' && currentUser.warehouse_id) {
    filtered = filtered.filter(t => String(t.warehouse_id) === String(currentUser.warehouse_id) || String(t.to_warehouse_id) === String(currentUser.warehouse_id) || String(t.from_warehouse_id) === String(currentUser.warehouse_id));
  } else if (currentUser.role === 'موظف مخصص' && currentUser.allowed_warehouses) {
    filtered = filtered.filter(t => currentUser.allowed_warehouses.some(w => String(w) === String(t.warehouse_id) || String(w) === String(t.to_warehouse_id) || String(w) === String(t.from_warehouse_id)));
  }

  if (filterType !== 'all') {
    filtered = filtered.filter(t => t.type === filterType);
  }
  if (filterFrom) {
    const fromDate = new Date(filterFrom); fromDate.setHours(0, 0, 0, 0);
    filtered = filtered.filter(t => new Date(t.date) >= fromDate);
  }
  if (filterTo) {
    const toDate = new Date(filterTo); toDate.setHours(23, 59, 59, 999);
    filtered = filtered.filter(t => new Date(t.date) <= toDate);
  }

  (filtered || []).forEach(t => {
    let typeLabel = ''; let statusLabel = ''; let whLabel = '';
    if (t.type === 'in') { typeLabel = 'استلام (مورد)'; whLabel = t.to_warehouse_name; }
    else if (t.type === 'opening_balance') { typeLabel = 'أول المدة'; whLabel = t.to_warehouse_name; }
    else if (t.type === 'depreciate_asset') { typeLabel = '<span style="color:var(--danger)">إهلاك أصل لمشروع</span>'; whLabel = t.from_warehouse_name; }
    else if (t.type === 'manufacture') { typeLabel = '<span style="color:var(--secondary); font-weight:bold;">أمر تصنيع</span>'; whLabel = t.from_warehouse_name; }
    else if (t.type === 'out_project') {
      const hasAsset = t.items && t.items.some(it => it.category === 'أصل');
      typeLabel = hasAsset ? '<span style="color:var(--danger)">إهلاك أصل لمشروع</span>' : 'صرف مشروع';
      whLabel = t.from_warehouse_name;
    }
    else if (t.type === 'transfer') { typeLabel = 'تحويل مخزني'; whLabel = `من (${t.from_warehouse_name || currentWarehouses.find(w => w.id == t.from_warehouse_id)?.name}) إلى (${t.to_warehouse_name || currentWarehouses.find(w => w.id == t.to_warehouse_id)?.name})`; }
    else if (t.type === 'sales') { typeLabel = 'فاتورة مبيعات'; whLabel = t.from_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(t.from_warehouse_id || t.warehouse_id))?.name) || '-'; }
    else if (t.type === 'purchases') { typeLabel = 'فاتورة مشتريات'; whLabel = t.to_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(t.to_warehouse_id))?.name) || '-'; }
    else if (t.type === 'sales_return') { typeLabel = 'مرتجع مبيعات'; whLabel = t.to_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(t.to_warehouse_id))?.name) || '-'; }
    else if (t.type === 'purchases_return') { typeLabel = 'مرتجع مشتريات'; whLabel = t.from_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(t.from_warehouse_id || t.warehouse_id))?.name) || '-'; }
    else if (t.type === 'petty_cash_settlement') { typeLabel = 'تسوية عهدة'; whLabel = t.to_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(t.to_warehouse_id))?.name) || '-'; }

    if (t.status === 'completed') statusLabel = '<span style="color:var(--success)">مكتمل</span>';
    else if (t.status === 'pending_receipt') statusLabel = '<span style="color:#f1c40f">قيد الاستلام</span>';
    else if (t.status === 'pending_decision') statusLabel = '<span style="color:var(--danger)">يوجد عجز</span>';
    else if (t.status === 'posted') statusLabel = '<span style="color:var(--success)">مُرحلة</span>';
    else if (t.status === 'approved') statusLabel = '<span style="color:var(--accent)">موافق عليها</span>';

    tbody.innerHTML += `<tr><td>#${t.id}</td><td>${new Date(t.date).toLocaleString('ar-EG')}</td><td>${typeLabel}</td><td style="font-size:13px;">${whLabel}</td><td>${statusLabel}</td><td>${t.user || t.created_by || '-'}</td><td><button onclick="viewDetails(${t.id})" class="btn-primary" style="padding:2px 8px; font-size:12px;">عرض وطباعة</button></td></tr>`;
  });
}
function renderNotifications(notifs) {
  const tbody = document.getElementById('notifications-tbody'); tbody.innerHTML = '';
  (notifs || []).forEach(n => {
    let msg = n.message || '';
    let actionBtn = '';

    if (msg.includes('مشتريات') || msg.includes('مبيعات') || msg.includes('مرتجع')) {
      // Warehouse storekeeper review (purchases, sales, returns)
      actionBtn = `<button onclick="openStorekeeperReviewModal(${n.invoice_id}, '${n.date}')" class="btn-primary" style="background:var(--accent)">مراجعة واعتماد المخزن</button>`;
    } else if (msg.includes('تحويل مخزني') || msg.includes('إذن تحويل')) {
      // Inventory transfer receipt
      actionBtn = `<button onclick="openReceiveModal(${n.invoice_id})" class="btn-primary">فتح إذن التحويل</button>`;
    } else if (msg.includes('مبلغ') || msg.includes('عهدة') || msg.includes('نقدية') || msg.includes('صرف') || msg.includes('قبض')) {
      // Financial receipt (cash to custody) - just confirm with simple button
      actionBtn = `<button onclick="confirmCashNotif(${n.id}, ${n.invoice_id}, '${n.date}')" class="btn-primary" style="background:var(--success)">✅ تأكيد الاستلام</button>`;
    } else if (currentUser.role === 'مدير عام' && msg.includes('عجز')) {
      actionBtn = `<button onclick="openDecisionModal(${n.invoice_id})" class="btn-primary" style="background:var(--danger)">مراجعة العجز</button>`;
    } else if (msg.includes('تعليق') || msg.includes('ذكرك')) {
      actionBtn = `<button onclick="viewDetails(${n.invoice_id}); markNotifAsRead('${n.date}');" class="btn-primary" style="background:var(--secondary)">عرض التعليق</button>`;
    } else {
      // Default: just dismiss
      actionBtn = `<button onclick="n/a" class="btn-primary">عرض</button>`;
    }

    // Add manual dismiss button
    actionBtn += ` <button onclick="dismissNotification(${n.id})" class="btn-secondary" style="padding:4px 8px; font-size:12px; margin-right:5px;">إخفاء ✕</button>`;

    tbody.innerHTML += `<tr><td>${new Date(n.date).toLocaleString('ar-EG')}</td><td>${msg}</td><td>النظام</td><td>${actionBtn}</td></tr>`;
  });

  if (notifs.length === 0) {
    tbody.innerHTML = `<tr><td colspan="4" style="text-align:center; padding: 20px; color: var(--text-secondary);">لا توجد مهام أو إشعارات جديدة بانتظارك</td></tr>`;
  }
}
window.confirmCashNotif = async function (notifId, invoiceId, notifDate) {
  try {
    // Mark the notification as read
    const notif = allNotifications.find(n => n.id == notifId || n.date === notifDate);
    if (notif) {
      notif.read = true;
      await window.DB.update('notifications', notif);
    }

    // Mark the related invoice/voucher as received if it exists
    if (invoiceId) {
      const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
      if (inv && inv.status !== 'posted') {
        inv.receiver_user = currentUser.username;
        inv.receiver_confirmed = true;
        await window.DB.update('transactions', inv);
      }
    }

    await loadData();
    alert('تم تأكيد الاستلام بنجاح.');
  } catch (e) {
    alert('خطأ: ' + e.message);
    console.error(e);
  }
};

window.dismissNotification = async function (notifId) {
  const notif = allNotifications.find(n => n.id == notifId);
  if (notif) {
    notif.read = true;
    await window.DB.update('notifications', notif);

    if (notif.invoice_id) {
       const duplicates = allNotifications.filter(x => x.user === currentUser.username && String(x.invoice_id) === String(notif.invoice_id) && !x.read && x.id !== notif.id);
       for (let dup of duplicates) {
           dup.read = true;
           await window.DB.update('notifications', dup);
       }
    }

    await loadData();
  }
};


window.markNotifAsRead = async function (notifDate) {
  const n = allNotifications.find(x => x.date === notifDate);
  if (n) {
    n.read = true;
    await window.DB.update('notifications', n);

    if (n.invoice_id) {
       const duplicates = allNotifications.filter(x => x.user === currentUser.username && String(x.invoice_id) === String(n.invoice_id) && !x.read && x.id !== n.id);
       for (let dup of duplicates) {
           dup.read = true;
           await window.DB.update('notifications', dup);
       }
    }

    const myNotifs = allNotifications.filter(x => x.user === currentUser.username && !x.read);
    document.getElementById('stat-pending').innerText = myNotifs.length;
    document.getElementById('notif-count').style.display = myNotifs.length > 0 ? 'inline-block' : 'none';
    document.getElementById('notif-count').innerText = myNotifs.length;
    if (typeof renderNotifications === 'function') renderNotifications(myNotifs);
  }
};

window.openStorekeeperReviewModal = function (invId, notifDate) {
  const inv = allInvoices.find(x => parseInt(x.id) === parseInt(invId));
  if (!inv) {
    alert('لم يتم العثور على الفاتورة، قد تكون حذفت.');
    return;
  }

  window.currentStorekeeperReviewInvoice = inv;
  window.currentStorekeeperReviewNotifDate = notifDate;

  document.getElementById('storekeeper-review-title').innerText =
    inv.type === 'purchases' ? 'مراجعة واستلام مشتريات' :
      inv.type === 'sales' ? 'مراجعة وصرف مبيعات' :
        inv.type === 'sales_return' ? 'مراجعة واستلام مرتجع مبيعات' :
          inv.type === 'purchases_return' ? 'مراجعة وصرف مرتجع مشتريات — إخراج من المخزن' :
            'مراجعة مستند مخزني';
  let typeLabel = inv.type === 'purchases' ? 'مشتريات' : inv.type === 'sales' ? 'مبيعات' : inv.type === 'sales_return' ? 'مرتجع مبيعات' : 'مرتجع مشتريات';
  let info = `<strong>رقم المستند:</strong> #${inv.id} &nbsp;|&nbsp; <strong>النوع:</strong> ${typeLabel}`;
  document.getElementById('storekeeper-review-info').innerHTML = info;

  const tbody = document.getElementById('storekeeper-review-tbody');
  tbody.innerHTML = '';
  const items = inv.items || [];
  (items || []).forEach((it, idx) => {
    let itemName = it.item_name;
    if (!itemName && it.item_id) {
      const dbItem = currentItems.find(x => parseInt(x.id) === parseInt(it.item_id));
      if (dbItem) itemName = dbItem.name;
    }
    tbody.innerHTML += `<tr>
      <td>${itemName || '-'}</td>
      <td>${it.qty}</td>
      <td><input type="number" id="review-qty-${idx}" value="${it.qty}" min="0" style="width:100px;"></td>
    </tr>`;
  });

  showModal('storekeeper-review-modal');
};

document.getElementById('btn-approve-storekeeper')?.addEventListener('click', async () => {
  const inv = window.currentStorekeeperReviewInvoice;
  if (!inv) return;

  // Update quantities based on storekeeper input
  (inv.items || []).forEach((it, idx) => {
    const actQty = parseFloat(document.getElementById(`review-qty-${idx}`).value) || 0;
    it.qty = actQty;
    // re-calculate line price/discount if needed, but for inventory qty is what matters most.
  });
  let newTotal = 0; (inv.items || []).forEach(it => {
    newTotal += (it.qty * (it.price || 0));
  });
  inv.total = newTotal;
  inv.amount = newTotal;

  inv.status = 'posted';
  await window.DB.update('transactions', inv);

  if (inv.type === 'sales') await generateSalesJournal(inv);
  else if (inv.type === 'purchases') await generatePurchasesJournal(inv);
  else if (inv.type === 'sales_return') { if (typeof generateSalesReturnJournal === 'function') await generateSalesReturnJournal(inv); }
  else if (inv.type === 'purchases_return') { if (typeof generatePurchasesReturnJournal === 'function') await generatePurchasesReturnJournal(inv); }

  if (window.currentStorekeeperReviewNotifDate) {
    await markNotifAsRead(window.currentStorekeeperReviewNotifDate);
  }

  closeModal('storekeeper-review-modal');
  if (typeof renderNotifications === 'function') renderNotifications();
  await loadData();
  alert('تم الاعتماد وتحديث المخزون والقيد المحاسبي بنجاح.');
});

function renderDecisions() {
  const tbody = document.getElementById('decisions-tbody'); tbody.innerHTML = '';
  allInvoices.filter(i => i.status === 'pending_decision').forEach(d => {
    tbody.innerHTML += `<tr><td>#${d.id}</td><td>${new Date(d.date).toLocaleDateString('ar-EG')}</td><td>${d.from_warehouse_name}</td><td>${d.to_warehouse_name}</td><td><button onclick="openDecisionModal(${d.id})" class="btn-primary" style="background:var(--danger)">اتخاذ قرار</button></td></tr>`;
  });
}
function renderBalances() {
  const tbody = document.getElementById('balances-tbody'); tbody.innerHTML = '';
  const filterWhId = document.getElementById('filter-warehouse-balance').value;
  (currentItems || []).forEach(item => {
    const b = balancesCache[item.id]; if (!b) return;
    let displayQty = (filterWhId === 'all') ? b.globalQty : (b.warehouses[parseInt(filterWhId)] || 0);
    if (displayQty === 0) return;
    const convF = parseFloat(item.conv_factor) || 1;
    const altU = item.alt_unit || '';
    const altDisplay = altU && convF !== 1 ? ` <span style="color:var(--text-secondary);font-size:12px;">(${(displayQty/convF).toLocaleString('ar-EG',{maximumFractionDigits:3})} ${altU})</span>` : '';
    tbody.innerHTML += `<tr><td>${item.code}</td><td style="font-weight:bold">${item.name} ${(item.name.includes('\u062E\u0634\u0628')||item.name.includes('\u0623\u062E\u0634\u0627\u0628')||(item.tag && item.tag.includes('\u062E\u0634\u0628'))) ? '<i class="fas fa-list" style="color:var(--primary); cursor:pointer; margin-right:5px; font-size: 14px;" onclick="showWoodBreakdown(' + item.id + ')" title="\u062A\u0641\u0627\u0635\u064A\u0644 \u0627\u0644\u0645\u0642\u0627\u0633\u0627\u062A"></i>' : ''}</td><td>${b.avgCost.toLocaleString('ar-EG', { maximumFractionDigits: 2 })} \u062C.\u0645</td><td style="font-weight:bold; color:var(--accent)">${displayQty} ${item.unit}${altDisplay}</td><td style="color:var(--success)">${(displayQty * b.avgCost).toLocaleString('ar-EG', { maximumFractionDigits: 2 })} \u062C.\u0645</td></tr>`;
  });
}


// --- EVENTS FOR FILTERS ---
document.getElementById('filter-invoice-type')?.addEventListener('change', renderInvoices);
document.getElementById('filter-invoice-from')?.addEventListener('change', renderInvoices);
document.getElementById('filter-invoice-to')?.addEventListener('change', renderInvoices);

document.getElementById('filter-warehouse-balance')?.addEventListener('change', renderBalances);

document.getElementById('report-project-filter')?.addEventListener('change', renderProjectReports);
document.getElementById('report-category-filter')?.addEventListener('change', renderProjectReports);
document.getElementById('report-date-from')?.addEventListener('change', renderProjectReports);
document.getElementById('report-date-to')?.addEventListener('change', renderProjectReports);

document.getElementById('card-item-filter')?.addEventListener('change', () => window.renderItemCard && window.renderItemCard());
document.getElementById('card-warehouse-filter')?.addEventListener('change', () => window.renderItemCard && window.renderItemCard());
document.getElementById('card-date-from')?.addEventListener('change', () => window.renderItemCard && window.renderItemCard());
document.getElementById('card-date-to')?.addEventListener('change', () => window.renderItemCard && window.renderItemCard());

document.getElementById('filter-contact-tag')?.addEventListener('input', renderContacts);
document.getElementById('filter-item-tag')?.addEventListener('input', renderItems);

// --- ITEM CARD (كارت الصنف) ---
window.renderItemCard = function () {
  const itemId = document.getElementById('card-item-filter')?.value;
  const whId = document.getElementById('card-warehouse-filter')?.value;
  const filterFrom = document.getElementById('card-date-from')?.value;
  const filterTo = document.getElementById('card-date-to')?.value;

  const tbody = document.getElementById('item-card-tbody');
  if (!tbody) return;
  tbody.innerHTML = '';

  if (!itemId) {
    document.getElementById('card-total-in').innerText = '0';
    document.getElementById('card-total-out').innerText = '0';
    document.getElementById('card-final-balance').innerText = '0';
    return;
  }

  let records = [];
  (allInvoices || []).forEach(inv => {
    let typeLabel = '';
    let locLabel = '';

    // Check if item was produced
    if (inv.type === 'manufacture' && inv.product_id === parseInt(itemId)) {
      records.push({ date: inv.date, inv: inv, type: 'وارد (منتج تام)', loc: inv.from_warehouse_name, whId: inv.from_warehouse_id, qtyIn: inv.product_qty || inv.produced_qty || 0, qtyOut: 0, price: inv.produced_cost || 0 });
    }

    // Check if item was in items array
    (inv.items || []).forEach(it => {

      if (String(it.item_id) === String(itemId)) {

        if (inv.type === 'sales_return' && inv.status === 'posted') {
          records.push({ date: inv.date, inv: inv, type: 'مرتجع مبيعات', loc: inv.from_warehouse_name || '', whId: inv.from_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price });
        } else if (inv.type === 'purchases_return' && inv.status === 'posted') {
          records.push({ date: inv.date, inv: inv, type: 'مرتجع مشتريات', loc: inv.from_warehouse_name || inv.to_warehouse_name || '', whId: inv.from_warehouse_id || inv.to_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price });
        } else if (inv.type === 'sales') {
          // فاتورة بيع - تخصم من المخزن
          const whId_s = inv.from_warehouse_id;
          const whName_s = inv.from_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(whId_s))?.name) || '-';
          records.push({ date: inv.date, inv: inv, type: 'فاتورة بيع', loc: whName_s, whId: whId_s, qtyIn: 0, qtyOut: it.qty, price: it.price || 0 });
        } else if (inv.type === 'purchases') {
          // فاتورة شراء - تضيف للمخزن
          const whId_p = inv.to_warehouse_id;
          const whName_p = inv.to_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(whId_p))?.name) || '-';
          records.push({ date: inv.date, inv: inv, type: 'فاتورة شراء', loc: whName_p, whId: whId_p, qtyIn: it.qty, qtyOut: 0, price: it.price || 0 });
        } else if (inv.type === 'in' || inv.type === 'opening_balance') {
          records.push({ date: inv.date, inv: inv, type: inv.type === 'in' ? 'وارد (إذن استلام)' : 'رصيد أول', loc: inv.to_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(inv.to_warehouse_id))?.name) || '-', whId: inv.to_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price });
        } else if (inv.type === 'out_project' || inv.type === 'depreciate_asset') {
          records.push({ date: inv.date, inv: inv, type: inv.type === 'out_project' ? 'منصرف لمشروع' : 'إهلاك أصل', loc: (inv.from_warehouse_name || '-') + (inv.project_name ? ' ⬅️ ' + inv.project_name : ''), whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price });
        } else if (inv.type === 'petty_cash_settlement' && inv.status === 'completed') {
          // تسوية العهدة - إضافة للمخزن
          const whId_st = inv.to_warehouse_id;
          const whName_st = inv.to_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(whId_st))?.name) || '-';
          records.push({ date: inv.date, inv: inv, type: 'تسوية عهدة', loc: whName_st, whId: whId_st, qtyIn: it.qty, qtyOut: 0, price: it.price || 0 });
        } else if (inv.type === 'manufacture') {
          records.push({ date: inv.date, inv: inv, type: 'مسحوب للتصنيع', loc: inv.from_warehouse_name || '-', whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: balancesCache[it.item_id]?.avgCost || 0 });
        } else if (inv.type === 'transfer') {
          // Out from source
          records.push({ date: inv.date, inv: inv, type: 'محول (منصرف)', loc: inv.from_warehouse_name || '-', whId: inv.from_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price || 0 });
          // In to dest
          if (inv.status === 'completed') {
            records.push({ date: inv.date, inv: inv, type: 'محول (وارد)', loc: inv.to_warehouse_name || '-', whId: inv.to_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price || 0 });
          }
        }
      }
    });
  });

  // Sort chronologically
  records.sort((a, b) => new Date(a.date) - new Date(b.date));

  // Warehouse filtering
  if (whId && whId !== 'all') {
    records = records.filter(r => r.whId === parseInt(whId));
  }

  // Date filtering
  if (filterFrom) {
    const fromDate = new Date(filterFrom); fromDate.setHours(0, 0, 0, 0);
    records = records.filter(r => new Date(r.date) >= fromDate);
  }
  if (filterTo) {
    const toDate = new Date(filterTo); toDate.setHours(23, 59, 59, 999);
    records = records.filter(r => new Date(r.date) <= toDate);
  }

  let runningBalance = 0;
  let totalIn = 0;
  let totalOut = 0;

  (records || []).forEach(r => {
    runningBalance += (r.qtyIn - r.qtyOut);
    totalIn += r.qtyIn;
    totalOut += r.qtyOut;
    tbody.innerHTML += `<tr>
      <td>${new Date(r.date).toLocaleString('ar-EG')}</td>
      <td>#${r.inv.id} <button class="btn-primary" style="padding:1px 5px; font-size:11px;" onclick="viewDetails(${r.inv.id})">🔍</button></td>
      <td>${r.type}</td>
      <td>${r.loc}</td>
      <td>${Number(r.price).toLocaleString(undefined, {maximumFractionDigits: 2})}</td>
      <td style="color:var(--success); font-weight:bold;">${r.qtyIn > 0 ? r.qtyIn : '-'}</td>
      <td style="color:var(--danger); font-weight:bold;">${r.qtyOut > 0 ? r.qtyOut : '-'}</td>
      <td style="font-weight:bold; background:rgba(255,255,255,0.05);">${runningBalance}</td>
    </tr>`;
  });

  document.getElementById('card-total-in').innerText = totalIn;
  document.getElementById('card-total-out').innerText = totalOut;
  document.getElementById('card-final-balance').innerText = runningBalance;
}

// Hook populateDropdowns to also populate item card
const oldPopulate = window.populateDropdowns || populateDropdowns;
window.populateDropdowns = function () {
  oldPopulate();
  const cardItemSelect = document.getElementById('card-item-filter');
  if (cardItemSelect) {
    cardItemSelect.innerHTML = `<option value="">-- إختر الصنف --</option>` + currentItems.map(i => `<option value="${i.id}">${i.name}</option>`).join('');
  }
  const cardWhFilter = document.getElementById('card-warehouse-filter');
  if (cardWhFilter) {
    cardWhFilter.innerHTML = `<option value="all">كل المخازن</option>` + currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  }

  const contactTagsList = document.getElementById('contact-tags-list');
  const filterContactTagsList = document.getElementById('filter-contact-tags-list');
  if (contactTagsList || filterContactTagsList) {
    const tags = [...new Set(currentContacts.map(c => c.tag).filter(t => t && t.trim()))];
    const tagsHtml = tags.map(t => `<option value="${t}"></option>`).join('');
    if (contactTagsList) contactTagsList.innerHTML = tagsHtml;
    if (filterContactTagsList) filterContactTagsList.innerHTML = tagsHtml;
  }

  const itemTagsList = document.getElementById('item-tags-list');
  const filterItemTagsList = document.getElementById('filter-item-tags-list');
  if (itemTagsList || filterItemTagsList) {
    const tags = [...new Set(currentItems.map(i => i.tag).filter(t => t && t.trim()))];
    const tagsHtml = tags.map(t => `<option value="${t}"></option>`).join('');
    if (itemTagsList) itemTagsList.innerHTML = tagsHtml;
    if (filterItemTagsList) filterItemTagsList.innerHTML = tagsHtml;
  }
}

// 4. Update available balance on invoice creation
window.updateAvailableBalance = function () {
  const whId = document.getElementById('invoice-warehouse')?.value;
  const itemId = window.getInvoiceItemId();
  let balLabel = document.getElementById('available-balance-label');

  if (!balLabel) {
    const parent = document.getElementById('invoice-item')?.parentElement;
    if (!parent) return;
    balLabel = document.createElement('div');
    balLabel.id = 'available-balance-label';
    balLabel.style = 'font-size:12px; color:var(--success); margin-top:5px; font-weight:bold;';
    parent.appendChild(balLabel);
  }

  if (!whId || !itemId) {
    balLabel.innerText = '';
    return;
  }

  const bInfo = balancesCache[itemId];
  if (bInfo && bInfo.warehouses && bInfo.warehouses[parseInt(whId)] !== undefined) {
    const availableQty = bInfo.warehouses[parseInt(whId)];
    balLabel.innerText = 'الرصيد المتاح حالياً في هذا المخزن: ' + availableQty;
    const itemDef = currentItems.find(i => String(i.id) === String(itemId));
    if (itemDef && (itemDef.name.includes('\u062E\u0634\u0628') || itemDef.name.includes('\u0623\u062E\u0634\u0627\u0628') || (itemDef.tag && itemDef.tag.includes('\u062E\u0634\u0628')))) {
        balLabel.innerHTML += ' <i class="fas fa-list" style="color:var(--primary); cursor:pointer; margin-right:5px; font-size: 14px;" onclick="showWoodBreakdown(' + itemId + ')" title="\u062A\u0641\u0627\u0635\u064A\u0644 \u0627\u0644\u0645\u0642\u0627\u0633\u0627\u062A"></i>';
    }
    
    balLabel.style.color = 'var(--success)';
  } else {
    balLabel.innerText = 'لا يوجد رصيد من هذا الصنف في المخزن المحدد.';
    balLabel.style.color = 'var(--danger)';
  }
}

document.getElementById('invoice-item')?.addEventListener('change', updateAvailableBalance);
document.getElementById('invoice-warehouse')?.addEventListener('change', updateAvailableBalance);



window.renderComments = function (inv) {
  const list = document.getElementById('details-comments-list');
  if (!list) return;
  list.innerHTML = '';
  if (!inv.comments || inv.comments.length === 0) {
    list.innerHTML = '<div style="color:var(--text-secondary); text-align:center; font-size:12px;">لا توجد تعليقات بعد.</div>';
    return;
  }
  (inv.comments || []).forEach(c => {
    let text = c.text;
    // highlight mentions
    text = text.replace(/@([\w\u0600-\u06FF]+)/g, '<span style="color:var(--primary); font-weight:bold;">@$1</span>');
    list.innerHTML += `<div style="margin-bottom:8px; padding-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.05);">
      <strong style="font-size:12px; color:var(--text-secondary);">${c.user} - ${new Date(c.date).toLocaleString('ar-EG')}</strong>
      <div style="margin-top:4px;">${text}</div>
    </div>`;
  });
  list.scrollTop = list.scrollHeight;
};

window.addComment = async function () {
  try {
    const input = document.getElementById('details-new-comment');
    const text = input.value.trim();
    if (!text || !window.currentViewingInvoiceId) return;

    const invIndex = allInvoices.findIndex(i => i.id === window.currentViewingInvoiceId);
    if (invIndex === -1) return;

    const inv = allInvoices[invIndex];
    if (!inv.comments) inv.comments = [];

    const commentObj = { user: currentUser.username, text: text, date: new Date().toISOString() };
    inv.comments.push(commentObj);

    // Extract Mentions
    const mentions = text.match(/@([\w\u0600-\u06FF]+)/g);
    if (mentions) {
      for (let m of mentions) {
        const username = m.substring(1);
        const mentionedUser = currentUsers.find(u => (u && u.username) === username);
        if (mentionedUser) {
          const notif = {
            date: new Date().toISOString(),
            message: `الموظف ${currentUser.username} ذكرك في تعليق على المستند #${inv.id}: "${text}"`,
            user: mentionedUser.username,
            read: false,
            invoice_id: inv.id
          };
          await window.DB.add('notifications', notif);
        }
      }
    }

    await window.DB.update('transactions', inv);
    allInvoices[invIndex] = inv;

    input.value = '';
    renderComments(inv);

    // Update notifications if needed
    allNotifications = ((await window.DB.getAll('notifications')) || []).filter(Boolean);
    const myNotifs = allNotifications.filter(n => n.user === currentUser.username && !n.read);
    if (window.renderNotifications) renderNotifications(myNotifs);
  } catch (e) {
    alert("حدث خطأ أثناء حفظ التعليق: " + e.message);
    console.error(e);
  }
};

window.handleMentionInput = function (input) {
  try {
    const val = input.value;
    const lastAt = val.lastIndexOf('@');
    const dropdown = document.getElementById('mention-dropdown');
    if (!dropdown) return;

    if (lastAt !== -1) {
      const searchStr = val.substring(lastAt + 1).toLowerCase();
      if (searchStr.includes(' ')) {
        dropdown.style.display = 'none';
        return;
      }
      const matches = currentUsers.filter(u => u && u.username && String(u.username).toLowerCase().startsWith(searchStr));
      if (matches.length > 0) {
        dropdown.innerHTML = matches.map(u => `<div style="padding:8px 10px; cursor:pointer; border-bottom:1px solid rgba(0,0,0,0.1); color:black;" class="mention-item" onclick="insertMention('${(u && u.username)}')">${(u && u.username)}</div>`).join('');
        dropdown.style.display = 'block';
      } else {
        dropdown.style.display = 'none';
      }
    } else {
      dropdown.style.display = 'none';
    }
  } catch (e) {
    console.error("Mention Error:", e);
  }
};

window.insertMention = function (username) {
  const input = document.getElementById('details-new-comment');
  const val = input.value;
  const lastAt = val.lastIndexOf('@');
  if (lastAt !== -1) {
    input.value = val.substring(0, lastAt) + '@' + username + ' ';
  }
  document.getElementById('mention-dropdown').style.display = 'none';
  input.focus();
};

// --- LOGO UPLOAD LOGIC ---
const logoUpload = document.getElementById('logo-upload');
if (logoUpload) {
  logoUpload.addEventListener('change', function (e) {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async function (event) {
      const base64 = event.target.result;
      localStorage.setItem('company_logo', base64);
      applyLogo(base64);
      try {
          const settings = (await window.DB.getAll('settings')) || [];
          let logoSet = settings.find(s => s.key === 'company_logo');
          if (logoSet) {
              logoSet.value = base64;
              await window.DB.update('settings', logoSet);
          } else {
              await window.DB.add('settings', { key: 'company_logo', value: base64 });
          }
      } catch(e) { console.error('Failed to save logo to DB', e); }
    };
    reader.readAsDataURL(file);
  });
}

function applyLogo(base64) {
  document.querySelectorAll('.logo-container').forEach(el => {
    el.style.backgroundImage = `url(${base64})`;
    const placeholder = el.querySelector('.logo-placeholder');
    if (placeholder) placeholder.style.display = 'none';
  });
}

const savedLogo = localStorage.getItem('company_logo');
if (savedLogo) applyLogo(savedLogo);

// --- SALES & PURCHASES MODULE ---
let currentSalesLines = [];
let currentPurchasesLines = [];

function renderSales() {
  const tbody = document.getElementById('sales-tbody');
  if (!tbody) return;
  tbody.innerHTML = '';
  const sales = allInvoices.filter(inv => inv.type === 'sales').sort((a, b) => new Date(b.date) - new Date(a.date));

  if (sales.length === 0) {
    tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; padding: 20px; color:#666;">لا توجد فواتير مبيعات حالياً. اضغط على زر "+ إنشاء فاتورة مبيعات" للبدء.</td></tr>';
    return;
  }

  (sales || []).forEach(inv => {
    let contactName = '-';
    if (inv.contact_id) {
      const c = currentContacts.find(x => x.id === inv.contact_id);
      if (c) contactName = c.name;
    }
    let whName = '-';
    if (inv.from_warehouse_id) {
      const w = currentWarehouses.find(x => x.id === inv.from_warehouse_id);
      if (w) whName = w.name;
    }

    let statusSpan = '';
    if (inv.status === 'draft') statusSpan = '<span class="badge" style="background:gray;">مسودة</span>';
    else if (inv.status === 'approved' || inv.status === 'pending_store') statusSpan = '<span class="badge" style="background:orange; color:white;">بانتظار المخزن</span>';
    else if (inv.status === 'posted') statusSpan = '<span class="badge" style="background:green;">مُرحلة</span>';

    let actions = `<button class="action-btn btn-view" onclick="openSalesModal(${inv.id})">👁️ عرض/تعديل</button>`;
    if (inv.status === 'posted') {
      actions += ` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = ${inv.id}; openVoucherModal('receipt', ${inv.id}, ${inv.contact_id}); }">سداد 💵</button>`;
    }
    if (inv.status === 'draft') {
      if (currentUser && currentUser.role === 'مدير عام') {
        actions += `<button class="action-btn btn-delete" onclick="deleteTransaction(${inv.id})">🗑️ حذف</button>`;
      }
      actions += `<button class="action-btn" style="background:var(--accent); margin-right:5px;" onclick="sendInvoiceToStore(${inv.id})">📤 إرسال للمخزن</button>`;
    }

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

function renderPurchases() {
  const tbody = document.getElementById('purchases-tbody');
  if (!tbody) return;
  tbody.innerHTML = '';
  const purchases = allInvoices.filter(inv => inv.type === 'purchases').sort((a, b) => new Date(b.date) - new Date(a.date));

  if (purchases.length === 0) {
    tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; padding: 20px; color:#666;">لا توجد فواتير مشتريات حالياً. اضغط على زر "+ إنشاء فاتورة مشتريات" للبدء.</td></tr>';
    return;
  }

  (purchases || []).forEach(inv => {
    let contactName = '-';
    if (inv.contact_id) {
      const c = currentContacts.find(x => x.id === inv.contact_id);
      if (c) contactName = c.name;
    }
    let whName = '-';
    if (inv.to_warehouse_id) {
      const w = currentWarehouses.find(x => x.id === inv.to_warehouse_id);
      if (w) whName = w.name;
    }

    let statusSpan = '';
    if (inv.status === 'draft') statusSpan = '<span class="badge" style="background:gray;">مسودة</span>';
    else if (inv.status === 'approved' || inv.status === 'pending_store') statusSpan = '<span class="badge" style="background:orange; color:white;">بانتظار المخزن</span>';
    else if (inv.status === 'posted') statusSpan = '<span class="badge" style="background:green;">مُرحلة</span>';

    let actions = `<button class="action-btn btn-view" onclick="openPurchasesModal(${inv.id})">👁️ عرض/تعديل</button>`;
    if (inv.status === 'posted') {
      actions += ` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = ${inv.id}; openVoucherModal('payment', ${inv.id}, ${inv.contact_id}); }">سداد 💵</button>`;
    }
    if (inv.status === 'draft') {
      if (currentUser && currentUser.role === 'مدير عام') {
        actions += `<button class="action-btn btn-delete" onclick="deleteTransaction(${inv.id})">🗑️ حذف</button>`;
      }
      actions += `<button class="action-btn" style="background:var(--accent); margin-right:5px;" onclick="sendInvoiceToStore(${inv.id})">📤 إرسال للمخزن</button>`;
    }

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

window.openSalesModal = function (id = null) {
  document.getElementById('sales-modal-title').innerText = id ? 'عرض / تعديل فاتورة مبيعات' : 'إنشاء فاتورة مبيعات جديدة';
  document.getElementById('edit-sales-id').value = id || '';

  const contactSel = document.getElementById('sales-contact');
  contactSel.innerHTML = '<option value="">اختر العميل...</option>' + currentContacts.map(c => `<option value="${c.id}">${c.name} (${c.type || ''})</option>`).join('');

  const whSel = document.getElementById('sales-warehouse');
  whSel.innerHTML = window.getAllowedWarehousesHtml('اختر المخزن...');

  const projSel = document.getElementById('sales-project');
  projSel.innerHTML = '<option value="">بدون مشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');

  const itemSel = document.getElementById('sales-item');
  const uniqueTagsSales = [...new Set(currentItems.map(i => i.tag).filter(t => t && t.trim() !== ''))];
  let tagOptsSales = '<option value="">-- كل التاجات --</option>';
  uniqueTagsSales.forEach(t => tagOptsSales += `<option value="${t}">${t}</option>`);
  
  let tagSelSales = document.getElementById('sales-item-tag');
  if (itemSel && !tagSelSales) {
      const container = itemSel.parentElement;
      if (container && container.parentElement) {
          const tagDiv = document.createElement('div');
          tagDiv.className = 'flex-col';
          tagDiv.style.maxWidth = '150px';
          tagDiv.innerHTML = '<label>التاج (الفلتر)</label><select id="sales-item-tag" onchange="filterItemsByTagGen(\'sales-item-tag\', \'sales-item\')" style="padding: 10px; border-radius: 5px; border: 1px solid var(--border);">' + tagOptsSales + '</select>';
          container.parentElement.insertBefore(tagDiv, container);
          tagSelSales = document.getElementById('sales-item-tag');
      }
  } else if (tagSelSales) {
      tagSelSales.innerHTML = tagOptsSales;
  }
  itemSel.innerHTML = '<option value="">اختر الصنف...</option>' + currentItems.map(i => `<option value="${i.id}">${i.name} (${i.unit || 'وحدة'})</option>`).join('');

  const trSel = document.getElementById('sales-treasury');
  if (trSel) {
    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('نقد'));
    trSel.innerHTML = '<option value="">-- اختر الخزينة/البنك --</option>' + cashAccounts.map(a => `<option value="${a.id}">${a.name}</option>`).join('');
  }

  if (id) {
    const inv = allInvoices.find(x => String(x.id) === String(id));
    document.getElementById('sales-date').value = inv.date;
    contactSel.value = inv.contact_id || '';
    whSel.value = inv.from_warehouse_id || '';
    projSel.value = inv.project_id || '';
    document.getElementById('sales-status').value = inv.status || 'draft';
    { let bPayS = document.getElementById('btn-pay-inside-sales'); if (inv.status === 'posted') { if (bPayS) bPayS.style.display = 'inline-block'; } else { if (bPayS) bPayS.style.display = 'none'; } }

    let bDelS = document.getElementById('btn-delete-inside-sales'); if (bDelS) bDelS.style.display = 'inline-block';

    // Hide when editing
    currentSalesLines = inv.items ? JSON.parse(JSON.stringify(inv.items)) : [];
  } else {
    document.getElementById('sales-date').value = new Date().toISOString().slice(0, 16);
    document.getElementById('sales-status').value = 'draft';
    let bPayS2 = document.getElementById('btn-pay-inside-sales'); if (bPayS2) bPayS2.style.display = 'none';
    let bDelS2 = document.getElementById('btn-delete-inside-sales'); if (bDelS2) bDelS2.style.display = 'none';
    // Show when creating new
    currentSalesLines = [];
  }

  document.getElementById('sales-qty').value = 1;
  document.getElementById('sales-price').value = 0;
  document.getElementById('sales-discount').value = 0;
  if (document.getElementById('sales-discount-type')) if (document.getElementById('sales-discount-type')) document.getElementById('sales-discount-type').value = 'value';

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

window.updateSalesUnitOptions = function() {
  const itemIdStr = document.getElementById('sales-item').value;
  if(!itemIdStr) return;
  const item = currentItems.find(i => String(i.id) === itemIdStr);
  if(item && document.getElementById('sales-price')) {
    document.getElementById('sales-price').value = item.sales_price || 0;
  }
};

window.addSalesLine = function () {
  const itemIdStr = document.getElementById('sales-item').value;
  if (!itemIdStr) { alert('اختر صنفاً أولاً'); return; }

  const itemId = parseInt(itemIdStr);
  const qty = parseFloat(document.getElementById('sales-qty').value) || 1;
  const price = parseFloat(document.getElementById('sales-price').value) || 0;
  const discount = parseFloat(document.getElementById('sales-discount').value) || 0;
  const discountType = document.getElementById('sales-discount-type').value || 'value';

  currentSalesLines.push({ item_id: itemId, qty, price, discount, discountType });

  document.getElementById('sales-item').value = '';
  document.getElementById('sales-qty').value = 1;
  document.getElementById('sales-price').value = 0;
  document.getElementById('sales-discount').value = 0;
  if (document.getElementById('sales-discount-type')) if (document.getElementById('sales-discount-type')) document.getElementById('sales-discount-type').value = 'value';

  renderSalesLines();
}

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

function renderSalesLines() {
  const tbody = document.getElementById('sales-lines-tbody');
  tbody.innerHTML = '';

  let subtotal = 0;
  let totalDiscountValue = 0;

  (currentSalesLines || []).forEach((line, idx) => {
    const item = currentItems.find(i => i.id === line.item_id);
    const itemName = item ? item.name : '-';

    const lineTotalBeforeDiscount = line.qty * line.price;
    let lineDiscountValue = parseFloat(line.discount) || 0;
    if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }
    const lineTotal = lineTotalBeforeDiscount - lineDiscountValue;

    subtotal += lineTotalBeforeDiscount;
    totalDiscountValue += lineDiscountValue;

    tbody.innerHTML += `<tr>
      <td>${itemName}</td>
      <td>${line.qty}</td>
      <td>${line.price}</td>
      <td>${line.discountType === 'percent' ? line.discount + '%' : (parseFloat(line.discount) || 0).toLocaleString('en-US')}</td>
      <td>${lineTotal.toLocaleString('ar-EG', { minimumFractionDigits: 2 })}</td>
      <td><button class="action-btn btn-delete" onclick="removeSalesLine(${idx})">❌</button></td>
    </tr>`;
  });

  if (document.getElementById('sales-subtotal')) document.getElementById('sales-subtotal').innerText = subtotal.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
  if (document.getElementById('sales-total-discount')) document.getElementById('sales-total-discount').innerText = totalDiscountValue.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
  const net = subtotal - totalDiscountValue;
  if (document.getElementById('sales-net-total')) document.getElementById('sales-net-total').innerText = net.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
  const idStr = document.getElementById('edit-sales-id').value;
  let paid = 0;
  if (idStr) {
    const id = parseInt(idStr);
    const linkedVouchers = allInvoices.filter(t => (t.type === 'receipt' || t.type === 'payment') && t.status === 'posted' && String(t.linked_invoice_id) === String(id));
    paid = linkedVouchers.reduce((sum, v) => sum + (parseFloat(v.amount) || 0), 0);

    const container = document.getElementById('sales-linked-vouchers-container');
    const list = document.getElementById('sales-linked-vouchers-list');
    if (linkedVouchers.length > 0) {
      if (container) container.style.display = 'block';
      if (list) list.innerHTML = linkedVouchers.map(v => {
        const accName = currentAccounts.find(a => a.id == v.treasury_account_id)?.name || 'غير محدد';
        return `<li>🔹 سند ${v.type === 'receipt' ? 'قبض' : 'صرف'} رقم <strong>${v.id}</strong> بمبلغ <strong>${v.amount}</strong> (الخزينة: ${accName}) بتاريخ ${v.date.split('T')[0]}</li>`;
      }).join('');
    } else {
      if (container) container.style.display = 'none';
      if (list) list.innerHTML = '';
    }
  } else {
    const container = document.getElementById('sales-linked-vouchers-container');
    if (container) container.style.display = 'none';
  }
  if (document.getElementById('sales-paid-total')) document.getElementById('sales-paid-total').innerText = paid.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
  if (document.getElementById('sales-remaining')) document.getElementById('sales-remaining').innerText = (net - paid).toLocaleString('ar-EG', { minimumFractionDigits: 2 });
}

document.getElementById('btn-save-sales')?.addEventListener('click', async () => {
  const idStr = document.getElementById('edit-sales-id').value;
  const date = document.getElementById('sales-date').value;
  const contact_id = parseInt(document.getElementById('sales-contact').value) || null;
  const from_warehouse_id = parseInt(document.getElementById('sales-warehouse').value) || null;
  const project_id = parseInt(document.getElementById('sales-project').value) || null;
  const status = document.getElementById('sales-status').value;

  if (!contact_id) { alert('يجب تحديد العميل'); return; }
  if (!from_warehouse_id) { alert('يجب تحديد المخزن الصادر منه البضاعة'); return; }
  if (currentSalesLines.length === 0) { alert('يجب إضافة أصناف للفاتورة'); return; }

  // Calculate total
  let netTotal = 0;
  (currentSalesLines || []).forEach(line => {
    const tot = (line.qty * line.price);
    const disc = parseFloat(line.discount) || 0;
    netTotal += (tot - disc);
  });

  const obj = {
    type: 'sales',
    date,
    contact_id,
    from_warehouse_id,
    to_warehouse_id: null,
    project_id,
    status,
    items: currentSalesLines,
    total: netTotal,
    user: currentUser.username,
    created_at: new Date().toISOString()
  };

  try {
    if (idStr) {
      obj.id = parseInt(idStr);
      await window.DB.update('transactions', obj);

      // Auto-Journal logic for posted
      if (status === 'posted') {
        await generateSalesJournal(obj);
        await window.processInvoicePayment(obj, 'sales');
      }
    } else {
      const newId = await window.DB.add('transactions', obj);
      obj.id = newId;
      if (status === 'posted') {
        await generateSalesJournal(obj);
        await window.processInvoicePayment(obj, 'sales');
      }
    }

    closeModal('sales-modal');
    await loadData();
    alert('تم حفظ الفاتورة بنجاح!');
  } catch (e) { alert("حدث خطأ أثناء الحفظ: " + e.message); }
});

async function generateSalesJournal(invoice) {
  // Check if a journal already exists for this invoice (by reference)
  const existingJ = currentJournals.find(j => j.reference === `فاتورة مبيعات #${invoice.id}`);
  if (existingJ) return; // already posted

  // Find accounts
  const clientAcc = await window.resolveContactAccount(invoice.contact_id, 'sales');
  const salesAcc = await window.resolveSystemAccount('إيرادات المبيعات', ['الإيرادات', 'إيرادات', 'ايرادات'], 'revenues', ['المبيعات', 'مبيعات', 'ايرادات مبيعات']);


  if (!clientAcc || !salesAcc) {
    alert('تحذير: لا يمكن توليد قيد آلي لأنه حدثت مشكلة في إنشاء حساب إيرادات المبيعات أو حساب العميل.');
    return;
  }

  const journal = {
    date: invoice.date.split('T')[0],
    reference: `فاتورة مبيعات #${invoice.id}`,
    desc: `قيد آلي لفاتورة المبيعات رقم ${invoice.id}`,
    status: 'posted',
    created_by: 'النظام',
    total: invoice.total,
    rows: [
      { account_id: clientAcc.id, debit: invoice.total, credit: 0, project_id: invoice.project_id },
      { account_id: salesAcc.id, debit: 0, credit: invoice.total, project_id: invoice.project_id }
    ]
  };

  // If we want to add COGS and Inventory, we need cost calculation. For now, Sales value.
  await window.DB.add('journal_entries', journal);
}

// ==========================================
// PURCHASES
// ==========================================
window.openPurchasesModal = function (id = null) {
  document.getElementById('purchases-modal-title').innerText = id ? 'عرض / تعديل فاتورة مشتريات' : 'إنشاء فاتورة مشتريات جديدة';
  document.getElementById('edit-purchases-id').value = id || '';

  const contactSel = document.getElementById('purchases-contact');
  contactSel.innerHTML = '<option value="">اختر المورد...</option>' + currentContacts.map(c => `<option value="${c.id}">${c.name} (${c.type || ''})</option>`).join('');

  const whSel = document.getElementById('purchases-warehouse');
  whSel.innerHTML = window.getAllowedWarehousesHtml('اختر المخزن...');

  const projSel = document.getElementById('purchases-project');
  projSel.innerHTML = '<option value="">بدون مشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');

  const itemSel = document.getElementById('purchases-item');
  const uniqueTagsPurch = [...new Set(currentItems.map(i => i.tag).filter(t => t && t.trim() !== ''))];
  let tagOptsPurch = '<option value="">-- كل التاجات --</option>';
  uniqueTagsPurch.forEach(t => tagOptsPurch += `<option value="${t}">${t}</option>`);
  
  let tagSelPurch = document.getElementById('purchases-item-tag');
  if (itemSel && !tagSelPurch) {
      const container = itemSel.parentElement;
      if (container && container.parentElement) {
          const tagDiv = document.createElement('div');
          tagDiv.className = 'flex-col';
          tagDiv.style.maxWidth = '150px';
          tagDiv.innerHTML = '<label>التاج (الفلتر)</label><select id="purchases-item-tag" onchange="filterItemsByTagGen(\'purchases-item-tag\', \'purchases-item\')" style="padding: 10px; border-radius: 5px; border: 1px solid var(--border);">' + tagOptsPurch + '</select>';
          container.parentElement.insertBefore(tagDiv, container);
          tagSelPurch = document.getElementById('purchases-item-tag');
      }
  } else if (tagSelPurch) {
      tagSelPurch.innerHTML = tagOptsPurch;
  }
  itemSel.innerHTML = '<option value="">اختر الصنف...</option>' + currentItems.map(i => `<option value="${i.id}">${i.name} (${i.unit || 'وحدة'})</option>`).join('');

  if (id) {
    const inv = allInvoices.find(x => String(x.id) === String(id));
    document.getElementById('purchases-date').value = inv.date;
    contactSel.value = inv.contact_id || '';
    whSel.value = inv.to_warehouse_id || '';
    projSel.value = inv.project_id || '';
    document.getElementById('purchases-status').value = inv.status || 'draft';
    { let bPayP = document.getElementById('btn-pay-inside-purchases'); if (inv.status === 'posted') { if (bPayP) bPayP.style.display = 'inline-block'; } else { if (bPayP) bPayP.style.display = 'none'; } }

    let bDelP = document.getElementById('btn-delete-inside-purchases'); if (bDelP) bDelP.style.display = 'inline-block';

    // Hide when editing
    currentPurchasesLines = inv.items ? JSON.parse(JSON.stringify(inv.items)) : [];
  } else {
    document.getElementById('purchases-date').value = new Date().toISOString().slice(0, 16);
    document.getElementById('purchases-status').value = 'draft';
    let bPayP2 = document.getElementById('btn-pay-inside-purchases'); if (bPayP2) bPayP2.style.display = 'none';
    let bDelP2 = document.getElementById('btn-delete-inside-purchases'); if (bDelP2) bDelP2.style.display = 'none';
    // Show when creating new
    currentPurchasesLines = [];
  }

  document.getElementById('purchases-qty').value = 1;
  document.getElementById('purchases-price').value = 0;
  document.getElementById('purchases-discount').value = 0;
  if (document.getElementById('purchases-discount-type')) if (document.getElementById('purchases-discount-type')) document.getElementById('purchases-discount-type').value = 'value';

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

window.addPurchasesLine = function () {
  const itemIdStr = document.getElementById('purchases-item').value;
  if (!itemIdStr) { alert('اختر صنفاً أولاً'); return; }

  const itemId = parseInt(itemIdStr);
  let qty = parseFloat(document.getElementById('purchases-qty').value) || 1;
  let price = parseFloat(document.getElementById('purchases-price').value) || 0;
  const discount = parseFloat(document.getElementById('purchases-discount').value) || 0;
  const discountType = document.getElementById('purchases-discount-type').value || 'value';

  const itemDef = currentItems.find(i => String(i.id) === String(itemId));
  if (itemDef && parseFloat(itemDef.conv_factor || 1) > 1) {
    const factor = parseFloat(itemDef.conv_factor);
    qty = qty * factor;
    price = price / factor;
  }

  currentPurchasesLines.push({ item_id: itemId, qty, price, discount, discountType });

  document.getElementById('purchases-item').value = '';
  document.getElementById('purchases-qty').value = 1;
  document.getElementById('purchases-price').value = 0;
  document.getElementById('purchases-discount').value = 0;
  if (document.getElementById('purchases-discount-type')) if (document.getElementById('purchases-discount-type')) document.getElementById('purchases-discount-type').value = 'value';

  renderPurchasesLines();
}

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

function renderPurchasesLines() {
  const tbody = document.getElementById('purchases-lines-tbody');
  tbody.innerHTML = '';

  let subtotal = 0;
  let totalDiscountValue = 0;

  (currentPurchasesLines || []).forEach((line, idx) => {
    const item = currentItems.find(i => i.id === line.item_id);
    const itemName = item ? item.name : '-';

    const lineTotalBeforeDiscount = line.qty * line.price;
    let lineDiscountValue = parseFloat(line.discount) || 0;
    if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }
    const lineTotal = lineTotalBeforeDiscount - lineDiscountValue;

    subtotal += lineTotalBeforeDiscount;
    totalDiscountValue += lineDiscountValue;

    tbody.innerHTML += `<tr>
      <td>${itemName}</td>
      <td>${line.qty}</td>
      <td>${line.price}</td>
      <td>${line.discountType === 'percent' ? line.discount + '%' : (parseFloat(line.discount) || 0).toLocaleString('en-US')}</td>
      <td>${lineTotal.toLocaleString('ar-EG', { minimumFractionDigits: 2 })}</td>
      <td><button class="action-btn btn-delete" onclick="removePurchasesLine(${idx})">❌</button></td>
    </tr>`;
  });

  if (document.getElementById('purchases-subtotal')) document.getElementById('purchases-subtotal').innerText = subtotal.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
  if (document.getElementById('purchases-total-discount')) document.getElementById('purchases-total-discount').innerText = totalDiscountValue.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
  const net = subtotal - totalDiscountValue;
  if (document.getElementById('purchases-net-total')) document.getElementById('purchases-net-total').innerText = net.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
  const idStr = document.getElementById('edit-purchases-id').value;
  let paid = 0;
  if (idStr) {
    const id = parseInt(idStr);
    const linkedVouchers = allInvoices.filter(t => (t.type === 'receipt' || t.type === 'payment') && t.status === 'posted' && String(t.linked_invoice_id) === String(id));
    paid = linkedVouchers.reduce((sum, v) => sum + (parseFloat(v.amount) || 0), 0);

    const container = document.getElementById('purchases-linked-vouchers-container');
    const list = document.getElementById('purchases-linked-vouchers-list');
    if (linkedVouchers.length > 0) {
      if (container) container.style.display = 'block';
      if (list) list.innerHTML = linkedVouchers.map(v => {
        const accName = currentAccounts.find(a => a.id == v.treasury_account_id)?.name || 'غير محدد';
        return `<li>🔹 سند ${v.type === 'receipt' ? 'قبض' : 'صرف'} رقم <strong>${v.id}</strong> بمبلغ <strong>${v.amount}</strong> (الخزينة: ${accName}) بتاريخ ${v.date.split('T')[0]}</li>`;
      }).join('');
    } else {
      if (container) container.style.display = 'none';
      if (list) list.innerHTML = '';
    }
  } else {
    const container = document.getElementById('purchases-linked-vouchers-container');
    if (container) container.style.display = 'none';
  }
  if (document.getElementById('purchases-paid-total')) document.getElementById('purchases-paid-total').innerText = paid.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
  if (document.getElementById('purchases-remaining')) document.getElementById('purchases-remaining').innerText = (net - paid).toLocaleString('ar-EG', { minimumFractionDigits: 2 });
}

document.getElementById('btn-save-purchases')?.addEventListener('click', async () => {
  const idStr = document.getElementById('edit-purchases-id').value;
  const date = document.getElementById('purchases-date').value;
  const contact_id = parseInt(document.getElementById('purchases-contact').value) || null;
  const to_warehouse_id = parseInt(document.getElementById('purchases-warehouse').value) || null;
  const project_id = parseInt(document.getElementById('purchases-project').value) || null;
  const status = document.getElementById('purchases-status').value;

  if (!contact_id) { alert('يجب تحديد المورد'); return; }
  if (!to_warehouse_id) { alert('يجب تحديد المخزن الوارد إليه البضاعة'); return; }
  if (currentPurchasesLines.length === 0) { alert('يجب إضافة أصناف للفاتورة'); return; }

  let netTotal = 0;
  (currentPurchasesLines || []).forEach(line => {
    const tot = (line.qty * line.price);
    const disc = parseFloat(line.discount) || 0;
    netTotal += (tot - disc);
  });

  const obj = {
    type: 'purchases',
    date,
    contact_id,
    from_warehouse_id: null,
    to_warehouse_id,
    project_id,
    status,
    items: currentPurchasesLines,
    total: netTotal,
    user: currentUser.username,
    created_at: new Date().toISOString()
  };

  try {
    if (idStr) {
      obj.id = parseInt(idStr);
      await window.DB.update('transactions', obj);
      if (status === 'posted') {
        await generatePurchasesJournal(obj);
        await window.processInvoicePayment(obj, 'purchases');
      }
    } else {
      const newId = await window.DB.add('transactions', obj);
      obj.id = newId;
      if (status === 'posted') {
        await generatePurchasesJournal(obj);
        await window.processInvoicePayment(obj, 'purchases');
      }
    }

    closeModal('purchases-modal');
    await loadData();
    alert('تم حفظ الفاتورة بنجاح!');
  } catch (e) { alert("حدث خطأ أثناء الحفظ: " + e.message); }
});

async function generatePurchasesJournal(invoice) {
  const existingJ = currentJournals.find(j => j.reference === `فاتورة مشتريات #${invoice.id}`);
  if (existingJ) return;

  const supplierAcc = await window.resolveContactAccount(invoice.contact_id, 'purchases');
  const invAcc = await window.resolveSystemAccount('مخزون البضاعة', ['الأصول', 'أصول', 'اصول متداولة'], 'assets', ['المخزون', 'مخزون', 'بضاعة']);

  let creditAccountId = supplierAcc ? supplierAcc.id : null;
  if (invoice.is_from_settlement && invoice.custody_account_id) {
    creditAccountId = invoice.custody_account_id;
  }

  if (!creditAccountId || !invAcc) {
    alert('تحذير: لا يمكن توليد قيد آلي لأنه حدثت مشكلة في إنشاء حساب المخزون أو المورد.');
    return;
  }

  const journal = {
    date: invoice.date.split('T')[0],
    reference: invoice.is_from_settlement ? `تسوية عهدة #${invoice.settlement_ref}` : `فاتورة مشتريات #${invoice.id}`,
    desc: invoice.is_from_settlement ? `قيد آلي لإضافة مخزون من تسوية عهدة رقم ${invoice.settlement_ref}` : `قيد آلي لفاتورة المشتريات رقم ${invoice.id}`,
    status: 'posted',
    created_by: 'النظام',
    total: invoice.total,
    rows: [
      { account_id: invAcc.id, debit: invoice.total, credit: 0, project_id: invoice.project_id },
      { account_id: creditAccountId, debit: 0, credit: invoice.total, project_id: invoice.project_id }
    ]
  };

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

window._sendingInvoiceToStore = window._sendingInvoiceToStore || {};

window.sendInvoiceToStore = async function (invId) {
  if (window._sendingInvoiceToStore[invId]) return;
  window._sendingInvoiceToStore[invId] = true;

  try {
      let inv = allInvoices.find(x => String(x.id) === String(invId));
      if (!inv) {
        const dbInvs = await window.DB.getAll('transactions');
        inv = dbInvs.find(x => String(x.id) === String(invId));
      }
      if (!inv) return;
      inv.status = 'pending_store';
      await window.DB.update('transactions', inv);
    
      const users = await window.DB.getAll('users');
      const storekeepers = users.filter(u => (u && u.role) === 'أمين مخزن');
    
      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);
            let msg = '';
            if (inv.type === 'purchases') msg = 'إذن استلام مشتريات وارد لك للتأكيد';
            else if (inv.type === 'sales') msg = 'إذن صرف مبيعات وارد لك للتأكيد';
            else if (inv.type === 'sales_return') msg = `مرتجع مبيعات #${inv.id} بانتظار استلامك واعتمادك.`;
            else if (inv.type === 'purchases_return') msg = `مرتجع مشتريات #${inv.id} بانتظار اعتمادك وتسجيل خروج البضاعة.`;
            else msg = `مستند #${inv.id} بانتظار مراجعتك.`;
            const notifObj = {
              user: sk.username,
              invoice_id: inv.id,
              message: msg,
              date: new Date().toISOString(),
              read: false
            };
            await window.DB.add('notifications', notifObj);
        }
      }
    
      await loadData();
      alert('تم الإرسال للمخزن بنجاح.');
  } finally {
      delete window._sendingInvoiceToStore[invId];
  }
};



window.renderAbstractComments = function (type, ab) {
  const section = document.getElementById(type + '-chat-section');
  if (section) section.style.display = ab.id ? 'block' : 'none';

  const listId = type + '-comments-list';
  const list = document.getElementById(listId);
  if (!list) return;
  list.innerHTML = '';
  if (!ab.comments || ab.comments.length === 0) {
    list.innerHTML = '<div style="color:var(--text-secondary); text-align:center; font-size:12px;">لا توجد تعليقات بعد.</div>';
    return;
  }
  (ab.comments || []).forEach(c => {
    let text = c.text;
    text = text.replace(/@([\w\u0600-\u06FF]+)/g, '<span style="color:var(--primary); font-weight:bold;">@$1</span>');
    list.innerHTML += `<div style="margin-bottom:8px; padding-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.05);">
      <strong style="font-size:12px; color:var(--text-secondary);">${c.user} - ${new Date(c.date).toLocaleString('ar-EG')}</strong>
      <div style="margin-top:4px;">${text}</div>
    </div>`;
  });
  list.scrollTop = list.scrollHeight;
};

window.addAbstractComment = async function (type) {
  try {
    const input = document.getElementById(type + '-new-comment');
    const text = input.value.trim();
    if (!text || !window.currentViewingAbstractId) return;

    let isClient = type === 'client-abstract';
    let dbTable = isClient ? 'client_abstracts' : 'abstracts';
    let allData = isClient ? allClientAbstracts : allAbstracts;

    const abIndex = allData.findIndex(i => i.id === window.currentViewingAbstractId);
    if (abIndex === -1) return;

    const ab = allData[abIndex];
    if (!ab.comments) ab.comments = [];

    const commentObj = { user: currentUser.username, text: text, date: new Date().toISOString() };
    ab.comments.push(commentObj);

    const mentions = text.match(/@([\w\u0600-\u06FF]+)/g);
    if (mentions) {
      for (let m of mentions) {
        const username = m.substring(1);
        const mentionedUser = currentUsers.find(u => (u && u.username) === username);
        if (mentionedUser) {
          let notifs = await window.DB.getAll('notifications') || [];
          notifs.push({
            id: Date.now().toString() + Math.random().toString(36).substring(2),
            user: mentionedUser.username,
            text: `تم عمل منشن لك في مستخلص رقم ${ab.doc_no}`,
            link: `#`,
            date: new Date().toISOString(),
            read: false
          });
          await window.DB.put('notifications', notifs);
        }
      }
    }

    await window.DB.put(dbTable, ab);
    input.value = '';
    window.renderAbstractComments(type, ab);

    const allNotifications = ((await window.DB.getAll('notifications')) || []).filter(Boolean);
    const myNotifs = allNotifications.filter(n => n.user === currentUser.username && !n.read);
    if (window.renderNotifications) renderNotifications(myNotifs);
  } catch (e) {
    alert("حدث خطأ أثناء إضافة التعليق: " + e.message);
  }
};

window.renderClientAbstracts = async function () {
  currentClientAbstracts = ((await window.DB.getAll('client_abstracts')) || []).filter(Boolean);
  const tbody = document.getElementById('client-abstracts-tbody');
  if (!tbody) return;
  tbody.innerHTML = '';
  const search = document.getElementById('client-abstract-search').value.toLowerCase();
  const statusFilter = document.getElementById('client-abstract-status-filter').value;

  let filtered = currentClientAbstracts.filter(ab => {
    const pName = (currentProjects.find(p => p.id == ab.project_id) || {}).name || '';
    const matchSearch = ab.client_name.toLowerCase().includes(search) ||
      pName.toLowerCase().includes(search) ||
      (ab.abstract_number && ab.abstract_number.toLowerCase().includes(search));
    const matchStatus = statusFilter === 'all' || ab.status === statusFilter;
    return matchSearch && matchStatus;
  });

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

  (filtered || []).forEach(ab => {
    const tr = document.createElement('tr');
    const pName = (currentProjects.find(p => p.id == ab.project_id) || {}).name || '';

    let paid = 0;
    const linkedVouchers = allInvoices.filter(j => j.type === 'receipt' && j.status === 'posted' && j.linked_invoice_id === 'cab-' + ab.id);
    (linkedVouchers || []).forEach(v => {
      paid += parseFloat(v.amount) || 0;
    });

    let actions = `
      <button class="action-btn btn-view" onclick="printClientAbstract(${ab.id})">عرض</button>
      ${ab.status === 'draft' ? `<button class="action-btn" style="background:var(--success); color:#fff; border:none;" onclick="approveClientAbstract(${ab.id})">اعتماد</button>` : ''}
      ${ab.status === 'approved' ? `<button class="action-btn" style="background:var(--success); color:#fff; border:none;" onclick="payClientAbstract(${ab.id})">سند قبض</button>` : ''}
      ${ab.status === 'draft' ? `<button class="action-btn btn-edit" onclick="openClientAbstractModal(${ab.id})">تعديل</button>` : ''}
      ${ab.status === 'draft' ? `<button class="action-btn btn-danger" onclick="deleteClientAbstract(${ab.id})">حذف</button>` : ''}
    `;

    let remaining = Math.max(0, (parseFloat(ab.net_value) || 0) - paid);

    tr.innerHTML = `
      <td>${ab.abstract_number || ('#' + ab.id)}</td>
      <td>${new Date(ab.date).toLocaleDateString('ar-EG')}</td>
      <td>${pName}</td>
      <td>${ab.client_name || ''}</td>
      <td style="font-weight:bold; color:var(--success);">${(parseFloat(ab.net_value) || 0).toLocaleString('en-US')} ج.م</td>
      <td style="color:var(--primary); font-weight:bold;">${paid.toLocaleString('en-US')} ج.م</td>
      <td style="color:var(--danger); font-weight:bold;">${remaining.toLocaleString('en-US')} ج.م</td>
      <td><span class="status-badge ${ab.status === 'approved' ? 'status-posted' : 'status-draft'}">${ab.status === 'approved' ? 'معتمد' : 'مسودة'}</span></td>
      <td>${actions}</td>
    `;
    tbody.appendChild(tr);
  });
};

window.openClientAbstractModal = function (id = null) {
  window.currentViewingAbstractId = id;
  document.getElementById('client-abstract-modal-title').innerText = id ? 'تعديل مستخلص عميل #' + id : 'مستخلص عميل جديد';
  document.getElementById('edit-client-abstract-id').value = id || '';

  if(projSelect) projSelect.onchange = window.onClientAbstractProjectChange;
  pSel.innerHTML = '<option value="">اختر المشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');

  if (id) {
    const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
    if (ab) {
      pSel.value = ab.project_id;
      document.getElementById('client-abstract-date').value = ab.date;
      document.getElementById('client-abstract-name').value = ab.client_name || '';
      document.getElementById('client-abstract-notes').value = ab.notes || '';
      document.getElementById('client-abstract-previous-value').value = ab.previous_value || 0;
      document.getElementById('client-abstract-current-value').value = ab.current_value || 0;
      document.getElementById('client-abstract-total-value').value = ab.total_value || 0;
      document.getElementById('client-abstract-deduction-percent').value = ab.deduction_percent || 0;
      document.getElementById('client-abstract-retention-percent').value = ab.retention_percent || 0;
      if (window.renderAbstractComments) window.renderAbstractComments('client-abstract', ab);
    }
  } else {
    const form = document.getElementById('client-abstract-form'); if (form) form.reset();
    document.getElementById('client-abstract-date').value = new Date().toISOString().split('T')[0];
    const nextId = (currentClientAbstracts.length > 0 ? Math.max(...currentClientAbstracts.map(a => a.id)) : 0) + 1;
    document.getElementById('client-abstract-number').value = 'CAB-' + nextId;
    if (window.renderAbstractComments) window.renderAbstractComments('client-abstract', { id: null });
  }

  showModal('client-abstract-modal');
};

window.deleteClientAbstract = async function (id) {
  if (confirm('هل أنت متأكد من حذف هذا المستخلص؟')) {
    await window.DB.remove('client_abstracts', id);
    if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
  }
};

window.approveClientAbstract = async function (id) {
  if (confirm('هل أنت متأكد من اعتماد هذا المستخلص؟')) {
    const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
    if (ab) {
      ab.status = 'approved';
      await window.DB.update('client_abstracts', ab);
      if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
      alert('تم الاعتماد بنجاح.');
    }
  }
};

window.payClientAbstract = function (id) {
  const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
  if (ab) {
    document.getElementById('receipt-linked-invoice').value = 'cab-' + ab.id;
    document.getElementById('receipt-amount').value = ab.net_value;
    const proj = currentProjects.find(p => p.id === parseInt(ab.project_id));
    if (proj && proj.client_name) {
      document.getElementById('receipt-party-name').value = proj.client_name;
    } else {
      document.getElementById('receipt-party-name').value = ab.client_name || '';
    }
    showModal('receipt-modal');
  }
};


// ==========================================
// PETTY CASH SETTLEMENTS LOGIC
// ==========================================

async function compressImageAndConvertToBase64(file) {
  return new Promise((resolve, reject) => {
    if (!file.type.startsWith('image/')) {
      // If it's a PDF or something else, just convert to base64 directly (no compression)
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
      return;
    }

    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = event => {
      const img = new Image();
      img.src = event.target.result;
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const MAX_WIDTH = 1000;
        const MAX_HEIGHT = 1000;
        let width = img.width;
        let height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }

        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, width, height);
        // Compress to 0.7 quality JPEG
        resolve(canvas.toDataURL('image/jpeg', 0.7));
      };
    };
    reader.onerror = error => reject(error);
  });
}

window.renderSettlements = function () {
  const search = document.getElementById('settlement-search')?.value.toLowerCase() || '';
  const statusFilter = document.getElementById('settlement-status-filter')?.value || 'all';
  const tbody = document.getElementById('settlements-tbody');
  if (!tbody) return;

  tbody.innerHTML = '';

  let settlements = allInvoices.filter(t => t.type === 'petty_cash_settlement');
  settlements.sort((a, b) => new Date(b.date) - new Date(a.date));

  settlements.forEach(s => {
    if (statusFilter !== 'all' && s.status !== statusFilter) return;

    let custodyName = 'غير محدد';
    if (s.custody_account_id) {
      const acc = currentAccounts.find(a => a.id === s.custody_account_id);
      if (acc) custodyName = acc.name;
    }

    if (search && !s.id.toString().includes(search) && !custodyName.toLowerCase().includes(search)) return;

    let actions = '';
    if (s.status === 'pending') {
      const canApprove = currentUser.role === 'مدير عام' || (currentUser.permissions && currentUser.permissions.includes('approve_settlements'));
      if (canApprove) {
        actions += `<button class="btn btn-sm" style="background:var(--success); color:white;" onclick="approveSettlement(${s.id})">✅ اعتماد</button> `;
      }
      actions += `<button class="btn btn-sm btn-primary" onclick="openSettlementModal(${s.id})">✏️ تعديل</button> `;
      actions += `<button class="btn btn-sm btn-danger" onclick="deleteSettlement(${s.id})">🗑️ حذف</button>`;
    } else {
      actions += `<button class="btn btn-sm btn-secondary" onclick="viewSettlement(${s.id})">👁️ عرض</button>`;
      const canDelete = currentUser.role === 'مدير عام' || (currentUser.permissions && currentUser.permissions.includes('approve_settlements'));
      if (canDelete) {
        actions += ` <button class="btn btn-sm btn-danger" onclick="deleteSettlement(${s.id})">🗑️ حذف بالقيود والأطراف</button>`;
      }
    }

    const total = s.items ? s.items.reduce((sum, it) => sum + ((parseFloat(it.qty) || 0) * (parseFloat(it.price) || 0)), 0) : 0;
    const statusHtml = s.status === 'posted' ? '<span class="badge" style="background:var(--success)">معتمدة</span>' : '<span class="badge" style="background:var(--warning)">معلقة</span>';

    tbody.innerHTML += `
            <tr>
                <td>${new Date(s.date).toLocaleString('ar-EG')}</td>
                <td>#${s.id}</td>
                <td>${custodyName}</td>
                <td>${total.toLocaleString('ar-EG', { minimumFractionDigits: 2 })} ج.م</td>
                <td>${statusHtml}</td>
                <td>${actions}</td>
            </tr>
        `;
  });
}

window.openSettlementModal = function (id = null) {
  document.getElementById('settlement-items-tbody').innerHTML = '';
  const custodySelect = document.getElementById('settlement-custody');
  custodySelect.innerHTML = '';

  // Populate custody accounts
  const custodyAccounts = currentAccounts.filter(a => a.name.includes('عهدة'));
  custodyAccounts.forEach(a => {
    custodySelect.innerHTML += `<option value="${a.id}">${a.name}</option>`;
  });

  if (id) {
    const s = allInvoices.find(i => String(i.id) === String(id));
    document.getElementById('settlement-modal-title').innerText = 'تعديل تسوية عهدة #' + s.id;
    document.getElementById('settlement-modal').dataset.editId = s.id;
    document.getElementById('settlement-date').value = s.date.substring(0, 16);
    custodySelect.value = s.custody_account_id;

    s.items.forEach(it => addSettlementRow(it));
  } else {
    document.getElementById('settlement-modal-title').innerText = 'تسوية عهدة جديدة';
    if (document.getElementById('settlement-related-links')) document.getElementById('settlement-related-links').style.display = 'none';
    delete document.getElementById('settlement-modal').dataset.editId;

    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    document.getElementById('settlement-date').value = now.toISOString().slice(0, 16);

    // Auto select current user's custody
    if (currentUser && currentUser.custody_account_id) {
      custodySelect.value = currentUser.custody_account_id;
    }

    addSettlementRow();
  }

  updateSettlementTotal();
  showModal('settlement-modal');
}

window.addSettlementRow = function (lineData = null) {
  const tbody = document.getElementById('settlement-items-tbody');
  const rowId = 'set-row-' + Date.now() + Math.floor(Math.random() * 1000);

  const tr = document.createElement('tr');
  tr.id = rowId;

  let whOptions = '<option value="">-- المخزن --</option>';
  currentWarehouses.forEach(w => whOptions += `<option value="${w.id}">${w.name}</option>`);

  let projOptions = '<option value="">-- بدون مركز تكلفة --</option>';
  currentProjects.forEach(p => projOptions += `<option value="${p.id}">${p.name}</option>`);

  let batchOptions = '<option value="">-- أمر الصب (اختياري) --</option>';
  if (typeof allConcreteInvoices !== 'undefined') {
      allConcreteInvoices.forEach(inv => {
          batchOptions += `<option value="${inv.id}">أمر #${inv.id} - ${inv.target_name || ''}</option>`;
      });
  }

  const attachmentUrl = lineData && lineData.attachment ? lineData.attachment : '';
  const attachmentBtnHtml = attachmentUrl ?
    `<a href="${attachmentUrl}" target="_blank" class="btn btn-sm btn-secondary" style="margin-bottom:5px; display:block;">👁️ عرض الفاتورة</a>
         <button class="btn btn-sm btn-danger" onclick="this.parentElement.querySelector('input').style.display='block'; this.parentElement.dataset.attachment=''; this.style.display='none'; this.previousElementSibling.style.display='none';">تغيير</button>
         <input type="file" accept="image/*,.pdf" style="display:none; max-width: 110px;" onchange="handleSettlementAttachment(this, '${rowId}')">`
    : `<input type="file" accept="image/*,.pdf" style="max-width: 110px;" onchange="handleSettlementAttachment(this, '${rowId}')">`;

  tr.innerHTML = `
        <td>
            <select class="set-type" onchange="updateSettlementRowOptions('${rowId}')">
                <option value="expense" ${lineData && lineData.item_type === 'expense' ? 'selected' : ''}>مصروف</option>
                <option value="inventory" ${lineData && lineData.item_type === 'inventory' ? 'selected' : ''}>مخزون</option>
            </select>
        </td>
        <td class="set-item-td">
            <!-- Populated dynamically -->
        </td>
        <td>
            <select class="set-warehouse">${whOptions}</select>
        </td>
        <td>
            <select class="set-project">${projOptions}</select>
        </td>
        <td>
            <select class="set-batch" style="min-width:100px;">${batchOptions}</select>
        </td>
        <td><input type="number" step="0.01" class="set-qty" value="${lineData ? lineData.qty : 1}" oninput="updateSettlementTotal()"></td>
        <td><input type="number" step="0.01" class="set-price" value="${lineData ? lineData.price : ''}" oninput="updateSettlementTotal()"></td>
        <td class="set-line-total">0</td>
        <td class="set-attachment-td" data-attachment="${attachmentUrl}">
            ${attachmentBtnHtml}
        </td>
        <td><button class="btn btn-danger btn-sm" onclick="this.closest('tr').remove(); updateSettlementTotal();">X</button></td>
    `;

  tbody.appendChild(tr);

  // Set values
  if (lineData) {
    tr.querySelector('.set-warehouse').value = lineData.warehouse_id || '';
    tr.querySelector('.set-project').value = lineData.project_id || '';
    if(tr.querySelector('.set-batch')) tr.querySelector('.set-batch').value = lineData.concrete_order_id || lineData.batch_id || '';
  }

  updateSettlementRowOptions(rowId, lineData);
  updateSettlementTotal();
}

window.updateSettlementRowOptions = function (rowId, lineData = null) {
  const tr = document.getElementById(rowId);
  if (!tr) return;
  const type = tr.querySelector('.set-type').value;
  const td = tr.querySelector('.set-item-td');
  const whSelect = tr.querySelector('.set-warehouse');

  if (type === 'inventory') {
    whSelect.style.display = 'block';
    
    const uniqueTags = [...new Set(currentItems.map(i => i.tag).filter(t => t && t.trim() !== ''))];
    let tagOpts = '<option value="">-- كل التاجات --</option>';
    uniqueTags.forEach(t => tagOpts += `<option value="${t}">${t}</option>`);
    
    let itemOpts = '<option value="">-- اختر الصنف --</option>';
    currentItems.forEach(i => itemOpts += `<option value="${i.id}">${i.name}</option>`);
    
    td.innerHTML = `
        <select class="set-item-tag" style="width:100%; margin-bottom:5px; font-size: 0.9em; padding: 2px;" onchange="filterSettlementItems(this)">
            ${tagOpts}
        </select>
        <select class="set-item-id" style="width:100%;">
            ${itemOpts}
        </select>
    `;
    
    if (lineData && lineData.item_id) {
      const item = currentItems.find(i => String(i.id) === String(lineData.item_id));
      if (item && item.tag) {
          td.querySelector('.set-item-tag').value = item.tag;
          const filtered = currentItems.filter(i => i.tag === item.tag);
          let filteredOpts = '<option value="">-- اختر الصنف --</option>';
          filtered.forEach(i => filteredOpts += `<option value="${i.id}">${i.name}</option>`);
          td.querySelector('.set-item-id').innerHTML = filteredOpts;
      }
      td.querySelector('.set-item-id').value = lineData.item_id;
    }
  } else {
    whSelect.style.display = 'none';
    whSelect.value = '';

    // For expense, we use an input text with a datalist of existing expense accounts
    const listId = 'exp-list-' + rowId;
    let dlOptions = '';
    const expParent = currentAccounts.find(a => a.name === 'المصروفات');
    if (expParent) {
      const expAccounts = currentAccounts.filter(a => a.parent_id === expParent.id);
      expAccounts.forEach(a => dlOptions += `<option value="${a.name}">`);
    }

    td.innerHTML = `
            <input type="text" class="set-expense-name" placeholder="اسم المصروف..." list="${listId}" value="${lineData && lineData.expense_name ? lineData.expense_name : ''}">
            <datalist id="${listId}">${dlOptions}</datalist>
        `;
  }
}

window.handleSettlementAttachment = async function (input, rowId) {
  if (!input.files || input.files.length === 0) return;
  const file = input.files[0];
  const td = document.getElementById(rowId).querySelector('.set-attachment-td');

  try {
    td.style.opacity = '0.5'; // loading state
    const base64 = await compressImageAndConvertToBase64(file);
    td.dataset.attachment = base64;
    td.style.opacity = '1';
    alert('تم إرفاق الفاتورة بنجاح!');
  } catch (e) {
    td.style.opacity = '1';
    alert('خطأ في قراءة الملف: ' + e.message);
  }
}

window.updateSettlementTotal = function () {
  let grandTotal = 0;
  document.querySelectorAll('#settlement-items-tbody tr').forEach(tr => {
    const qty = parseFloat(tr.querySelector('.set-qty').value) || 0;
    const price = parseFloat(tr.querySelector('.set-price').value) || 0;
    const total = qty * price;
    tr.querySelector('.set-line-total').innerText = total.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
    grandTotal += total;
  });
  document.getElementById('settlement-total-amount').innerText = grandTotal.toLocaleString('ar-EG', { minimumFractionDigits: 2 });
}

window.filterSettlementItems = function(tagSelect) {
    const selectedTag = tagSelect.value;
    const itemSelect = tagSelect.parentElement.querySelector('.set-item-id');
    const currentVal = itemSelect.value;
    
    let itemOpts = '<option value="">-- اختر الصنف --</option>';
    const filtered = selectedTag ? currentItems.filter(i => i.tag === selectedTag) : currentItems;
    filtered.forEach(i => itemOpts += `<option value="${i.id}">${i.name}</option>`);
    
    itemSelect.innerHTML = itemOpts;
    if(filtered.some(i => String(i.id) === String(currentVal))) {
        itemSelect.value = currentVal;
    }
}

window.saveSettlement = async function () {
  const custodyId = document.getElementById('settlement-custody').value;
  const date = document.getElementById('settlement-date').value;

  if (!custodyId || !date) return alert("يرجى إكمال البيانات الأساسية.");

  const items = [];
  let hasError = false;

  document.querySelectorAll('#settlement-items-tbody tr').forEach(tr => {
    const type = tr.querySelector('.set-type').value;
    const whId = tr.querySelector('.set-warehouse').value;
    const projId = tr.querySelector('.set-project').value;
    const batchId = tr.querySelector('.set-batch') ? tr.querySelector('.set-batch').value : '';
    const qty = parseFloat(tr.querySelector('.set-qty').value) || 0;
    const price = parseFloat(tr.querySelector('.set-price').value) || 0;
    const attachment = tr.querySelector('.set-attachment-td').dataset.attachment || '';

    if (qty <= 0 || price <= 0) { alert("يجب إدخال كمية وسعر صحيحين."); hasError = true; return; }

    const line = {
      item_type: type,
      warehouse_id: whId ? parseInt(whId) : null,
      project_id: projId ? parseInt(projId) : null,
      batch_id: batchId ? parseInt(batchId) : null,
      qty: qty,
      price: price,
      attachment: attachment
    };

    if (type === 'inventory') {
      const itemId = tr.querySelector('.set-item-id').value;
      if (!itemId) { alert("يرجى اختيار الصنف."); hasError = true; return; }
      if (!whId) { alert("يرجى اختيار المخزن لبنود المخزون."); hasError = true; return; }
      line.item_id = parseInt(itemId);
      line.item_name = currentItems.find(i => i.id === line.item_id)?.name || '';
    } else {
      const expName = tr.querySelector('.set-expense-name').value.trim();
      if (!expName) { alert("يرجى إدخال اسم المصروف."); hasError = true; return; }
      line.expense_name = expName;
    }

    items.push(line);
  });

  if (hasError) return;
  if (items.length === 0) return alert("يرجى إضافة بند واحد على الأقل.");

  const isEditId = document.getElementById('settlement-modal').dataset.editId;

  const settlement = {
    type: 'petty_cash_settlement',
    date: date,
    user: currentUser.username,
    custody_account_id: parseInt(custodyId),
    status: 'pending',
    items: items
  };

  try {
    let savedId = isEditId ? parseInt(isEditId) : null;
    if (savedId) {
      settlement.id = savedId;
      await window.DB.update('transactions', settlement);
    } else {
      savedId = await window.DB.add('transactions', settlement);
    }
    closeModal('settlement-modal');
    await loadData();
    if (typeof renderSettlements === 'function') renderSettlements();

    // Auto approve
    if (savedId && typeof window.approveSettlement === 'function') {
      await window.approveSettlement(savedId, true);
    }
  } catch (e) {
    alert("خطأ: " + e.message);
  }
}

window.ensureExpenseAccountExists = async function (expenseName) {
  // Check if account already exists
  let expParent = currentAccounts.find(a => a.name === 'المصروفات' || a.name.includes('المصروفات') || (a.code === '5' && a.parent_id === null));
  if (!expParent) return null; // Should never happen based on loadData

  // Find exact match
  let acc = currentAccounts.find(a => a.name === expenseName && a.parent_id === expParent.id);
  if (acc) return acc.id;

  // Not found? Create it!
  const childCount = currentAccounts.filter(a => a.parent_id === expParent.id).length;
  let newCode = expParent.code + (childCount + 1).toString().padStart(2, '0');

  // Ensure code uniqueness just in case
  while (currentAccounts.find(a => a.code === newCode)) {
    newCode = newCode + '1';
  }

  const newAccId = await window.DB.add('accounts', {
    code: newCode,
    name: expenseName,
    type: 'مصروفات',
    parent_id: expParent.id
  });

  // Refresh accounts list
  currentAccounts = await window.DB.getAll('accounts');
  return newAccId;
}

window.approveSettlement = async function (id, skipConfirm = false) {
  if (!skipConfirm && !confirm('هل أنت متأكد من اعتماد هذه التسوية؟ للمصروفات سيتم عمل قيد، وللمخزون سيتم إرساله لاعتماد أمين المخزن.')) return;

  const s = allInvoices.find(i => String(i.id) === String(id));
  if (!s || s.status !== 'pending') return;

  try {
    let expensesTotal = 0;
    const journalLines = [];
    const inventoryByWarehouse = {};

    // Loop over items and separate logic
    for (let it of s.items) {
      const lineTotal = it.qty * it.price;

      if (it.item_type === 'expense') {
        expensesTotal += lineTotal;
        const expAccId = await ensureExpenseAccountExists(it.expense_name);
        journalLines.push({ account_id: expAccId, debit: lineTotal, credit: 0, notes: 'تسوية مصروفات لعهدة رقم ' + s.id, project_id: it.project_id });
      } else if (it.item_type === 'inventory') {
        const whId = it.warehouse_id || s.warehouse_id;
        if (!inventoryByWarehouse[whId]) inventoryByWarehouse[whId] = [];
        inventoryByWarehouse[whId].push(it);
      }
    }

    // If there are expenses, create a direct Journal Entry
    if (expensesTotal > 0 && journalLines.length > 0) {
      journalLines.push({ account_id: s.custody_account_id, debit: 0, credit: expensesTotal, notes: 'منصرف تسوية عهدة رقم ' + s.id });
      const je = {
        date: s.date && s.date.includes('T') ? s.date.split('T')[0] : s.date,
        reference: 'تسوية عهدة #' + s.id,
        desc: 'اعتماد مصروفات تسوية عهدة رقم ' + s.id,
        rows: journalLines,
        total: expensesTotal,
        status: 'posted',
        created_by: currentUser.username,
        user: currentUser.username,
        type: 'settlement',
        ref_id: s.id
      };
      await window.DB.add('journal_entries', je);
    }

    // For inventory items, create "purchases" invoices pending storekeeper approval
    for (let whId in inventoryByWarehouse) {
      const items = inventoryByWarehouse[whId];
      let invTotal = 0;
      items.forEach(it => invTotal += (it.qty * it.price));

      const whName = currentWarehouses.find(w => String(w.id) === String(whId))?.name || '';
      const custodyName = currentAccounts.find(a => a.id == s.custody_account_id)?.name || 'العهدة';

      const newInv = {
        type: 'purchases',
        date: new Date().toISOString(),
        user: currentUser.username,
        contact_name: custodyName, // Show custody as supplier visually
        to_warehouse_id: parseInt(whId),
        to_warehouse_name: whName,
        status: 'pending_store',
        is_from_settlement: true,
        custody_account_id: s.custody_account_id,
        settlement_ref: s.id,
        total: invTotal,
        total_amount: invTotal,
        items: items,
        notes: 'تلقائي من تسوية عهدة رقم ' + s.id
      };

      const newInvId = await window.DB.add('transactions', newInv);
      if (typeof window.sendInvoiceToStore === 'function') {
        await window.sendInvoiceToStore(newInvId);
      }
    }

    // Update settlement status
    s.status = 'posted';
    await window.DB.update('transactions', s);

    alert('تم اعتماد التسوية! تم توليد قيود المصروفات وإرسال بنود المخزون لأمين المخزن.');
    await loadData();
    if (typeof renderSettlements === 'function') renderSettlements();

  } catch (e) {
    alert("خطأ أثناء الاعتماد: " + e.message);
  }
}

window.deleteSettlement = async function (id) {
  if (!confirm("تحذير خطير: هل أنت متأكد من حذف هذه التسوية وجميع القيود المحاسبية وأذون التوريد المرتبطة بها نهائياً؟")) return;

  try {
    const s = allInvoices.find(i => String(i.id) === String(id));
    if (!s) {
      // Fallback if not found in memory
      // Delete linked vouchers
      try {
        const allTransactions = await window.DB.getAll('transactions');
        const linkedVouchers = allTransactions.filter(t => t.linked_invoice_id == id);
        for (let v of linkedVouchers) {
          // Also delete journal entries for these vouchers
          const vJournals = allJ.filter(j => j.reference && j.reference.includes(`${v.id}`));
          for (let j of vJournals) {
            await window.DB.remove('journal_entries', j.id);
          }
          // DELETE STORE JOURNAL IF EXISTS
        const _jrnls3 = await window.DB.getAll('journal_entries') || [];
        const _sJrnls3 = _jrnls3.filter(j => j.source_type === 'store_out' && String(j.source_id) === String(v.id));
        for(let _j3 of _sJrnls3) await window.DB.remove('journal_entries', _j3.id);
        
        await window.DB.remove('transactions', v.id);
        }
      } catch (e) { console.error("Failed to delete linked vouchers", e); }

      // DELETE STORE JOURNAL IF EXISTS
        const _jrnls = await window.DB.getAll('journal_entries') || [];
        const _sJrnls = _jrnls.filter(j => j.source_type === 'store_out' && String(j.source_id) === String(id));
        for(let _j of _sJrnls) await window.DB.remove('journal_entries', _j.id);
        
        await window.DB.remove('transactions', id);
    } else {
      // 1. Delete Journal Entries related to expenses
      const relatedJournals = currentJournals.filter(j => j.type === 'settlement' && j.ref_id === id);
      for (let j of relatedJournals) {
        await window.DB.remove('journal_entries', j.id);
      }

      // 2. Find and Delete any generated inventory invoices (purchases type)
      const dbInvs = await window.DB.getAll('transactions');
      const generatedInvoices = dbInvs.filter(inv => inv.is_from_settlement === true && inv.settlement_ref === id);
      for (let inv of generatedInvoices) {
        // Delete the generated invoice itself
        // DELETE STORE JOURNAL IF EXISTS
        const _jrnls2 = await window.DB.getAll('journal_entries') || [];
        const _sJrnls2 = _jrnls2.filter(j => j.source_type === 'store_out' && String(j.source_id) === String(inv.id));
        for(let _j2 of _sJrnls2) await window.DB.remove('journal_entries', _j2.id);
        
        await window.DB.remove('transactions', inv.id);

        // Delete the journal entry generated by the storekeeper if they already approved it
        const allJournals = await window.DB.getAll('journal_entries');
        const invJournal = allJournals.find(j => j.reference === `فاتورة مشتريات #${inv.id}`);
        if (invJournal) {
          await window.DB.remove('journal_entries', invJournal.id);
        }
      }

      // 3. Delete the settlement itself
      // Delete linked vouchers
      try {
        const allTransactions = await window.DB.getAll('transactions');
        const linkedVouchers = allTransactions.filter(t => t.linked_invoice_id == id);
        for (let v of linkedVouchers) {
          // Also delete journal entries for these vouchers
          const vJournals = allJ.filter(j => j.reference && j.reference.includes(`${v.id}`));
          for (let j of vJournals) {
            await window.DB.remove('journal_entries', j.id);
          }
          // DELETE STORE JOURNAL IF EXISTS
        const _jrnls3 = await window.DB.getAll('journal_entries') || [];
        const _sJrnls3 = _jrnls3.filter(j => j.source_type === 'store_out' && String(j.source_id) === String(v.id));
        for(let _j3 of _sJrnls3) await window.DB.remove('journal_entries', _j3.id);
        
        await window.DB.remove('transactions', v.id);
        }
      } catch (e) { console.error("Failed to delete linked vouchers", e); }

      // DELETE STORE JOURNAL IF EXISTS
        const _jrnls = await window.DB.getAll('journal_entries') || [];
        const _sJrnls = _jrnls.filter(j => j.source_type === 'store_out' && String(j.source_id) === String(id));
        for(let _j of _sJrnls) await window.DB.remove('journal_entries', _j.id);
        
        await window.DB.remove('transactions', id);
    }

    await loadData();
    if (typeof renderSettlements === 'function') renderSettlements();
    alert("تم حذف التسوية وحذف كل التوجيهات المحاسبية والمخزنية التابعة لها بنجاح.");
  } catch (e) {
    alert("حدث خطأ أثناء الحذف: " + e.message);
  }
}

window.viewSettlement = function (id) {
  // Reuses the modal but read-only
  openSettlementModal(id);
  document.getElementById('settlement-modal-title').innerText = 'عرض تسوية عهدة #' + id;
  if (typeof renderRelatedLinks === 'function') renderRelatedLinks('settlement', id, 'settlement-related-links');

  const modal = document.getElementById('settlement-modal');
  modal.querySelectorAll('input, select, button').forEach(el => {
    if (!el.classList.contains('close') && el.innerText !== 'إلغاء' && el.innerText !== '👁️ عرض الفاتورة') {
      if (el.tagName === 'BUTTON') el.style.display = 'none';
      else el.disabled = true;
    }
  });
}

// --- CONTACT STATEMENT (SUB-LEDGER) ---
window.currentStatementContactId = null;

window.openContactStatement = function (contactId) {
  window.currentStatementAccountId = null;

  window.currentStatementContactId = contactId;
  const c = currentContacts.find(x => String(x.id) === String(contactId));
  if (!c) return;
  document.getElementById('statement-header-info').innerText = `كشف حساب: ${c.name} (${c.type})`;
  document.getElementById('statement-date-from').value = '';
  document.getElementById('statement-date-to').value = '';
  window.refreshContactStatement();
  showModal('contact-statement-modal');
}

window.refreshContactStatement = function () {
  const contactId = window.currentStatementContactId;
  const c = currentContacts.find(x => String(x.id) === String(contactId));
  if (!c) return;

  const filterFrom = document.getElementById('statement-date-from').value;
  const filterTo = document.getElementById('statement-date-to').value;

  const tbody = document.getElementById('statement-tbody');
  tbody.innerHTML = '';

  let records = [];


  // Gather Client Abstracts
  if (typeof currentClientAbstracts !== 'undefined') {
      currentClientAbstracts.forEach(ab => {
          if (ab.status === 'approved' && ab.client_name) {
             const proj = (typeof currentProjects !== 'undefined') ? currentProjects.find(p => String(p.id) === String(ab.project_id)) : null;
             const isMatch = (proj && String(proj.client) === c.name) || String(ab.client_name) === c.name || (proj && String(proj.contact_id) === String(contactId));
             if (isMatch) {
                 const gross = parseFloat(ab.gross_value) || 0;
                 const net = parseFloat(ab.net_value) || 0;
                 const tax = parseFloat(ab.tax_value) || 0;
                 const ret = parseFloat(ab.retention_value) || 0;
                 const advance = parseFloat(ab.advance_payment) || 0;
                 const otherDed = parseFloat(ab.other_deductions) || 0;
                 
                                  if(tax > 0) records.push({ date: ab.date, type: 'استقطاع ضرائب', ref: '#' + ab.id, notes: 'ضرائب مستخلص إيراد', debit: 0, credit: tax });
                 if(ret > 0) records.push({ date: ab.date, type: 'استقطاع ضمان أعمال', ref: '#' + ab.id, notes: 'ضمان أعمال مستخلص إيراد', debit: 0, credit: ret });
                 if(advance > 0) records.push({ date: ab.date, type: 'استنزاف دفعة مقدمة', ref: '#' + ab.id, notes: 'خصم دفعات مقدمة من المستخلص', debit: 0, credit: advance });
                 if(otherDed > 0) records.push({ date: ab.date, type: 'استقطاعات أخرى', ref: '#' + ab.id, notes: 'استقطاعات متنوعة', debit: 0, credit: otherDed });
                 
                 // The balance change is now exactly Net Amount!
             }
          }
      });
  }

  // Gather Subcontract Abstracts
  if (typeof currentSubcontractAbstracts !== 'undefined') {
      currentSubcontractAbstracts.forEach(ab => {
          if (ab.status === 'approved') {
              const cont = (typeof currentSubcontracts !== 'undefined') ? currentSubcontracts.find(c => String(c.id) === String(ab.contract_id)) : null;
              if (cont && String(cont.subcontractor_id) === String(contactId)) {
                 const gross = parseFloat(ab.gross_value) || 0;
                 const net = parseFloat(ab.net_value) || 0;
                 const ret = parseFloat(ab.retention_value) || 0;
                 const tax = parseFloat(ab.tax_value) || 0;
                 const advance = parseFloat(ab.advance_payment) || 0;
                 const otherDed = parseFloat(ab.other_deductions) || 0;
                 
                 // 1. Gross Credit (We owe them)
                 records.push({ date: ab.date, type: 'مستخلص مقاول باطن رقم ' + (ab.abstract_number||ab.id), ref: '#' + ab.id, notes: 'إجمالي مستخلص مقاول الباطن', debit: 0, credit: gross });
                 
                 // 2. Deductions (Debits reducing our debt to them)
                 if(tax > 0) records.push({ date: ab.date, type: 'خصم ضرائب', ref: '#' + ab.id, notes: 'ضرائب مخصومة من المستخلص', debit: tax, credit: 0 });
                 if(ret > 0) records.push({ date: ab.date, type: 'خصم تأمينات/ضمان', ref: '#' + ab.id, notes: 'ضمان أعمال مخصوم من المستخلص', debit: ret, credit: 0 });
                 if(advance > 0) records.push({ date: ab.date, type: 'خصم دفعة مقدمة', ref: '#' + ab.id, notes: 'دفعة مقدمة مخصومة', debit: advance, credit: 0 });
                 if(otherDed > 0) records.push({ date: ab.date, type: 'استقطاعات أخرى', ref: '#' + ab.id, notes: 'استقطاعات متنوعة', debit: otherDed, credit: 0 });
              }
          }
      });
  }

  // Gather Invoices + Vouchers من allInvoices (كل شيء في جدول transactions)
  allInvoices.forEach(inv => {
    // String comparison عشان contact_id ممكن يكون int أو string
    if (String(inv.contact_id) !== String(contactId)) return;
    if (inv.status !== 'posted') return;

    let typeStr = '';
    let debit = 0;
    let credit = 0;
    const total = parseFloat(inv.amount) ||
                  (inv.items || []).reduce((s, it) => s + (parseFloat(it.price) || 0) * (parseFloat(it.qty) || 0), 0);

    if      (inv.type === 'sales')            { typeStr = 'فاتورة مبيعات';      debit  = total; }
    else if (inv.type === 'purchases')        { typeStr = 'فاتورة مشتريات';     credit = total; }
    else if (inv.type === 'sales_return')     { typeStr = 'مرتجع مبيعات';       credit = total; }
    else if (inv.type === 'purchases_return') { typeStr = 'مرتجع مشتريات';      debit  = total; }
    else if (inv.type === 'receipt')          { typeStr = 'سند قبض';            credit = parseFloat(inv.amount) || 0; }
    else if (inv.type === 'payment')          { typeStr = 'سند دفع';            debit  = parseFloat(inv.amount) || 0; }
    else return;

    if (debit === 0 && credit === 0) return;

    records.push({
      date: inv.date,
      type: typeStr,
      ref: (inv.doc_no ? inv.doc_no + ' ' : '') + '#' + inv.id,
      notes: inv.notes || '',
      debit,
      credit
    });
  });

  // Filter by date
  if (filterFrom) {
    const fromDate = new Date(filterFrom); fromDate.setHours(0, 0, 0, 0);
    records = records.filter(r => new Date(r.date) >= fromDate);
  }
  if (filterTo) {
    const toDate = new Date(filterTo); toDate.setHours(23, 59, 59, 999);
    records = records.filter(r => new Date(r.date) <= toDate);
  }

  // Sort chronologically
  records.sort((a, b) => new Date(a.date) - new Date(b.date));

  let runningBalance = 0;
  let totalDebit = 0;
  let totalCredit = 0;

  records.forEach(r => {
    totalDebit += r.debit;
    totalCredit += r.credit;
    runningBalance += (r.debit - r.credit);

    let balStr = Math.abs(runningBalance).toLocaleString('en-US');
    if (runningBalance > 0) balStr += ' مدين';
    else if (runningBalance < 0) balStr += ' دائن';

    r.balStr = balStr;
  });

  window.currentStatementRecords = records;
  window.renderStatementPage(1);

  document.getElementById('statement-total-debit').innerText = totalDebit.toLocaleString('en-US');
  document.getElementById('statement-total-credit').innerText = totalCredit.toLocaleString('en-US');

  let finalBalStr = Math.abs(runningBalance).toLocaleString('en-US');
  if (runningBalance > 0) finalBalStr += ' مدين (لنا)';
  else if (runningBalance < 0) finalBalStr += ' دائن (لهم)';
  else finalBalStr = '0';
  document.getElementById('statement-final-balance').innerText = finalBalStr;
}

window.printContactStatement = function () {
  const content = document.getElementById('contact-statement-modal').innerHTML;
  const original = document.body.innerHTML;
  document.body.innerHTML = content;
  window.print();
  document.body.innerHTML = original;
  window.location.reload();
}


window.openAccountStatement = function (accountId) {
  window.currentStatementContactId = null;

  window.currentStatementAccountId = accountId;
  const a = currentAccounts.find(x => String(x.id) === String(accountId));
  if (!a) return;
  document.getElementById('statement-header-info').innerText = `كشف حساب: ${a.name}`;
  document.getElementById('statement-date-from').value = '';
  document.getElementById('statement-date-to').value = '';
  window.refreshAccountStatement();

  // Reuse the contact statement modal since it's just a generic table
  showModal('contact-statement-modal');
};

window.refreshAccountStatement = function () {
  const accountId = window.currentStatementAccountId;
  const a = currentAccounts.find(x => String(x.id) === String(accountId));
  if (!a) return;

  const filterFrom = document.getElementById('statement-date-from').value;
  const filterTo = document.getElementById('statement-date-to').value;

  const tbody = document.getElementById('statement-tbody');
  tbody.innerHTML = '';

  let records = [];

  // Add Opening Balance
  if (a.op_debit || a.op_credit) {
    records.push({
      date: '1970-01-01', // very old date to stay at top
      type: 'رصيد افتتاحي',
      ref: '-',
      notes: '',
      debit: parseFloat(a.op_debit) || 0,
      credit: parseFloat(a.op_credit) || 0
    });
  }

  // Gather Journals
  currentJournals.filter(j => j.status === 'posted').forEach(j => {
    if (j.rows) {
      j.rows.forEach(r => {
        if (r.account_id == accountId) {

          let tName = 'قيد يومية';
          let rName = '#' + j.id;

          if (j.reference) {
            if (j.reference.startsWith('voucher_')) { tName = 'سند (صرف/قبض)'; rName = '#' + j.reference.split('_')[1]; }
            else if (j.reference.startsWith('transfer_')) { tName = 'سند تحويل'; rName = '#' + j.reference.split('_')[1]; }
            else if (j.reference.startsWith('sales_')) { tName = 'فاتورة مبيعات'; rName = '#' + j.reference.split('_')[1]; }
            else if (j.reference.startsWith('purchases_')) { tName = 'فاتورة مشتريات'; rName = '#' + j.reference.split('_')[1]; }
            else if (j.reference.startsWith('returns_sales_')) { tName = 'مرتجع مبيعات'; rName = '#' + j.reference.split('_')[2]; }
            else if (j.reference.startsWith('returns_purchases_')) { tName = 'مرتجع مشتريات'; rName = '#' + j.reference.split('_')[2]; }
            else if (j.reference.startsWith('client_abstract_')) { tName = 'مستخلص عميل'; rName = '#' + j.reference.split('_')[2]; }
            else if (j.reference.startsWith('subcontract_abstract_')) { tName = 'مستخلص مقاول'; rName = '#' + j.reference.split('_')[2]; }
            else if (j.reference.startsWith('manual_')) { tName = 'قيد يدوي'; rName = '#' + j.reference.split('_')[1]; }
            else { rName = j.reference; }
          }

          // Fallback to description heuristics if reference is missing or generic
          if (tName === 'قيد يومية' && j.desc) {
            if (j.desc.includes('سند صرف')) tName = 'سند صرف';
            else if (j.desc.includes('سند قبض')) tName = 'سند قبض';
            else if (j.desc.includes('سند تحويل')) tName = 'سند تحويل';
          }

          records.push({
            date: j.date,
            type: tName,
            ref: rName,
            notes: r.description || j.notes || j.desc || '',
            debit: parseFloat(r.debit) || 0,
            credit: parseFloat(r.credit) || 0
          });
        }
      });
    }
  });

  // Filter by date
  if (filterFrom) {
    const fromDate = new Date(filterFrom); fromDate.setHours(0, 0, 0, 0);
    records = records.filter(r => r.date === '1970-01-01' || new Date(r.date) >= fromDate);
  }
  if (filterTo) {
    const toDate = new Date(filterTo); toDate.setHours(23, 59, 59, 999);
    records = records.filter(r => new Date(r.date) <= toDate);
  }

  // Sort chronologically
  records.sort((r1, r2) => new Date(r1.date) - new Date(r2.date));

  let runningBalance = 0;
  let totalDebit = 0;
  let totalCredit = 0;

  records.forEach(r => {
    totalDebit += r.debit;
    totalCredit += r.credit;
    runningBalance += (r.debit - r.credit);

    let balStr = Math.abs(runningBalance).toLocaleString('en-US');
    if (runningBalance > 0) balStr += ' مدين';
    else if (runningBalance < 0) balStr += ' دائن';

    let displayDate = r.date === '1970-01-01' ? '-' : new Date(r.date).toLocaleString('ar-EG');

    r.balStr = balStr;
  });

  window.currentStatementRecords = records;
  window.renderStatementPage(1);

  document.getElementById('statement-total-debit').innerText = totalDebit.toLocaleString('en-US');
  document.getElementById('statement-total-credit').innerText = totalCredit.toLocaleString('en-US');

  let finalBalStr = Math.abs(runningBalance).toLocaleString('en-US');
  if (runningBalance > 0) finalBalStr += ' مدين';
  else if (runningBalance < 0) finalBalStr += ' دائن';
  else finalBalStr = '0';
  document.getElementById('statement-final-balance').innerText = finalBalStr;
};


// Prevent scrolling on number inputs from changing the value
document.addEventListener("wheel", function (event) {
  if (document.activeElement.type === "number") {
    document.activeElement.blur();
  }
});


// Full Backup Logic
document.getElementById('btn-full-backup')?.addEventListener('click', async () => {
  try {
    if (!confirm('هل تريد تحميل نسخة احتياطية كاملة من قاعدة البيانات الآن؟')) return;

    const backupData = {
      timestamp: new Date().toISOString(),
      users: await window.DB.getAll('users'),
      items: await window.DB.getAll('items'),
      projects: await window.DB.getAll('projects'),
      warehouses: await window.DB.getAll('warehouses'),
      contacts: await window.DB.getAll('contacts'),
      units: await window.DB.getAll('units'),
      transactions: await window.DB.getAll('transactions'),
      notifications: await window.DB.getAll('notifications'),
      client_abstracts: await window.DB.getAll('client_abstracts'),
      invoice_items: await window.DB.getAll('invoice_items'),
      item_bom: await window.DB.getAll('item_bom'),
      accounts: await window.DB.getAll('accounts'),
      journal_entries: await window.DB.getAll('journal_entries'),
      journal_lines: await window.DB.getAll('journal_lines')
    };

    const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(backupData, null, 2));
    const downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href", dataStr);
    const dateStr = new Date().toISOString().split('T')[0];
    downloadAnchorNode.setAttribute("download", "EasyERP_FullBackup_" + dateStr + ".json");
    document.body.appendChild(downloadAnchorNode); // required for firefox
    downloadAnchorNode.click();
    downloadAnchorNode.remove();

  } catch (err) {
    console.error('Backup failed:', err);
    alert('حدث خطأ أثناء تحميل النسخة الاحتياطية: ' + err.message);
  }
});


// --- CROSS LINKING ---
window.renderRelatedLinks = function (type, id, containerId) {
  const container = document.getElementById(containerId);
  if (!container) return;

  let html = '<div style="background: rgba(23, 162, 184, 0.1); padding: 10px; border-radius: 5px; border: 1px solid #17a2b8; margin-bottom: 15px;">';
  html += '<strong style="color: #17a2b8; display: block; margin-bottom: 8px;">🔗 حركات ومستندات مرتبطة:</strong>';
  let hasLinks = false;

  if (type === 'invoice') {
    const inv = allInvoices.find(i => String(i.id) === String(id));
    let banner = document.getElementById('sales-invoice-returns-banner');
    if (!banner) {
      banner = document.createElement('div');
      banner.id = 'sales-invoice-returns-banner';
      const title = document.getElementById('sales-modal-title');
      if (title) title.after(banner);
    }
    if (inv) {
      const returns = allInvoices.filter(r => r.type === 'sales_return' && r.linked_invoice_id === inv.id);
      if (returns.length > 0) {
        let linksHTML = returns.map(r => `<a href="#" onclick="closeModal('sales-modal'); window.switchView('sales-returns'); setTimeout(() => { window.editSalesReturn(${r.id}); }, 200); return false;" style="margin-right:10px; text-decoration:none; font-weight:bold; color:#b71c1c;">🔗 عرض المرتجع #${r.id}</a>`).join('');
        banner.innerHTML = `<div style="margin:10px 0; background:#ffebee; padding:10px; border-radius:5px; border-right:4px solid #f44336;"><strong>⚠️ يوجد مرتجعات لهذه الفاتورة:</strong><br>${linksHTML}</div>`;
      } else {
        banner.innerHTML = '';
      }
    } else {
      banner.innerHTML = '';
    }
    if (inv) {
      if (inv.is_from_settlement && inv.settlement_ref) {
        html += `<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); viewSettlement(${inv.settlement_ref})">👁️ عرض تسوية العهدة الأصلية</button>`;
        hasLinks = true;
      }
      if (inv.type === 'purchases_return' || inv.type === 'sales_return') {
        if (inv.doc_no) {
          const originalInv = allInvoices.find(i => String(i.id) === String(inv.doc_no) || String(i.doc_no) === String(inv.doc_no));
          if (originalInv && originalInv.id !== inv.id) {
            html += `<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); viewDetails(${originalInv.id})">👁️ عرض الفاتورة الأصلية</button>`;
            hasLinks = true;
          }
        }
      }
      if (inv.type === 'in' || inv.type === 'out' || inv.type === 'sales') {
        const returns = allInvoices.filter(i => (i.type === 'purchases_return' || i.type === 'sales_return') && (String(i.doc_no) === String(inv.id) || (inv.doc_no && String(i.doc_no) === String(inv.doc_no))));
        returns.forEach(r => {
          html += `<button class="btn btn-sm btn-warning" style="margin-left: 5px; margin-bottom: 5px; color:black;" onclick="closeModal('details-modal'); viewDetails(${r.id})">👁️ عرض فاتورة مرتجع (#${r.id})</button>`;
          hasLinks = true;
        });
      }

      const relatedVouchers = allInvoices.filter(i => (i.type === 'receipt' || i.type === 'payment') && (String(i.linked_invoice_id) === String(inv.id) || (i.notes && i.notes.includes(String(inv.id)))));
      relatedVouchers.forEach(v => {
        html += `<button class="btn btn-sm btn-success" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); if(typeof editVoucher === 'function') editVoucher(${v.id}); else alert('السند رقم ${v.id} بمبلغ ${v.amount}')">💵 عرض ${v.type === 'receipt' ? 'سند قبض' : 'سند صرف'} (#${v.id})</button>`;
        hasLinks = true;
      });

      if (inv.status === 'posted' && (inv.type === 'sales' || inv.type === 'purchases')) {
        html += `<button class="btn btn-sm btn-primary" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); if(typeof openVoucherModal === 'function') { openVoucherModal('${inv.type === 'sales' ? 'receipt' : 'payment'}', ${inv.id}, ${inv.contact_id}); }">➕ تسجيل دفعة جديدة</button>`;
        hasLinks = true;
      }

      if (typeof currentJournals !== 'undefined') {
        const relatedJournals = currentJournals.filter(j =>
          (String(j.ref_id) === String(inv.id)) ||
          (j.reference && j.reference.includes('#' + inv.id)) ||
          (j.reference && j.reference.includes('_' + inv.id))
        );
        relatedJournals.forEach(j => {
          if (new RegExp('\\b' + inv.id + '\\b').test(j.reference) || String(j.ref_id) === String(inv.id)) {
            html += `<button class="btn btn-sm" style="background:#6f42c1; color:white; margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); openJournalModal(${j.id})">📓 عرض قيد اليومية</button>`;
            hasLinks = true;
          }
        });
      }
    }
  } else if (type === 'settlement') {
    const s = allInvoices.find(i => String(i.id) === String(id));
    if (s) {

      const relatedVouchers = allInvoices.filter(i => (i.type === 'receipt' || i.type === 'payment') && (String(i.linked_invoice_id) === String(inv.id) || (i.notes && i.notes.includes(String(inv.id)))));
      relatedVouchers.forEach(v => {
        html += `<button class="btn btn-sm btn-success" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); if(typeof editVoucher === 'function') editVoucher(${v.id}); else alert('السند رقم ${v.id} بمبلغ ${v.amount}')">💵 عرض ${v.type === 'receipt' ? 'سند قبض' : 'سند صرف'} (#${v.id})</button>`;
        hasLinks = true;
      });

      if (inv.status === 'posted' && (inv.type === 'sales' || inv.type === 'purchases')) {
        html += `<button class="btn btn-sm btn-primary" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); if(typeof openVoucherModal === 'function') { openVoucherModal('${inv.type === 'sales' ? 'receipt' : 'payment'}', ${inv.id}, ${inv.contact_id}); }">➕ تسجيل دفعة جديدة</button>`;
        hasLinks = true;
      }

      if (typeof currentJournals !== 'undefined') {
        const settlementJournals = currentJournals.filter(j => j.type === 'settlement' && String(j.ref_id) === String(s.id));
        settlementJournals.forEach(j => {
          html += `<button class="btn btn-sm" style="background:#6f42c1; color:white; margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('settlement-modal'); openJournalModal(${j.id})">📓 عرض قيد المصروفات</button>`;
          hasLinks = true;
        });
      }
      const inventoryInvs = allInvoices.filter(i => i.is_from_settlement === true && String(i.settlement_ref) === String(s.id));
      inventoryInvs.forEach(inv => {
        html += `<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('settlement-modal'); viewDetails(${inv.id})">📦 عرض إذن المخزن</button>`;
        hasLinks = true;
      });
    }
  } else if (type === 'journal') {
    const j = currentJournals.find(x => String(x.id) === String(id));
    if (j) {
      if (j.type === 'settlement' && j.ref_id) {
        html += `<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('journal-modal'); viewSettlement(${j.ref_id})">👁️ عرض تسوية العهدة</button>`;
        hasLinks = true;
      }
      if (j.reference) {
        const match = j.reference.match(/#(\d+)/) || j.reference.match(/_(\d+)$/);
        if (match && match[1]) {
          const invId = parseInt(match[1]);
          const relatedInv = allInvoices.find(i => String(i.id) === String(invId));
          if (relatedInv) {
            html += `<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('journal-modal'); viewDetails(${invId})">👁️ المستند المرتبط</button>`;
            hasLinks = true;
          }
        }
      }
    }
  }

  html += '</div>';
  if (hasLinks) {
    container.innerHTML = html;
    container.style.display = 'block';
  } else {
    container.innerHTML = '';
    container.style.display = 'none';
  }
};


window.processInvoicePayment = async function (invoice, invType) {
  const paidAmountInput = document.getElementById(invType + '-paid-amount');
  const treasuryInput = document.getElementById(invType + '-treasury');

  if (!paidAmountInput || !treasuryInput) return;

  const paidAmount = parseFloat(paidAmountInput.value) || 0;
  const treasuryId = parseInt(treasuryInput.value) || null;

  if (paidAmount <= 0) return;
  if (!treasuryId) {
    console.warn('Treasury not selected for payment.');
    return;
  }

  const voucherType = invType === 'sales' ? 'receipt' : 'payment';

  const v = {
    id: Date.now() + Math.floor(Math.random() * 1000),
    type: voucherType,
    date: invoice.date,
    doc_no: String(invoice.id),
    contact_id: invoice.contact_id,
    treasury_account_id: treasuryId,
    amount: paidAmount,
    notes: `دفعة نقدية عند حفظ فاتورة ${invType === 'sales' ? 'المبيعات' : 'المشتريات'} رقم ${invoice.id}`,
    status: 'posted',
    created_by: typeof currentUser !== 'undefined' && currentUser ? currentUser.username : 'النظام',
    linked_invoice_id: invoice.id
  };

  await window.DB.add('transactions', v);

  if (typeof window.generateVoucherJournal === 'function') {
    await window.generateVoucherJournal(v);
  }

  // Reset paid amount so it doesn't duplicate if they edit again and don't change it.
  paidAmountInput.value = 0;
};


window.openPayInsideModal = function (type) {
  const id = document.getElementById(`edit-${type}-id`).value;
  const contactId = document.getElementById(`${type}-contact`).value;
  if (!id) {
    alert('يجب حفظ الفاتورة أولاً!');
    return;
  }
  closeModal(type + '-modal');
  if (typeof openVoucherModal === 'function') {
    openVoucherModal(type === 'sales' ? 'receipt' : 'payment', id, contactId);
  }
};


window.deleteInvoiceInsideModal = async function (type) {
  const id = document.getElementById(`edit-${type}-id`).value;
  if (!id) return;
  if (confirm('هل أنت متأكد من حذف هذه الفاتورة؟')) {
    await deleteInvoice(parseInt(id), type);
    closeModal(type + '-modal');
  }
};
// btn-save-invoice handler registered above via window._saveInvoiceHandler
window.generateProjectCostsReport = function() {
  const table = document.getElementById('project-costs-table');
  const custodiesTable = document.getElementById('custodies-table');
  const subTable = document.getElementById('subcontractors-table');
  if (!table) return;

  const fmtN = n => (parseFloat(n)||0).toLocaleString('en-US', {minimumFractionDigits:2});

  // 1. تجميع البيانات
  let allData = [];
  if (typeof allInvoices !== 'undefined') allData = allData.concat(allInvoices);
  if (typeof window.allSales !== 'undefined') allData = allData.concat(window.allSales);
  if (typeof window.allPurchases !== 'undefined') allData = allData.concat(window.allPurchases);

  let uniqueDataMap = new Map();
  allData.forEach(inv => {
     if (inv && inv.id && inv.type) uniqueDataMap.set(inv.type + '_' + inv.id, inv);
  });
  let mergedInvoices = Array.from(uniqueDataMap.values());

  // ===== جدول المشاريع =====
  let thead = `<thead><tr style="background:var(--primary);color:#fff;">
    <th>المشروع</th><th>الحالة</th>
    <th>مواد (منصرف/إهلاك)</th><th>مشتريات مباشرة</th><th>مواد (تسوية عهدة)</th>
    <th>مصاريف (تسوية)</th><th>رواتب وأجور</th><th>مستخلصات مقاولين</th>
    <th>إجمالي التكاليف</th><th>قيمة العقد</th><th>الربح / الخسارة</th>
  </tr></thead>`;
  let tbody = '<tbody>';
  let grandTotal = 0;

  (currentProjects || []).forEach(proj => {
    let materialsCost = 0;
    let directPurchasesCost = 0;
    let settlementMaterials = 0;
    let settlementExpenses = 0;

    mergedInvoices.forEach(inv => {
        if (inv.status === 'draft') return; // تجاهل المسودات

        // أ. مواد من أذونات الصرف والإهلاك
        if ((inv.type === 'out_project' || inv.type === 'depreciate_asset') && String(inv.project_id) === String(proj.id)) {
            (inv.items || []).forEach(it => { materialsCost += (parseFloat(it.qty)||0)*(parseFloat(it.price)||0); });
        }

        // ب. مشتريات مباشرة للمشروع
        if (inv.type === 'purchases' && String(inv.project_id) === String(proj.id)) {
            (inv.items || []).forEach(it => { directPurchasesCost += (parseFloat(it.qty)||0)*(parseFloat(it.price)||0); });
        }

        // ج. مواد + مصاريف من تسويات العهدة
        if (inv.type === 'petty_cash_settlement' && (inv.status === 'completed' || inv.status === 'posted')) {
            (inv.items || []).forEach(it => {
                const itProjId = parseInt(it.project_id) || parseInt(inv.project_id);
                if (itProjId !== parseInt(proj.id)) return;
                const lineTotal = (parseFloat(it.qty)||0) * (parseFloat(it.price)||0);
                if (it.item_type === 'inventory') settlementMaterials += lineTotal;
                else settlementExpenses += lineTotal;
            });
        }
    });

    // د. مستخلصات مقاولي الباطن
    let subcontractorsCost = 0;
    if (window.allSubAbstracts) {
      window.allSubAbstracts.filter(a =>
        String(a.project_id) === String(proj.id) && a.status !== 'cancelled'
      ).forEach(a => { subcontractorsCost += parseFloat(a.net_value)||0; });
    }

    // هـ. مصاريف الموارد البشرية (الرواتب والأجور) من القيود
    let payrollCost = 0;
    (currentJournals || []).forEach(j => {
      if (j.reference && j.reference.startsWith('PR-')) {
        (j.rows || []).forEach(r => {
          if (String(r.project_id) === String(proj.id) && parseFloat(r.debit) > 0) {
            const acc = currentAccounts.find(a => String(a.id) === String(r.account_id));
            if (acc && acc.type === 'مصروفات') {
              payrollCost += parseFloat(r.debit);
            }
          }
        });
      }
    });

    const total = materialsCost + directPurchasesCost + settlementMaterials + settlementExpenses + subcontractorsCost + payrollCost;
    grandTotal += total;
    const contractVal = parseFloat(proj.contract_value || proj.budget || 0);
    const profit = contractVal - total;
    const profitColor = profit >= 0 ? 'color:#388e3c;' : 'color:#d32f2f;';
    const statusColor = proj.status === 'active' ? '#1976d2' : proj.status === 'completed' ? '#388e3c' : '#9e9e9e';

    tbody += `<tr>
      <td style="font-weight:bold;text-align:right;">${proj.name}</td>
      <td><span style="background:${statusColor};color:#fff;padding:2px 8px;border-radius:4px;font-size:12px;">${proj.status==='active'?'نشط':proj.status==='completed'?'مكتمل':'معلق'}</span></td>
      <td>${fmtN(materialsCost)}</td>
      <td><span style="color:#e67e22;font-weight:bold;">${fmtN(directPurchasesCost)}</span></td>
      <td>${fmtN(settlementMaterials)}</td>
      <td>${fmtN(settlementExpenses)}</td>
      <td style="color:#8e44ad;font-weight:bold;">${fmtN(payrollCost)}</td>
      <td>${fmtN(subcontractorsCost)}</td>
      <td style="font-weight:bold;background:rgba(0,0,0,0.1);">${fmtN(total)}</td>
      <td style="color:var(--primary);">${contractVal ? fmtN(contractVal) : '-'}</td>
      <td style="${profitColor}font-weight:bold;">${contractVal ? (profit>=0?'+':'')+fmtN(profit) : '-'}</td>
    </tr>`;
  });

  tbody += `<tr style="background:rgba(0,0,0,0.2);font-weight:bold;">
    <td colspan="8">الإجمالي الكلي</td>
    <td>${fmtN(grandTotal)} ج.م</td><td></td><td></td>
  </tr></tbody>`;
  table.innerHTML = thead + tbody;

  // ===== جدول عهد الموظفين =====
  if (custodiesTable) {
    let cHead = `<thead><tr style="background:var(--secondary);color:#fff;">
      <th>الموظف</th><th>المشروع</th><th>إجمالي العهدة</th><th>المُسوَّى</th><th>المتبقي</th>
    </tr></thead>`;
    let cBody = '<tbody>';
    const custodies = mergedInvoices.filter(inv => inv.type === 'petty_cash');
    custodies.forEach(c => {
      const settled = mergedInvoices.filter(inv =>
        inv.type === 'petty_cash_settlement' && (inv.status === 'completed' || inv.status === 'posted') &&
        String(inv.custody_id) === String(c.id)
      ).reduce((s,inv) => s + (inv.items||[]).reduce((ss,it) => ss+(parseFloat(it.qty)||0)*(parseFloat(it.price)||0), 0), 0);
      const remaining = (parseFloat(c.amount)||0) - settled;
      const proj = (currentProjects||[]).find(p => String(p.id) === String(c.project_id));
      cBody += `<tr>
        <td>${c.employee_name || c.contact_name || '-'}</td>
        <td>${proj?.name || '-'}</td>
        <td>${fmtN(c.amount)} ج.م</td>
        <td>${fmtN(settled)} ج.م</td>
        <td style="${remaining>0?'color:#d32f2f;':'color:#388e3c;'}font-weight:bold;">${fmtN(remaining)} ج.م</td>
      </tr>`;
    });
    if (!custodies.length) cBody += '<tr><td colspan="5" style="text-align:center;">لا توجد عهد</td></tr>';
    cBody += '</tbody>';
    custodiesTable.innerHTML = cHead + cBody;
  }

  // ===== جدول مستخلصات مقاولين =====
  if (subTable && window.allSubAbstracts && window.allSubContracts) {
    let sHead = `<thead><tr style="background:var(--accent);color:#fff;">
      <th>المقاول</th><th>المشروع</th><th>قيمة العقد</th><th>المستخلصات</th><th>المتبقي</th>
    </tr></thead>`;
    let sBody = '<tbody>';
    (window.allSubContracts||[]).forEach(sc => {
      const abstracts = (window.allSubAbstracts||[]).filter(a =>
        String(a.contract_id) === String(sc.id) && a.status !== 'cancelled'
      );
      const totalAbstracts = abstracts.reduce((s,a) => s+(parseFloat(a.net_value)||0), 0);
      const remaining = (parseFloat(sc.contract_value)||0) - totalAbstracts;
      const proj = (currentProjects||[]).find(p => String(p.id) === String(sc.project_id));
      const contractor = (currentContacts||[]).find(c => String(c.id) === String(sc.subcontractor_id));
      sBody += `<tr>
        <td>${contractor?.name || '-'}</td>
        <td>${proj?.name || '-'}</td>
        <td>${fmtN(sc.contract_value)} ج.م</td>
        <td style="color:#d32f2f;">${fmtN(totalAbstracts)} ج.م</td>
        <td style="${remaining<0?'color:#d32f2f;':'color:#388e3c;'}font-weight:bold;">${fmtN(remaining)} ج.م</td>
      </tr>`;
    });
    if (!(window.allSubContracts||[]).length) sBody += '<tr><td colspan="5" style="text-align:center;">لا توجد عقود مقاولين</td></tr>';
    sBody += '</tbody>';
    subTable.innerHTML = sHead + sBody;
  }
};
window.addEventListener('load', function() {
    setTimeout(function() {
        console.log("تفعيل نظام المقايسة (محصن ضد أخطاء الحفظ + ربط حي للبيانات)...");

        const getProjects = () => typeof currentProjects !== 'undefined' ? currentProjects : [];
        window.currentScBoqItems = []; 

        // =========================================================
        // 1. إعادة كتابة دوال الحفظ لتخطي أي فقدان للبيانات
        // =========================================================
        window.saveSubcontract = async function() {
            try {
                const idStr = document.getElementById('subcontract-id')?.value;
                const project_id = document.getElementById('sc-project-id')?.value;
                const subcontractor_id = document.getElementById('sc-subcontractor-id')?.value;
                const contract_number = document.getElementById('sc-contract-number')?.value;
                const date = document.getElementById('sc-date')?.value;
                const notes = document.getElementById('sc-notes')?.value || '';
                
                if (!project_id || !subcontractor_id || !date) {
                    alert('الرجاء إكمال البيانات الأساسية (المشروع، المقاول، التاريخ).');
                    return;
                }

                // حساب الإجمالي مباشرة من المصفوفة التي تم تحديثها حياً
                const contract_value = (window.currentScBoqItems || []).reduce((sum, it) => sum + ((parseFloat(it.qty)||0) * (parseFloat(it.price)||0)), 0);

                const obj = {
                    project_id: parseInt(project_id),
                    subcontractor_id: parseInt(subcontractor_id),
                    contract_number: contract_number,
                    date: date,
                    notes: notes,
                    contract_value: contract_value,
                    boq_items: window.currentScBoqItems || []
                };

                if (idStr) {
                    obj.id = parseInt(idStr);
                    await window.DB.update('subcontracts', obj);
                } else {
                    await window.DB.add('subcontracts', obj);
                }
                
                if(typeof closeModal === 'function') closeModal('subcontract-modal');
                if(typeof window.loadData === 'function') await window.loadData();
                if(typeof window.renderSubContracts === 'function') window.renderSubContracts();
                if(typeof window.renderSubcontracts === 'function') window.renderSubcontracts();
                alert('تم حفظ العقد بنجاح!');
            } catch(e) { alert('خطأ أثناء الحفظ: ' + e.message); }
        };

        window.saveSubContract = async function() {
            try {
                const idStr = document.getElementById('sc-new-id')?.value;
                const contract_number = document.getElementById('sc-new-number')?.value;
                const date = document.getElementById('sc-new-date')?.value;
                const project_id = document.getElementById('sc-new-project')?.value;
                const subcontractor_id = document.getElementById('sc-new-subcontractor')?.value;
                const deduction_percent = document.getElementById('sc-new-deduction-percent')?.value || 0;
                const retention_percent = document.getElementById('sc-new-retention-percent')?.value || 0;
                const notes = document.getElementById('sc-new-notes')?.value || '';

                if (!project_id || !subcontractor_id || !date) {
                    alert('الرجاء إكمال البيانات الأساسية للعقد.');
                    return;
                }

                const contract_value = (window.currentScBoqItems || []).reduce((sum, it) => sum + ((parseFloat(it.qty)||0) * (parseFloat(it.price)||0)), 0);

                const obj = {
                    project_id: parseInt(project_id),
                    subcontractor_id: parseInt(subcontractor_id),
                    contract_number: contract_number,
                    date: date,
                    deduction_percent: parseFloat(deduction_percent),
                    retention_percent: parseFloat(retention_percent),
                    contract_value: contract_value,
                    notes: notes,
                    boq_items: window.currentScBoqItems || []
                };

                if (idStr) {
                    obj.id = parseInt(idStr);
                    await window.DB.update('subcontracts', obj);
                } else {
                    await window.DB.add('subcontracts', obj);
                }
                
                if(typeof closeModal === 'function') closeModal('sc-new-modal');
                if(typeof window.loadData === 'function') await window.loadData();
                if(typeof window.renderSubContracts === 'function') window.renderSubContracts();
                if(typeof window.renderSubcontracts === 'function') window.renderSubcontracts();
                alert('تم حفظ العقد بنجاح!');
            } catch(e) { alert('خطأ أثناء الحفظ: ' + e.message); }
        };

        // =========================================================
        // 2. تحديثات ذكية للـ DOM لمنع فقدان البيانات أثناء الكتابة
        // =========================================================
        window.recalcScRow = function(tr, idx) {
            const qty = parseFloat(window.currentScBoqItems[idx].qty) || 0;
            const price = parseFloat(window.currentScBoqItems[idx].price) || 0;
            const rowTotal = qty * price;
            const totalTd = tr.querySelector('.row-total');
            if(totalTd) totalTd.innerText = rowTotal.toLocaleString('en-US');
            window.recalcScGrandTotal();
        };

        window.recalcScGrandTotal = function() {
            const grandTotal = (window.currentScBoqItems || []).reduce((sum, it) => sum + ((parseFloat(it.qty)||0) * (parseFloat(it.price)||0)), 0);
            const totalSpan1 = document.getElementById('sc-total-value');
            const totalSpan2 = document.getElementById('sc-new-boq-grand-total');
            const contractVal = document.getElementById('sc-new-contract-value');
            if (totalSpan1) totalSpan1.innerText = grandTotal.toLocaleString('en-US');
            if (totalSpan2) totalSpan2.innerText = grandTotal.toLocaleString('en-US');
            if (contractVal) contractVal.value = grandTotal;
        };

        window.renderScItemsTable1 = window.renderScItemsTable2 = function() {
            const tbody1 = document.getElementById('sc-items-tbody');
            const tbody2 = document.getElementById('sc-new-boq-tbody');
            const tbodys = [tbody1, tbody2].filter(t => t); // تطبيق على أي جدول موجود بالشاشة المفتوحة
            
            tbodys.forEach(tbody => {
                tbody.innerHTML = '';
                (window.currentScBoqItems || []).forEach((it, idx) => {
                    const originalQty = it.original_qty !== undefined ? it.original_qty : (it.qty || 0);
                    const qty = parseFloat(it.qty) || 0;
                    const price = parseFloat(it.price) || 0;
                    const rowTotal = qty * price;
                    
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td style="text-align:center;"><input type="checkbox" checked style="width:16px;height:16px; accent-color:var(--primary);"></td>
                        <td><input type="text" value="${it.name || ''}" class="row-name" style="width:100%; border:none; background:rgba(0,0,0,0.05); padding:5px; color:#fff; font-size:14px;" placeholder="اسم البند"></td>
                        <td><input type="text" value="${it.unit || ''}" class="row-unit" style="width:70px; text-align:center; color:#fff; background:rgba(0,0,0,0.05); border:none; font-size:14px;" placeholder="الوحدة"></td>
                        <td>
                            <input type="number" min="0" step="any" value="${qty}" class="row-qty" style="width:100%; text-align:center; color:#fff; background:rgba(0,0,0,0.1); border:1px solid var(--primary); border-radius:4px; padding:6px; font-size:16px; font-weight:bold;">
                            <div style="font-size:14px; font-weight:bold; color:#ff9800; background:rgba(255,152,0,0.15); border:2px solid rgba(255,152,0,0.5); border-radius:6px; padding:5px; margin-top:8px; text-align:center;" title="الكمية الأصلية في مقايسة المشروع">الأساسي: ${originalQty}</div>
                        </td>
                        <td><input type="number" min="0" step="any" value="${price}" class="row-price" style="width:100px; text-align:center; color:#fff; background:rgba(0,0,0,0.05); border:none; font-size:14px;"></td>
                        <td style="font-weight:bold; color:var(--primary); text-align:center; font-size:16px;" class="row-total">${rowTotal.toLocaleString('en-US')}</td>
                        <td style="text-align:center;"><button type="button" class="action-btn btn-delete">❌</button></td>
                    `;

                    // ربط حي للبيانات (Live Binding)
                    tr.querySelector('.row-name').addEventListener('input', (e) => { window.currentScBoqItems[idx].name = e.target.value; });
                    tr.querySelector('.row-unit').addEventListener('input', (e) => { window.currentScBoqItems[idx].unit = e.target.value; });
                    tr.querySelector('.row-qty').addEventListener('input', (e) => { 
                        window.currentScBoqItems[idx].qty = parseFloat(e.target.value) || 0; 
                        window.recalcScRow(tr, idx); 
                    });
                    tr.querySelector('.row-price').addEventListener('input', (e) => { 
                        window.currentScBoqItems[idx].price = parseFloat(e.target.value) || 0; 
                        window.recalcScRow(tr, idx); 
                    });
                    tr.querySelector('.btn-delete').addEventListener('click', () => {
                        window.currentScBoqItems.splice(idx, 1);
                        window.renderScItemsTable1();
                    });

                    tbody.appendChild(tr);
                });
            });
            window.recalcScGrandTotal();
        };

        window.addScItemRow = window.addScBoqRow = function() { 
            window.currentScBoqItems.push({name:'', unit:'متر', qty:0, original_qty:0, price:0}); 
            window.renderScItemsTable1(); 
        };

        // =========================================================
        // 3. تعديل سلوك "فتح نافذة العقد" لجلب البيانات المحفوظة 
        // =========================================================
        const origOpenSubcontractModal = window.openSubcontractModal;
        window.openSubcontractModal = async function(id = null) {
            if (origOpenSubcontractModal) origOpenSubcontractModal(id);
            
            if (id) { // في حالة التعديل
                const contracts = await window.DB.getAll('subcontracts') || [];
                const contract = contracts.find(c => String(c.id) === String(id));
                if (contract && contract.boq_items) {
                    window.currentScBoqItems = JSON.parse(JSON.stringify(contract.boq_items));
                } else {
                    window.currentScBoqItems = [];
                }
            } else { // في حالة إضافة جديد
                window.currentScBoqItems = [];
            }
            setTimeout(() => window.renderScItemsTable1(), 150);
        };

        const origOpenSubContractModal = window.openSubContractModal;
        if(origOpenSubContractModal) {
            window.openSubContractModal = async function(id = null) {
                if (origOpenSubContractModal) origOpenSubContractModal(id);
                
                if (id) {
                    const contracts = await window.DB.getAll('subcontracts') || [];
                    const contract = contracts.find(c => String(c.id) === String(id));
                    if (contract && contract.boq_items) {
                        window.currentScBoqItems = JSON.parse(JSON.stringify(contract.boq_items));
                    } else {
                        window.currentScBoqItems = [];
                    }
                } else {
                    window.currentScBoqItems = [];
                }
                setTimeout(() => window.renderScItemsTable1(), 150);
            };
        }

        // =========================================================
        // 4. استيراد المقايسة عند اختيار المشروع (فقط للعقود الجديدة)
        // =========================================================
        window.onSubcontractProjectChange = window.onScProjectChange = window.importScBoqFromProject = function() {
            // نمنع إعادة السحب من المشروع لو كنا بنعمل "تعديل" لعقد مسجل بالفعل
            const editId = document.getElementById('subcontract-id')?.value || document.getElementById('sc-new-id')?.value;
            if (editId && window.currentScBoqItems && window.currentScBoqItems.length > 0) return;

            const selectEl = document.getElementById('sc-project-id') || document.getElementById('sc-new-project');
            if(!selectEl) return;
            const projValue = selectEl.value;
            
            if (!projValue) {
                window.currentScBoqItems = [];
                window.renderScItemsTable1();
                return;
            }

            const project = getProjects().find(p => String(p.id) === String(projValue) || p.name === projValue);
            
            if (!project || !project.boq_items || project.boq_items.length === 0) {
                window.currentScBoqItems = [];
            } else {
                let clonedItems = JSON.parse(JSON.stringify(project.boq_items));
                clonedItems.forEach(it => {
                    it.original_qty = it.qty; 
                    it.qty = 0;               
                });
                window.currentScBoqItems = clonedItems;
            }
            window.renderScItemsTable1();
        };

    }, 1500);
});
window.addEventListener('load', function() {
    setTimeout(function() {
        console.log("تفعيل نظام مستخلصات المقاولين (النسخة النهائية)...");

        // 1. الدالة التي تعمل عند اختيار العقد في المستخلص
        window.onAbstractContractChange = async function() {
            const contractSelect = document.getElementById('ab-contract-id');
            if (!contractSelect) return;

            const contractId = contractSelect.value;
            if (!contractId) {
                window.currentAbstractItems = [];
                window.renderAbstractItemsTable();
                return;
            }

            try {
                // جلب بيانات العقد مباشرة من قاعدة البيانات
                const contracts = await window.DB.getAll('subcontracts') || [];
                const contract = contracts.find(c => String(c.id) === String(contractId));
                
                // جلب المستخلصات السابقة لنفس العقد
                const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
                const prevAbs = abstracts.filter(a => String(a.contract_id) === String(contractId));

                // تعيين رقم المستخلص تلقائياً (جاري 1، جاري 2، الخ)
                const abstractNumberEl = document.getElementById('ab-abstract-number');
                if (abstractNumberEl && (!abstractNumberEl.value || abstractNumberEl.value.startsWith('SUB-') || abstractNumberEl.value.startsWith('جار'))) {
                    abstractNumberEl.value = 'جاري ' + (prevAbs.length + 1);
                }

                if (!contract || !contract.boq_items || contract.boq_items.length === 0) {
                    alert('هذا العقد لا يحتوي على بنود مسجلة. يمكنك إضافة البنود يدوياً.');
                    window.currentAbstractItems = [];
                } else {
                    // سحب بنود العقد وتجهيزها للمستخلص مع حساب الكميات السابقة
                    window.currentAbstractItems = JSON.parse(JSON.stringify(contract.boq_items)).map((item, index) => {
                        let pQty = 0;
                        prevAbs.forEach(pa => {
                            const paItems = pa.items || pa.boq_lines || [];
                            if (paItems[index]) {
                                pQty += (parseFloat(paItems[index].current_qty) || 0);
                            }
                        });
                        return {
                            name: item.name,
                            unit: item.unit,
                            price: parseFloat(item.price) || 0,
                            prev_qty: pQty, 
                            current_qty: 0,
                            total_qty: parseFloat(item.qty || item.total_qty) || 0
                        };
                    });
                }
                window.renderAbstractItemsTable();
            } catch (e) {
                console.error("خطأ في جلب بيانات العقد:", e);
            }
        };

        // 2. دالة رسم جدول المستخلص
        window.renderAbstractItemsTable = function() {
            const tbody = document.getElementById('ab-items-tbody');
            if (!tbody) return;
            tbody.innerHTML = '';

            let currentWorksTotal = 0;
            let prevWorksTotal = 0;
            let totalWorksTotal = 0;

            (window.currentAbstractItems || []).forEach((it, index) => {
                const currentQty = parseFloat(it.current_qty) || 0;
                const prevQty = parseFloat(it.prev_qty) || 0;
                const accumQty = prevQty + currentQty;
                const price = parseFloat(it.price) || 0;
                const contractQty = parseFloat(it.total_qty || it.qty) || 0;

                const currentVal = currentQty * price;
                const prevVal = prevQty * price;
                const accumVal = accumQty * price;
                const contractVal = contractQty * price;

                currentWorksTotal += currentVal;
                prevWorksTotal += prevVal;
                totalWorksTotal += accumVal;

                tbody.innerHTML += `
                    <tr>
                        <td style="text-align:center;">
                            ${index + 1}
                            <button class="action-btn btn-delete" onclick="window.removeAbstractItem(${index})" style="padding: 2px 5px; margin-right: 5px; background:transparent; border:none; color:red;" title="حذف">❌</button>
                        </td>
                        <td><input type="text" class="ab-item-name" value="${it.name || ''}" onchange="window.updateAbstractItem(${index}, 'name', this.value)" style="width:100%; border:none; background:transparent; color:#fff; font-weight:bold;"></td>
                        <td style="text-align:center;"><input type="text" class="ab-item-unit" value="${it.unit || ''}" onchange="window.updateAbstractItem(${index}, 'unit', this.value)" style="width:50px; border:none; background:transparent; color:#fff; text-align:center;"></td>
                        <td style="text-align:center;"><input type="number" step="any" class="ab-item-price" value="${price}" onchange="window.updateAbstractItem(${index}, 'price', this.value)" style="width:70px; border:none; background:transparent; color:#fff; text-align:center;"></td>
                        <td style="text-align:center;"><input type="number" step="any" class="ab-item-total-qty" value="${contractQty}" onchange="window.updateAbstractItem(${index}, 'total_qty', this.value)" style="width:60px; border:none; background:transparent; color:#fff; text-align:center;"></td>
                        <td style="text-align:center; color:#fff; font-weight:bold;"><span class="ab-item-total-val">${contractVal.toLocaleString('en-US')}</span></td>
                        <td style="text-align:center;"><input type="number" step="any" class="ab-item-prev-qty" value="${prevQty}" onchange="window.updateAbstractItem(${index}, 'prev_qty', this.value)" style="width:60px; border:none; background:transparent; color:#aaa; text-align:center;"></td>
                        <td style="text-align:center;"><input type="number" step="any" class="ab-item-curr-qty" value="${currentQty}" onchange="window.updateAbstractItem(${index}, 'current_qty', this.value)" style="width:70px; border:1px solid var(--primary); background:rgba(0,0,0,0.3); color:#fff; font-weight:bold; padding:5px;"></td>
                        <td style="text-align:center; color:#ff9800; font-weight:bold;"><span class="ab-item-accum-qty">${accumQty}</span></td>
                        <td style="text-align:center; color:#aaa;"><span class="ab-item-prev-val">${prevVal.toLocaleString('en-US')}</span></td>
                        <td style="text-align:center; color:var(--primary); font-weight:bold;"><span class="ab-item-curr-val">${currentVal.toLocaleString('en-US')}</span></td>
                        <td style="text-align:center; color:#4caf50; font-weight:bold;"><span class="ab-item-accum-val">${accumVal.toLocaleString('en-US')}</span></td>
                    </tr>
                `;
            });

            // تحديث إجمالي الأعمال الجارية
            const currWorksEl = document.getElementById('ab-current-works');
            if (currWorksEl) currWorksEl.innerText = currentWorksTotal.toLocaleString('en-US');
            
            const prevWorksEl = document.getElementById('ab-prev-works');
            if (prevWorksEl) prevWorksEl.innerText = prevWorksTotal.toLocaleString('en-US');
            
            const totalWorksEl = document.getElementById('ab-total-works');
            if (totalWorksEl) totalWorksEl.innerText = totalWorksTotal.toLocaleString('en-US');
            
            if (typeof window.calculateAbstractTotals === 'function') window.calculateAbstractTotals();
        };

        // 3. دوال التحديث والإضافة
        window.updateAbstractItem = function(index, field, value) {
            window.currentAbstractItems[index][field] = value;
            window.renderAbstractItemsTable();
        };

        window.removeAbstractItem = function(index) {
            window.currentAbstractItems.splice(index, 1);
            window.renderAbstractItemsTable();
        };

        window.addAbstractItem = function() {
            window.currentAbstractItems.push({ name: 'بند جديد', unit: 'متر', price: 0, prev_qty: 0, current_qty: 0 });
            window.renderAbstractItemsTable();
        };

        // 4. الحسابات التلقائية (استقطاعات وصافي)
        window.calculateAbstractTotals = function() {
            const currWorksText = document.getElementById('ab-current-works')?.innerText || '0';
            const currWorks = parseFloat(currWorksText.replace(/,/g, '')) || 0;

            const advPayment = parseFloat(document.getElementById('ab-advance-payment')?.value) || 0;
            const taxPercent = parseFloat(document.getElementById('ab-tax-percent')?.value) || 0;
            const retPercent = parseFloat(document.getElementById('ab-retention-percent')?.value) || 0;
            const otherDed = parseFloat(document.getElementById('ab-other-deductions')?.value) || 0;

            const taxVal = currWorks * (taxPercent / 100);
            const retentionVal = currWorks * (retPercent / 100);

            if(document.getElementById('ab-tax-value')) document.getElementById('ab-tax-value').innerText = taxVal.toLocaleString('en-US');
            if(document.getElementById('ab-retention-value')) document.getElementById('ab-retention-value').innerText = retentionVal.toLocaleString('en-US');

            const totalDed = advPayment + taxVal + retentionVal + otherDed;
            if(document.getElementById('ab-total-deductions')) document.getElementById('ab-total-deductions').innerText = totalDed.toLocaleString('en-US');

            const netTotal = currWorks - totalDed;
            if(document.getElementById('ab-net-value')) document.getElementById('ab-net-value').innerText = netTotal.toLocaleString('en-US');
        };

    }, 1500);
});
window.renderAbstracts = async function() {
    const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
    const subcontractors = await window.DB.getAll('subcontractors') || [];
    const projects = await window.DB.getAll('projects') || [];
    const subcontracts = await window.DB.getAll('subcontracts') || [];

    // الجدول داخل view مستخلصات مقاولي الباطن تحديداً
    const view = document.getElementById('view-subcontract-abstracts');
    const table = view?.querySelector('table');
    if (!table) return;

    const tbody = table.querySelector('tbody') || table.appendChild(document.createElement('tbody'));
    tbody.innerHTML = '';

    abstracts.forEach(abs => {
        const sub  = subcontractors.find(s => s.id === abs.subcontractor_id)?.name || '-';
        const proj = projects.find(p => p.id === abs.project_id)?.name || '-';
        const cont = subcontracts.find(c => c.id === abs.contract_id)?.contract_number || abs.contract_id || '-';
        const paid = abs.advance_payment || 0;
        const net  = abs.net_value || 0;

        tbody.insertAdjacentHTML('beforeend', `
            <tr>
                <td>${abs.abstract_number || '-'}</td>
                <td>${sub}</td>
                <td>${proj}</td>
                <td>${cont}</td>
                <td>${abs.date || '-'}</td>
                <td>${abs.period || '-'}</td>
                <td>${net.toLocaleString()}</td>
                <td>${paid.toLocaleString()}</td>
                <td>${(net - paid).toLocaleString()}</td>
                <td>${abs.status === 'paid' ? 'مدفوع' : abs.status === 'approved' ? 'معتمد' : 'مسودة'}</td>
                <td>
                    <button class="btn btn-sm btn-primary" onclick="editAbstract(${abs.id})">تعديل</button>
                    ${abs.status === 'draft' ? `<button class="btn btn-sm btn-success" onclick="approveAbstractWithJournal(${abs.id})">اعتماد</button>` : ''}
                    ${abs.status === 'approved' ? `<button class="btn btn-sm btn-info" onclick="paySubcontractAbstract(${abs.id}, ${net - paid}, ${abs.contract_id})">سداد</button>` : ''}
                    <button class="btn btn-sm btn-danger" onclick="deleteAbstract(${abs.id})">حذف</button>
                </td>
            </tr>
        `);
    });
};
window.approveAbstractWithJournal = async function(id) {
    if(confirm('هل أنت متأكد من اعتماد هذا المستخلص؟ (سيتم توليد قيد استحقاق للمقاول)')) {
        const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
        const a = abstracts.find(x => x.id === id);
        if(a) {
            a.status = 'approved';
            await window.DB.update('subcontract_abstracts', a);
            
            // Generate Journal Entry
            const subcontracts = await window.DB.getAll('subcontracts') || [];
            const cont = subcontracts.find(c => c.id == a.contract_id);
            if (cont) {
                const journalEntry = {
                    date: new Date().toISOString().split('T')[0],
                    reference: 'SUB-ABS-' + a.abstract_number,
                    description: 'استحقاق مستخلص مقاول باطن رقم ' + a.abstract_number,
                    lines: [
                        { account_name: 'تكاليف مقاولي الباطن', debit: a.net_value, credit: 0 },
                        { account_name: 'دائنو مقاولي الباطن', debit: 0, credit: a.net_value, contact_id: cont.subcontractor_id }
                    ],
                    total: a.net_value
                };
                await window.DB.add('journal_entries', journalEntry);
                alert('تم اعتماد المستخلص وتوليد القيد بنجاح!');
            }
            if (typeof window.renderAbstracts === 'function') window.renderAbstracts();
        }
    }
};

window.paySubcontractAbstract = function(abstractId, remainingAmount, contractId) {
    if (typeof window.openVoucherModal === 'function') {
        window.openVoucherModal('payment');
        setTimeout(() => {
            if(document.getElementById('voucher-linked-invoice')) document.getElementById('voucher-linked-invoice').value = 'sca-' + abstractId;
            if(document.getElementById('voucher-amount')) document.getElementById('voucher-amount').value = remainingAmount;
            if(document.getElementById('voucher-status')) document.getElementById('voucher-status').value = 'posted';
            
            const sc = typeof currentSubcontracts !== 'undefined' ? currentSubcontracts.find(s => String(s.id) === String(contractId)) : undefined;
            const a = typeof currentSubcontractAbstracts !== 'undefined' ? currentSubcontractAbstracts.find(x => String(x.id) === String(abstractId)) : undefined;
            
            let subcName = '';
            if (sc) {
                if (document.getElementById('voucher-contact')) {
                    document.getElementById('voucher-contact').value = sc.subcontractor_id;
                }
                const subc = typeof currentContacts !== 'undefined' ? currentContacts.find(c => String(c.id) === String(sc.subcontractor_id)) : undefined;
                if(subc) subcName = subc.name;
            }
            
            // تعيين رقم المستند والبيان
            if (a) {
                if(document.getElementById('voucher-doc-no')) {
                    document.getElementById('voucher-doc-no').value = a.abstract_number || ('مستخلص ' + a.id);
                }
                if(document.getElementById('voucher-notes')) {
                    const scNumber = sc ? (sc.contract_number || sc.id) : contractId;
                    document.getElementById('voucher-notes').value = "سداد مستخلص مقاول باطن رقم (" + (a.abstract_number || a.id) + ") " + (subcName ? "للمقاول: " + subcName : "") + " - عقد رقم: " + scNumber;
                }
            } else {
                if(document.getElementById('voucher-notes')) document.getElementById('voucher-notes').value = "سداد مستخلص مقاول باطن رقم " + abstractId;
            }
        }, 150);
    } else {
        alert('يرجى سداد المبلغ من شاشة سندات الصرف وربطها بالمستخلص.');
    }
};



window.currentAuditPage = 1;
window.renderAuditLogs = function() {
  const tbody = document.getElementById('audit-logs-tbody');
  const paginationDiv = document.getElementById('audit-logs-pagination');
  if(!tbody) return;
  tbody.innerHTML = '';
  if (paginationDiv) paginationDiv.innerHTML = '';
  
  let logs = (window.currentAuditLogs || []).slice().reverse();
  
  const searchTerm = (document.getElementById('audit-search').value || '').toLowerCase();
  const dateFilter = document.getElementById('audit-date').value;
  
  let filteredLogs = logs.filter(log => {
    if(searchTerm && (!String(log.username || '').toLowerCase().includes(searchTerm) && !String(log.action || '').toLowerCase().includes(searchTerm) && !String(log.details || '').toLowerCase().includes(searchTerm))) return false;
    if(dateFilter && !String(log.timestamp || '').startsWith(dateFilter)) return false;
    return true;
  });

  const pageSize = 50;
  const totalItems = filteredLogs.length;
  const totalPages = Math.ceil(totalItems / pageSize);
  if (window.currentAuditPage > totalPages && totalPages > 0) window.currentAuditPage = totalPages;
  const startIndex = (window.currentAuditPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const pageData = filteredLogs.slice(startIndex, endIndex);
  
  pageData.forEach(log => {
    tbody.innerHTML += `<tr>
      <td>${log.timestamp || ''}</td>
      <td>${log.username || ''}</td>
      <td><span class="badge ${log.action === 'حذف' ? 'bg-danger' : 'bg-primary'}">${log.action || ''}</span></td>
      <td>${log.module || log.store || ''}</td>
      <td>${log.record_id || ''}</td>
      <td>${log.details || ''}</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.currentAuditPage) {
             btn.style.backgroundColor = 'var(--primary)';
             btn.style.color = '#fff';
         } else {
             btn.style.backgroundColor = '#fff';
             btn.style.color = '#333';
         }
         btn.onclick = () => { window.currentAuditPage = i; window.renderAuditLogs(); };
         paginationDiv.appendChild(btn);
     }
  }
};
window.resetSystemInputs = function() {
    if (currentUser.role !== 'مدير عام') {
        alert('غير مصرح لك بتنفيذ هذه العملية.');
        return;
    }
    
    const pin = prompt('تنبيه خطير! هذه العملية ستقوم بحذف جميع البيانات التشغيلية (فواتير، سندات، قيود، عهد، رواتب، وغيرها) بشكل نهائي.\n\nللتأكيد، يرجى كتابة الرمز السري:');
    if (pin !== '2290') {
        if (pin !== null) alert('الرمز غير صحيح، تم إلغاء العملية.');
        return;
    }
    
    if (!confirm('تأكيد أخير: هل أنت متأكد 100% من تصفير النظام؟ هذه العملية لا يمكن التراجع عنها.')) return;
    
    const card = document.getElementById('backup-result-card');
    const msg = document.getElementById('backup-result-msg');
    
    fetch('reset_inputs.php', {
        method: 'POST'
    })
    .then(r => r.json())
    .then(res => {
        card.style.display = 'block';
        if (res.success) {
            msg.style.color = 'green';
            msg.innerText = res.message;
            setTimeout(() => {
                window.location.reload(true);
            }, 2000);
        } else {
            msg.style.color = 'red';
            msg.innerText = res.error || 'حدث خطأ غير معروف';
        }
    })
    .catch(e => {
        card.style.display = 'block';
        msg.style.color = 'red';
        msg.innerText = 'فشل الاتصال بالخادم.';
    });
};


// Fetch logo on load for login screen
window.addEventListener('DOMContentLoaded', () => {
    fetch('api.php?store=settings')
      .then(res => res.json())
      .then(data => {
          const dbLogoSetting = (data || []).find(s => s.key === 'company_logo');
          if (dbLogoSetting && dbLogoSetting.value) {
              localStorage.setItem('company_logo', dbLogoSetting.value);
              if(typeof applyLogo === 'function') applyLogo(dbLogoSetting.value);
          }
      })
      .catch(e => console.log('Could not fetch logo on load', e));
});


// ==========================================
// STORE JOURNAL ENTRY SYNC
// ==========================================
window.syncStoreJournalEntry = async function(invId) {
    try {
        const invs = await window.DB.getAll('transactions');
        const inv = invs.find(x => String(x.id) === String(invId));
        if (!inv || (inv.type !== 'out_project' && inv.type !== 'depreciate_asset' && inv.type !== 'opening_balance')) return;

        let totalCost = 0;
        (inv.items || []).forEach(it => {
            totalCost += (it.qty || 0) * (it.price || 0);
        });

        // Delete existing journal entry if any
        const journals = await window.DB.getAll('journal_entries') || [];
        const existingJournals = journals.filter(j => j.source_type === 'store_out' && String(j.source_id) === String(invId));
        for(let ej of existingJournals) {
            await window.DB.remove('journal_entries', ej.id);
        }

        if (totalCost <= 0) return;

        const inventoryAcc = await window.resolveSystemAccount('المخزون', ['الأصول المتداولة', 'الأصول'], 'assets');
        const projectCostsAcc = await window.resolveSystemAccount('تكلفة المشاريع', ['المصروفات'], 'expenses');
        
        let debitAcc, creditAcc;
        if (inv.type === 'out_project') {
            debitAcc = projectCostsAcc;
            creditAcc = inventoryAcc;
        } else if (inv.type === 'depreciate_asset') {
            debitAcc = projectCostsAcc;
            creditAcc = await window.resolveSystemAccount('مجمع الإهلاك', ['الخصوم', 'الالتزامات', 'المصروفات'], 'liabilities');
        } else if (inv.type === 'opening_balance') {
            debitAcc = inventoryAcc;
            creditAcc = await window.resolveSystemAccount('أرباح مبقاة (فروق جرد)', ['حقوق الملكية', 'رأس المال', 'الخصوم'], 'equity');
        }

        const newJournal = {
            date: inv.date,
            desc: (inv.type === 'opening_balance' ? 'رصيد أول المدة (جرد)' : inv.type === 'out_project' ? 'صرف مخزني للمشروع ' + (inv.project_name || '') : 'إهلاك أصل للمشروع ' + (inv.project_name || '')) + ' - إذن رقم ' + invId,
            source_type: 'store_out',
            source_id: invId,
            reference: 'store_' + inv.type + '_' + invId,
            status: 'draft',
            total: totalCost,
            rows: [
                { account_id: debitAcc.id, debit: totalCost, credit: 0, project_id: inv.project_id || null },
                { account_id: creditAcc.id, debit: 0, credit: totalCost, project_id: null }
            ]
        };

        await window.DB.add('journal_entries', newJournal);
    } catch(e) {
        console.error('Error syncing store journal entry:', e);
    }
};



window.currentStatementRecords = [];
window.renderStatementPage = function(page) {
  const records = window.currentStatementRecords || [];
  const recordsPerPage = 100;
  const totalPages = Math.ceil(records.length / recordsPerPage);
  if (page < 1) page = 1;
  if (page > totalPages && totalPages > 0) page = totalPages;

  const tbody = document.getElementById('statement-tbody');
  tbody.innerHTML = '';
  
  if (records.length === 0) {
    tbody.innerHTML = '<tr><td colspan="7" style="text-align:center">لا توجد حركات</td></tr>';
    document.getElementById('statement-pagination-controls').innerHTML = '';
    return;
  }

  const startIdx = (page - 1) * recordsPerPage;
  const endIdx = Math.min(startIdx + recordsPerPage, records.length);

  for (let i = startIdx; i < endIdx; i++) {
    const r = records[i];
    tbody.innerHTML += `<tr>
      <td>${new Date(r.date).toLocaleString('ar-EG')}</td>
      <td>${r.type}</td>
      <td>${r.ref}</td>
      <td>${r.notes}</td>
      <td style="color:var(--danger)">${r.debit ? r.debit.toLocaleString('en-US') : '-'}</td>
      <td style="color:#008a45; font-weight:bold;">${r.credit ? r.credit.toLocaleString('en-US') : '-'}</td>
      <td style="font-weight:bold">${r.balStr || ''}</td>
    </tr>`;
  }

  let controlsHtml = '';
  if (totalPages > 1) {
    controlsHtml += `<button class="btn-secondary" style="padding:5px 10px;" onclick="window.renderStatementPage(1)" ${page === 1 ? 'disabled' : ''}>الأولى</button>`;
    controlsHtml += `<button class="btn-secondary" style="padding:5px 10px;" onclick="window.renderStatementPage(${page - 1})" ${page === 1 ? 'disabled' : ''}>السابق</button>`;
    controlsHtml += `<span style="margin:0 10px; font-weight:bold;">صفحة ${page} من ${totalPages}</span>`;
    controlsHtml += `<button class="btn-secondary" style="padding:5px 10px;" onclick="window.renderStatementPage(${page + 1})" ${page === totalPages ? 'disabled' : ''}>التالي</button>`;
    controlsHtml += `<button class="btn-secondary" style="padding:5px 10px;" onclick="window.renderStatementPage(${totalPages})" ${page === totalPages ? 'disabled' : ''}>الأخيرة</button>`;
  }
  document.getElementById('statement-pagination-controls').innerHTML = controlsHtml;
};

window.refreshCurrentStatement = function() {
    if (window.currentStatementProjectId) window.refreshProjectStatement();
    else if (window.currentStatementAccountId) window.refreshAccountStatement();
    else if (window.currentStatementContactId) window.refreshContactStatement();
};

window.printCurrentStatement = function() {
    const content = document.getElementById('contact-statement-modal').innerHTML;
    const original = document.body.innerHTML;
    document.body.innerHTML = content;
    window.print();
    document.body.innerHTML = original;
    window.location.reload();
};



window.openProjectStatement = function (projectId) {
    window.currentStatementProjectId = projectId;
    window.currentStatementContactId = null;
    window.currentStatementAccountId = null;
    
    document.getElementById('statement-date-from').value = '';
    document.getElementById('statement-date-to').value = '';
    window.refreshProjectStatement();
    
    if (typeof showModal === 'function') showModal('contact-statement-modal');
};

window.refreshProjectStatement = function () {
    const projectId = window.currentStatementProjectId;
    const p = currentProjects.find(x => String(x.id) === String(projectId));
    if (!p) return;

    const filterFrom = document.getElementById('statement-date-from').value;
    const filterTo = document.getElementById('statement-date-to').value;

    const tbody = document.getElementById('statement-tbody');
    tbody.innerHTML = '';

    let records = [];

    (currentJournals || []).filter(j => j.status === 'posted').forEach(j => {
        if (j.rows) {
            j.rows.forEach(r => {
                if (String(r.project_id) === String(projectId)) {
                    let tName = 'قيد يومية';
                    let rName = '#' + j.id;

                    if (j.reference) {
                        if (j.reference.startsWith('voucher_')) { tName = 'سند (صرف/قبض)'; rName = '#' + j.reference.split('_')[1]; }
                        else if (j.reference.startsWith('transfer_')) { tName = 'سند تحويل'; rName = '#' + j.reference.split('_')[1]; }
                        else if (j.reference.startsWith('sales_')) { tName = 'فاتورة مبيعات'; rName = '#' + j.reference.split('_')[1]; }
                        else if (j.reference.startsWith('purchases_')) { tName = 'فاتورة مشتريات'; rName = '#' + j.reference.split('_')[1]; }
                        else if (j.reference.startsWith('returns_sales_')) { tName = 'مرتجع مبيعات'; rName = '#' + j.reference.split('_')[2]; }
                        else if (j.reference.startsWith('returns_purchases_')) { tName = 'مرتجع مشتريات'; rName = '#' + j.reference.split('_')[2]; }
                        else if (j.reference.startsWith('client_abstract_')) { tName = 'مستخلص عميل'; rName = '#' + j.reference.split('_')[2]; }
                        else if (j.reference.startsWith('subcontract_abstract_')) { tName = 'مستخلص مقاول'; rName = '#' + j.reference.split('_')[2]; }
                        else if (j.reference.startsWith('manual_')) { tName = 'قيد يدوي'; rName = '#' + j.reference.split('_')[1]; }
                        else if (j.reference.startsWith('store_out_')) { tName = 'صرف مخزني'; rName = '#' + j.reference.split('_')[2]; }
                        else if (j.reference.startsWith('store_in_')) { tName = 'إضافة مخزنية'; rName = '#' + j.reference.split('_')[2]; }
                        else if (j.reference.startsWith('store_opening_balance_')) { tName = 'رصيد أول مخزون'; rName = '#' + j.reference.split('_')[3]; }
                    }
                    
                    if (tName === 'قيد يومية' && j.desc) {
                        if (j.desc.includes('سند صرف')) tName = 'سند صرف';
                        else if (j.desc.includes('سند قبض')) tName = 'سند قبض';
                        else if (j.desc.includes('سند تحويل')) tName = 'سند تحويل';
                        else if (j.desc.includes('صرف مخزني')) tName = 'صرف مخزني';
                        else if (j.desc.includes('إضافة مخزنية')) tName = 'إضافة مخزنية';
                        else if (j.desc.includes('أول المدة (جرد)')) tName = 'جرد مخزني';
                        else if (j.desc.includes('جرد')) tName = 'جرد مخزني';
                        else if (j.desc.includes('إهلاك أصل')) tName = 'إهلاك أصل';
                    }
                    const accName = currentAccounts.find(a => String(a.id) === String(r.account_id))?.name || 'حساب محذوف';
                    
                    let descText = j.desc || '';
                    let finalNotes = descText ? (descText + ' | حساب: ' + accName) : ('حساب: ' + accName);
                    
                    records.push({
                        date: j.date,
                        type: tName,
                        ref: rName,
                        notes: finalNotes,
                        debit: parseFloat(r.debit) || 0,
                        credit: parseFloat(r.credit) || 0
                    });
                }
            });
        }
    });

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

    if (filterFrom) records = records.filter(r => new Date(r.date) >= new Date(filterFrom));
    if (filterTo) records = records.filter(r => new Date(r.date) <= new Date(filterTo));

    let runningBalance = 0;
    let totalD = 0;
    let totalC = 0;

    records.forEach(r => {
        totalD += r.debit;
        totalC += r.credit;
        runningBalance += (r.debit - r.credit);
        let balText = Math.abs(runningBalance).toLocaleString('en-US');
        let balDir = runningBalance > 0 ? ' (مدين)' : runningBalance < 0 ? ' (دائن)' : '';
        r.balStr = balText + balDir;
        r.displayDate = r.date.split('T')[0];
    });

    document.getElementById('statement-total-debit').innerText = totalD.toLocaleString('en-US');
    document.getElementById('statement-total-credit').innerText = totalC.toLocaleString('en-US');
    document.getElementById('statement-final-balance').innerText = Math.abs(runningBalance).toLocaleString('en-US') + (runningBalance > 0 ? ' (مدين)' : runningBalance < 0 ? ' (دائن)' : '');

    window.currentStatementRecords = records;
    window.renderStatementPage(1);
    
    document.getElementById('statement-print-date').innerText = new Date().toLocaleString('ar-EG');
    const periodText = (filterFrom || filterTo) ? `من ${filterFrom || 'البداية'} إلى ${filterTo || 'الآن'}` : 'كل الفترات';
    document.getElementById('statement-period-text').innerText = periodText;
};


// ==========================================
// SMART WOOD CYCLE LOGIC
// ==========================================

window.addWoodEntryRow = function() {
    const tbody = document.getElementById('wood-entries-tbody');
    const itemId = document.getElementById('wood-modal-item-id').value;
    
    let cachedW = '', cachedT = '';
    try {
        const cache = JSON.parse(localStorage.getItem('woodDims_' + itemId));
        if(cache) { cachedW = cache.w; cachedT = cache.t; }
    } catch(e){}

    const tr = document.createElement('tr');
    tr.innerHTML = `
        <td><input type="number" step="0.01" class="form-control wood-l" value="" placeholder="الطول"></td>
        <td><input type="number" step="0.001" class="form-control wood-w" value="${cachedW}" placeholder="العرض"></td>
        <td><input type="number" step="0.001" class="form-control wood-t" value="${cachedT}" placeholder="السمك"></td>
        <td><input type="number" step="1" class="form-control wood-c" placeholder="العدد"></td>
        <td><button class="action-btn btn-delete" onclick="this.closest('tr').remove()">X</button></td>
    `;
    tbody.appendChild(tr);
};

window.processWoodData = function() {
    const itemId = parseInt(document.getElementById('wood-modal-item-id').value);
    const itemDef = currentItems.find(i => String(i.id) === String(itemId));
    if(!itemDef) return;

    const tbody = document.getElementById('wood-entries-tbody');
    const rows = tbody.querySelectorAll('tr');
    
    let validEntryFound = false;

    rows.forEach(row => {
        const l = parseFloat(row.querySelector('.wood-l').value) || 0;
        const w = parseFloat(row.querySelector('.wood-w').value) || 0;
        const t = parseFloat(row.querySelector('.wood-t').value) || 0;
        const c = parseInt(row.querySelector('.wood-c').value) || 0;

        if (l > 0 && w > 0 && t > 0 && c > 0) {
            validEntryFound = true;
            localStorage.setItem('woodDims_' + itemId, JSON.stringify({l, w, t}));
            
            const cubicMeters = (l * w * t * c);
            const notes = '\u0639\u062F\u062F ' + c + ' \u0644\u0648\u062D - \u0645\u0642\u0627\u0633: ' + l + '\u0645 \u00D7 ' + w + '\u0645 \u00D7 ' + t + '\u0645.';

            currentInvoiceItems.push({ 
                item_id: itemId, 
                item_name: itemDef.name, 
                category: itemDef.category, 
                unit: itemDef.unit || 'متر مكعب', 
                qty: parseFloat(cubicMeters.toFixed(4)), 
                price: parseFloat(document.getElementById('invoice-price').value) || 0,
                asset_code: document.getElementById('invoice-asset-code').value || '', 
                alt_unit: null, 
                conv_factor: 1, 
                display_qty: parseFloat(cubicMeters.toFixed(4)) + ' ' + (itemDef.unit || 'متر مكعب'),
                notes: notes
            });
        }
    });

    if (validEntryFound) {
        if(typeof renderInvoiceDraftTable === 'function') renderInvoiceDraftTable();
        closeModal('wood-modal');
        document.getElementById('invoice-item').value = '';
        document.getElementById('invoice-qty').value = '';
    } else {
        alert('يرجى إدخال المقاسات والعدد بشكل صحيح');
    }
};

window.showWoodBreakdown = async function(itemId) {
    try {
        const allInvs = window.allInvoices || [];
        let lengthCounts = {};
        
        allInvs.forEach(inv => {
            if (inv.status === 'draft' || inv.status === 'rejected') return;
            
            const type = inv.type;
            const isOut = (type === 'out' || type === 'out_project' || type === 'depreciate_asset');
            const isIn = (type === 'in' || type === 'opening_balance' || type === 'return_vendor');
            // If return_customer it's technically in, but let's just stick to the main ones
            
            (inv.items || []).forEach(it => {
                if (String(it.item_id) === String(itemId) && it.notes) {
                    const match = it.notes.match(/عبارة عن (\d+) لوح - مقاس: ([\d.]+)م ط/);
                    if (match) {
                        const count = parseInt(match[1]);
                        const length = parseFloat(match[2]);
                        
                        if (!lengthCounts[length]) lengthCounts[length] = 0;
                        
                        if (isIn) {
                            lengthCounts[length] += count;
                        } else if (isOut) {
                            lengthCounts[length] -= count;
                        }
                    }
                }
            });
        });

        const itemDef = window.currentItems.find(i => String(i.id) === String(itemId));
        document.getElementById('wood-breakdown-item-name').innerText = itemDef ? itemDef.name : 'الصنف';

        const contentDiv = document.getElementById('wood-breakdown-content');
        contentDiv.innerHTML = '';
        
        let hasStock = false;
        Object.keys(lengthCounts).sort((a,b)=>b-a).forEach(length => {
            if (lengthCounts[length] > 0) {
                hasStock = true;
                contentDiv.innerHTML += `<div style="padding: 10px; border-bottom: 1px solid #ccc; font-size: 16px;">طول ${length} متر: <strong style="color:var(--primary);">المتاح (${lengthCounts[length]} لوح)</strong></div>`;
            }
        });

        if (!hasStock) {
            contentDiv.innerHTML = '<div style="padding: 10px; text-align: center;">لا يوجد رصيد حالي من الألواح</div>';
        }

        document.getElementById('wood-breakdown-modal').style.display = 'flex';
    } catch(e) {
        console.error(e);
        alert('حدث خطأ أثناء تحميل التفاصيل');
    }
};




window.filterInvoiceItemsByTag = function() {
  try {
      const tagEl = document.getElementById('invoice-item-tag');
      const iItem = document.getElementById('invoice-item-list') || document.getElementById('invoice-item');
      if(!iItem || !tagEl) return;
      
      const tag = tagEl.value;
      let filtered = currentItems;
      
      if(tag && tag !== '') {
          filtered = currentItems.filter(i => {
              let c = String(i.category||'').trim();
              let t = String(i.tags||'').trim();
              let singleTag = String(i.tag||'').trim();
              let val = tag.trim();
              
              if (c === val || c.includes(val)) return true;
              if (singleTag === val || singleTag.includes(val)) return true;
              
              let tagList = t.split(',').map(s=>s.trim());
              if (tagList.includes(val)) return true;
              
              return t.includes(val);
          });
      }
      
      let html = '';
      filtered.forEach(i => {
          html += `<option value="${i.name}" data-id="${i.id}"></option>`;
      });
      iItem.innerHTML = html;
  } catch (err) {
      console.error('Error in filterInvoiceItemsByTag:', err);
  }
};
