// State
let currentUser = null;
let currentItems = [];
let currentProjects = [];
let currentWarehouses = [];
let currentUsers = [];
let currentContacts = [];
let currentUnits = [];
let allInvoices = [];
let allNotifications = [];
let currentInvoiceItems = [];
let currentItemBom = [];
let currentAccounts = [];
let currentJournals = [];
let currentJournalLines = [];

let balancesCache = {};

// 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();
      await loadData();
    }
  } catch(e) {
    console.error("Initialization Error: ", e);
    alert("حدث خطأ أثناء تحميل قاعدة البيانات: " + e.message);
  }
});

function setupUserUI() {
  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'];
  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 = 'كل المخازن';
  } else if (currentUser.role === 'موظف مخصص') {
    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';
    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';
    }
    
    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;
    
  } else {
    document.getElementById('nav-items').style.display = 'block';
    document.getElementById('nav-item-card').style.display = 'block';
    document.getElementById('nav-projects').style.display = 'block';
    document.getElementById('nav-project-reports').style.display = 'block';
    document.getElementById('nav-balances').style.display = 'block';
    document.getElementById('nav-transactions').style.display = 'block';
    document.getElementById('nav-sales').style.display = 'block';
    document.getElementById('nav-purchases').style.display = 'block';
  }
}

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

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

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

  window.expandedAccounts = window.expandedAccounts || {};
  
  function renderTree(parentId, level = 0, isVisible = true) {
    const children = currentAccounts.filter(a => (a.parent_id || null) === parentId).sort((a,b) => (a.code || '').localeCompare(b.code || ''));
    children.forEach(acc => {
      let actions = '';
      if(currentUser && currentUser.role === 'مدير عام') {
        actions = `<button class="action-btn btn-edit" onclick="openAccountModal(${acc.id})">✏️ تعديل</button>
                   <button class="action-btn btn-view" onclick="openAccountModal(null, ${acc.id})">➕ فرعي</button>
                   <button class="action-btn btn-delete" onclick="deleteAccount(${acc.id})">🗑️ حذف</button>`;
      }
      
      const accChildren = currentAccounts.filter(a => a.parent_id === acc.id);
      const indent = level * 20;
      const isExpanded = window.expandedAccounts[acc.id] !== false; 
      const arrow = accChildren.length > 0 ? (isExpanded ? '🔽' : '▶️') : '📄';
      
      const displayStyle = isVisible ? '' : 'display:none;';
      const rowStyle = level === 0 ? 'background:rgba(0,0,0,0.03); font-weight:bold;' : '';
      
      const bal = accBalances[acc.id];
      const totDebit = bal.op_debit + bal.mov_debit;
      const totCredit = bal.op_credit + bal.mov_credit;
      const netDebit = totDebit > totCredit ? totDebit - totCredit : 0;
      const netCredit = totCredit > totDebit ? totCredit - totDebit : 0;
      
      const formatNum = (num) => num === 0 ? '-' : num.toLocaleString('ar-EG', {minimumFractionDigits:2});
      
      tbody.innerHTML += `<tr class="acc-row" style="${rowStyle} ${displayStyle}">
        <td>${acc.code}</td>
        <td style="padding-right: ${indent + 10}px; cursor:pointer; user-select:none;" onclick="toggleAccount(${acc.id})">${arrow} ${acc.name}</td>
        <td>${acc.type}</td>
        <td style="color:#666;">${formatNum(bal.op_debit)}</td>
        <td style="color:#666;">${formatNum(bal.op_credit)}</td>
        <td style="color:var(--primary);">${formatNum(bal.mov_debit)}</td>
        <td style="color:var(--danger);">${formatNum(bal.mov_credit)}</td>
        <td style="font-weight:bold; color:var(--primary);">${formatNum(netDebit)}</td>
        <td style="font-weight:bold; color:var(--danger);">${formatNum(netCredit)}</td>
        <td>${actions}</td>
      </tr>`;
      
      renderTree(acc.id, level + 1, isVisible && isExpanded);
    });
  }
  
  renderTree(null, 0, true);
}

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

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

  if(id) {
    const acc = currentAccounts.find(x => x.id === 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 => a.id === 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 => x.id === 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(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';
    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 => a.id == 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('ar-EG');
  document.getElementById('je-total-credit').innerText = totCredit.toLocaleString('ar-EG');
  document.getElementById('je-diff').innerText = Math.abs(totDebit - totCredit).toLocaleString('ar-EG');
}

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

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

function renderJournals() {
  const tbody = document.getElementById('journals-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  if (currentJournals.length === 0) {
    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; padding: 20px; color:#666;">لا توجد قيود حالياً. اضغط على "+ قيد يومية" لإضافة قيد.</td></tr>';
    return;
  }
  currentJournals.forEach(je => {
    let statusSpan = `<span style="color:gray;">مسودة</span>`;
    if(je.status === 'approved') statusSpan = `<span style="color:var(--primary);">معتمد</span>`;
    if(je.status === 'posted') statusSpan = `<span style="color:green; font-weight:bold;">مُرحّل</span>`;
    
    let actions = `<button class="action-btn btn-view" onclick="openJournalModal(${je.id})">🔍 عرض/تعديل</button>`;
    if(currentUser && currentUser.role === 'مدير عام') {
      if(je.status === 'draft') actions += ` <button class="action-btn" style="color:var(--primary)" onclick="changeJournalStatus(${je.id}, 'approved')">✔️ اعتماد</button>`;
      if(je.status === 'approved') actions += ` <button class="action-btn" style="color:green; font-weight:bold" onclick="changeJournalStatus(${je.id}, 'posted')">🗃️ ترحيل</button>`;
      actions += ` <button class="action-btn btn-delete" onclick="deleteJournal(${je.id})">🗑️ حذف</button>`;
    }
    
    tbody.innerHTML += `<tr><td>#${je.id}</td><td>${je.date}</td><td>${je.desc || je.reference || '-'}</td><td style="font-weight:bold">${(je.total||0).toLocaleString('ar-EG')}</td><td>${statusSpan}</td><td>${actions}</td></tr>`;
  });
}

window.changeJournalStatus = async function(id, newStatus) {
  const msg = newStatus === 'approved' ? 'اعتماد' : 'ترحيل';
  if(!confirm(`هل أنت متأكد من ${msg} القيد؟`)) return;
  const je = currentJournals.find(x => x.id === 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(e.target.id === 'btn-logout') return;
    navItems.forEach(n => n.classList.remove('active'));
    e.target.classList.add('active');
    views.forEach(v => v.classList.remove('active'));
    document.getElementById(`view-${e.target.dataset.view}`).classList.add('active');
    if(e.target.dataset.view === 'project-reports') renderProjectReports();
  });
});

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

// --- CALCULATIONS ---
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.status === 'posted')) {
        b.globalQty += item.qty;
        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.status === 'posted')) {
        b.globalQty -= item.qty;
        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];
        let fromWh = inv.from_warehouse_id;
        b.globalQty -= raw.qty;
        if(fromWh) b.warehouses[fromWh] -= raw.qty;
        let consumedCost = raw.qty * b.avgCost;
        b.totalValue -= consumedCost;
        totalRawCost += consumedCost;
      });
      let prodB = balancesCache[inv.produced_item_id];
      let toWh = inv.from_warehouse_id;
      prodB.globalQty += inv.produced_qty;
      if(toWh) prodB.warehouses[toWh] += inv.produced_qty;
      prodB.totalValue += totalRawCost;
      prodB.avgCost = prodB.globalQty > 0 ? (prodB.totalValue / prodB.globalQty) : 0;
      inv.produced_cost = totalRawCost;
    }
  });
}

// --- 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('');

  if (isEdit) {
    const u = currentUsers.find(x => x.id === id);
    document.getElementById('user-username').value = u.username;
    document.getElementById('user-password').value = u.password;
    document.getElementById('user-role').value = 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 = '';
    
    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 => x.id === 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 => x.id === 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 => x.id === 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 => x.id === id);
    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;
    document.getElementById('item-tag').value = i.tag || '';
    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 = '';
    document.getElementById('item-category').value = 'مادة مستهلكة';
    document.getElementById('item-unit').value = currentUnits[0]?.name || '';
    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 => i.id === 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 => n.id === 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('ar-EG')}</td>
        <td><button class="action-btn btn-delete" onclick="removeProjectBoqRow(${idx})">❌</button></td>
      </tr>
    `;
  });
  document.getElementById('project-boq-total').innerText = total.toLocaleString('ar-EG');
}

// 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 => x.id === 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 = 'block'; proj.style.display = 'block';
    customPerms.style.display = 'none';
  } else if (role === 'موظف مخصص') {
    wh.style.display = 'none'; proj.style.display = 'none';
    customPerms.style.display = 'block';
  } else {
    wh.style.display = 'none'; proj.style.display = 'none';
    customPerms.style.display = 'none';
  }
});

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 = parseInt(e.target.value);
  const itemDef = currentItems.find(i => i.id === item_id);
  const assetGroup = document.getElementById('invoice-asset-code-group');
  if (itemDef && itemDef.category === 'أصل') {
    assetGroup.style.display = 'block';
  } else {
    assetGroup.style.display = 'none';
    document.getElementById('invoice-asset-code').value = '';
  }
});

// --- INVOICE DRAFTING ---
document.getElementById('btn-add-invoice-item').addEventListener('click', () => {
  const item_id = parseInt(document.getElementById('invoice-item').value);
  const 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 || '';
  
  if (!item_id || !qty || qty <= 0) { alert('البيانات غير صحيحة'); return; }
  
  const itemDef = currentItems.find(i => i.id === item_id);
  if(currentInvoiceItems.find(i => i.item_id === item_id && i.asset_code === asset_code)) { alert('الصنف مضاف مسبقاً للفاتورة'); return; }

  currentInvoiceItems.push({ item_id, item_name: itemDef.name, category: itemDef.category, unit: itemDef.unit, qty, price, asset_code });
  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) => {
    let row = `<tr><td>${it.item_name}</td><td>${it.asset_code || '-'}</td><td>${it.qty} ${it.unit}</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;
  });
}

document.getElementById('btn-save-invoice').addEventListener('click', async () => {
  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.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;
      invoice.to_warehouse_name = currentWarehouses.find(w => w.id === primary_wh).name;
      if (type === 'in' && contact_id) {
        invoice.contact_id = contact_id;
        invoice.contact_name = currentContacts.find(c => c.id === contact_id)?.name;
      }
    } else if (type === 'out_project' || type === 'depreciate_asset') {
      invoice.from_warehouse_id = primary_wh;
      invoice.from_warehouse_name = currentWarehouses.find(w => w.id === primary_wh).name;
      invoice.project_id = proj;
      invoice.project_name = currentProjects.find(p => p.id === proj).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;
      invoice.from_warehouse_name = currentWarehouses.find(w => w.id === primary_wh).name;
      invoice.to_warehouse_id = to_wh;
      invoice.to_warehouse_name = currentWarehouses.find(w => w.id === to_wh).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); }

    if (!isEdit && type === 'transfer') {
      const receiverUsers = currentUsers.filter(u => u.warehouse_id === to_wh || u.role === 'مدير عام');
      for (let ru of receiverUsers) {
        await window.DB.add('notifications', {
          user: ru.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); }
});

// --- 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 => i.id === 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 => i.id === 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 => w.id === 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.some(it => it.item_id === 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 => x.id === 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=>x.id===id);
  if(allInvoices.some(inv => inv.user === u.username)) { alert('لا يمكن حذفه لوجود حركات باسمه!'); return; }
  if(confirm('متأكد من حذف المستخدم؟')) { await window.DB.remove('users', id); await loadData(); }
}
window.deleteInvoice = async function(id) {
  if(confirm('تحذير: الحذف سيعكس الأرصدة! متأكد؟')) {
    await window.DB.remove('transactions', id);
    await loadData(); closeModal('details-modal');
  }
}

// --- BASIC SAVE LOGIC (CRUD) ---
document.getElementById('btn-save-user').addEventListener('click', async () => {
  try {
    const editIdStr = document.getElementById('edit-user-id').value;
    const username = document.getElementById('user-username').value;
    const pass = document.getElementById('user-password').value;
    const role = document.getElementById('user-role').value;
    const warehouse_id = role === 'أمين مخزن' ? parseInt(document.getElementById('user-warehouse').value) : null;
    const project_id = role === 'أمين مخزن' && document.getElementById('user-project').value ? parseInt(document.getElementById('user-project').value) : null;
    
    let allowed_modules = [];
    let allowed_warehouses = [];
    let allowed_projects = [];
    if (role === 'موظف مخصص') {
      document.querySelectorAll('.perm-module:checked').forEach(cb => allowed_modules.push(cb.value));
      document.querySelectorAll('.perm-warehouse:checked').forEach(cb => allowed_warehouses.push(parseInt(cb.value)));
      document.querySelectorAll('.perm-project:checked').forEach(cb => allowed_projects.push(parseInt(cb.value)));
    }
    
    if(username && pass) { 
      const obj = { username, password: pass, role, warehouse_id, project_id, allowed_modules, allowed_warehouses, allowed_projects };
      if(editIdStr) { obj.id = parseInt(editIdStr); await window.DB.update('users', obj); } 
      else { await window.DB.add('users', obj); }
      closeModal('user-modal'); await loadData(); 
    } else { alert('أدخل بيانات الدخول!'); }
  } catch(e) { alert("خطأ: " + e.message); }
});

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 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 obj = { code, name, unit, category, tag, bom: category === 'منتج تام' ? currentItemBom : [], bom_produced_qty: category === 'منتج تام' ? bomProducedQty : 1 };
      if(editIdStr) { obj.id = parseInt(editIdStr); await window.DB.update('items', obj); } 
      else { await window.DB.add('items', obj); }
      closeModal('item-modal'); await loadData(); 
    } 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 => i.id === 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 = '';
  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 => i.id === 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.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 => i.id === 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 => i.id === 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 => i.id === 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 || ''; }
    }
    tbody.innerHTML += `<tr><td>${itemName || '-'}</td><td>${it.asset_code || '-'}</td><td>${it.qty} ${itemUnit || ''}</td><td>${it.price || '-'}</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; showModal('details-modal');
}
window.printInvoice = function(invId) {
  const inv = allInvoices.find(i => i.id === 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('ar-EG') : '-'}</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('ar-EG') : '-'}</td><td>${total ? total.toLocaleString('ar-EG') : '-'}</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));
  
  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>`;
    });
  });
  document.getElementById('report-project-total').innerText = totalCost.toLocaleString('ar-EG') + ' ج.م';
}

// --- LOAD DATA & RENDER ---
async function loadData() {
  currentItems = await window.DB.getAll('items');
  currentProjects = await window.DB.getAll('projects');
  currentWarehouses = await window.DB.getAll('warehouses');
  currentUsers = await window.DB.getAll('users');
  currentContacts = await window.DB.getAll('contacts') || [];
  currentUnits = await window.DB.getAll('units') || [];
  allInvoices = await window.DB.getAll('transactions');
  allNotifications = await window.DB.getAll('notifications') || [];
  currentAccounts = await window.DB.getAll('accounts') || [];
  
  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');
  }

  currentJournals = await window.DB.getAll('journal_entries') || [];

  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.startsWith(today)).length;
  document.getElementById('stat-inventory-value').innerText = totalInventoryValue.toLocaleString('ar-EG', { maximumFractionDigits: 2 }) + ' ج.م';

  const myNotifs = allNotifications.filter(n => n.user === currentUser.username && !n.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;

  renderWarehouses(); renderContacts(); renderUnits(); renderUsers(); renderItems(); renderProjects(); 
  renderInvoices(); renderBalances(); renderNotifications(myNotifs); renderDecisions();
  renderProjectReports();
  if (typeof renderSales === 'function') renderSales();
  if (typeof renderPurchases === 'function') renderPurchases();
}

function populateDropdowns() {
  document.getElementById('invoice-item').innerHTML = currentItems.map(i => `<option value="${i.id}">${i.name}</option>`).join('');
  document.getElementById('invoice-contact').innerHTML = currentContacts.filter(c => c.type === 'مورد').map(c => `<option value="${c.id}">${c.name}</option>`).join('');
  document.getElementById('item-unit').innerHTML = 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.filter(c => c.type === 'عميل').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

  const filterBalance = document.getElementById('filter-warehouse-balance');
  let filterOptions = '';
  if (currentUser.role === 'مدير عام' || (currentUser.role === 'موظف مخصص' && userWhs.length !== 1)) {
    filterOptions = `<option value="all">كل المخازن المسموحة</option>` + userWhOptions;
  } else {
    filterOptions = userWhOptions;
  }
  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 = '';
    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 === 'مدير عام') 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 === 'مدير عام') 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 === 'مدير عام') 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 === 'مدير عام') 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.username}</td><td>${u.role}</td><td>${wh ? wh.name : 'الكل'}</td><td>${proj ? proj.name : 'بدون'}</td><td>${actions}</td></tr>`;
  });
}
function renderItems() {
  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));
      });
    }
  }

  filtered.forEach(i => { 
    let actions = '';
    if(currentUser.role === 'مدير عام') actions = `<button class="action-btn btn-edit" onclick="openItemModal(${i.id})">✏️ تعديل</button> <button class="action-btn btn-delete" onclick="deleteItem(${i.id})">🗑️ حذف</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>`; 
  });
}
window.openProjectDetails = function(id) {
  const p = currentProjects.find(x => x.id === 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> `;
    if(currentUser.role === 'مدير عام') {
       actions += `<button class="action-btn btn-edit" onclick="openProjectModal(${p.id})">✏️ تعديل</button> <button class="action-btn btn-delete" onclick="deleteProject(${p.id})">🗑️ حذف</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 from the official inventory transactions view
  filtered = filtered.filter(t => {
      if ((t.type === 'sales' || t.type === 'purchases') && (t.status === 'draft' || t.status === 'pending_store')) return false;
      return true;
  });
  
  if (currentUser.role === 'أمين مخزن' && currentUser.warehouse_id) {
    filtered = filtered.filter(t => t.warehouse_id === currentUser.warehouse_id || t.to_warehouse_id === currentUser.warehouse_id);
  } else if (currentUser.role === 'موظف مخصص' && currentUser.allowed_warehouses) {
    filtered = filtered.filter(t => currentUser.allowed_warehouses.includes(t.warehouse_id) || currentUser.allowed_warehouses.includes(t.to_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}) إلى (${t.to_warehouse_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>';

    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}</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 = `<button onclick="openReceiveModal(${n.invoice_id})" class="btn-primary">فتح الإذن</button>`;
    if (msg.includes('مشتريات') || msg.includes('مبيعات')) {
        actionBtn = `<button onclick="openStorekeeperReviewModal(${n.invoice_id}, '${n.date}')" class="btn-primary" style="background:var(--accent)">مراجعة واعتماد</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>`;
    }
    
    // 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.markNotifAsRead = async function(notifDate) {
  const n = allNotifications.find(x => x.date === notifDate);
  if(n) {
    n.read = true;
    await window.DB.update('notifications', n);
    const myNotifs = allNotifications.filter(x => x.user === currentUser.username && !n.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;
    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' ? 'مراجعة واستلام مشتريات' : 'مراجعة وصرف مبيعات';
  let info = `<strong>رقم المستند:</strong> #${inv.id} &nbsp;|&nbsp; <strong>النوع:</strong> ${inv.type === 'purchases' ? 'مشتريات' : 'مبيعات'}`;
  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.
  });
  
  inv.status = 'posted';
  await window.DB.update('transactions', inv);
  
  if (inv.type === 'sales') await generateSalesJournal(inv);
  else if (inv.type === 'purchases') await generatePurchasesJournal(inv);
  
  if (window.currentStorekeeperReviewNotifDate) {
    await markNotifAsRead(window.currentStorekeeperReviewNotifDate);
  }
  
  closeModal('storekeeper-review-modal');
  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;
    tbody.innerHTML += `<tr><td>${item.code}</td><td style="font-weight:bold">${item.name}</td><td>${b.avgCost.toLocaleString('ar-EG', {maximumFractionDigits:2})} ج.م</td><td style="font-weight:bold; color:var(--accent)">${displayQty} ${item.unit}</td><td style="color:var(--success)">${(displayQty * b.avgCost).toLocaleString('ar-EG', {maximumFractionDigits:2})} ج.م</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 (it.item_id === parseInt(itemId)) {
        if (inv.type === 'in' || inv.type === 'opening_balance') {
           records.push({ date: inv.date, inv: inv, type: inv.type==='in'?'وارد (مشتريات)':'رصيد أول', loc: inv.to_warehouse_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 === '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('ar-EG')}</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 = document.getElementById('invoice-item').value;
  let balLabel = document.getElementById('available-balance-label');
  if(!balLabel) {
    const parent = document.getElementById('invoice-item').parentElement;
    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[whId]) {
    balLabel.innerText = 'الرصيد المتاح حالياً في هذا المخزن: ' + bInfo.warehouses[whId].qty;
  } 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.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') || [];
    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.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.username}')">${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 = function(event) {
      const base64 = event.target.result;
      localStorage.setItem('company_logo', base64);
      applyLogo(base64);
    };
    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 === '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('ar-EG')}</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 === '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('ar-EG')}</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.filter(c=>c.type==='عميل').map(c => `<option value="${c.id}">${c.name}</option>`).join('');
  
  const whSel = document.getElementById('sales-warehouse');
  whSel.innerHTML = '<option value="">اختر المخزن...</option>' + currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  
  const projSel = document.getElementById('sales-project');
  projSel.innerHTML = '<option value="">بدون مشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  
  const itemSel = document.getElementById('sales-item');
  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 => x.id === 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';
    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';
    currentSalesLines = [];
  }
  
  document.getElementById('sales-qty').value = 1;
  document.getElementById('sales-price').value = 0;
  document.getElementById('sales-discount').value = 0;

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

window.addSalesLine = function() {
  const itemIdStr = document.getElementById('sales-item').value;
  if(!itemIdStr) { alert('اختر صنفاً أولاً'); return; }
  
  const itemId = parseInt(itemIdStr);
  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;
  
  currentSalesLines.push({ item_id: itemId, qty, price, discount });
  
  document.getElementById('sales-item').value = '';
  document.getElementById('sales-qty').value = 1;
  document.getElementById('sales-price').value = 0;
  document.getElementById('sales-discount').value = 0;
  
  renderSalesLines();
}

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

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

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);
      }
    } else {
      const newId = await window.DB.add('transactions', obj);
      obj.id = newId;
      if(status === 'posted') {
         await generateSalesJournal(obj);
      }
    }
    
    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 = currentAccounts.find(a => a.name === 'العملاء'); // Should be dynamic, but for now we look for generic "العملاء" or similar
  const salesAcc = currentAccounts.find(a => a.name === 'إيرادات المبيعات' || a.name === 'إيرادات مبيعات');
  const invAcc = currentAccounts.find(a => a.name === 'المخزون' || a.name === 'مخزون');
  const cogsAcc = currentAccounts.find(a => a.name === 'تكلفة البضاعة المباعة');
  
  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.filter(c=>c.type==='مورد').map(c => `<option value="${c.id}">${c.name}</option>`).join('');
  
  const whSel = document.getElementById('purchases-warehouse');
  whSel.innerHTML = '<option value="">اختر المخزن...</option>' + currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  
  const projSel = document.getElementById('purchases-project');
  projSel.innerHTML = '<option value="">بدون مشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  
  const itemSel = document.getElementById('purchases-item');
  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 => x.id === 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';
    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';
    currentPurchasesLines = [];
  }
  
  document.getElementById('purchases-qty').value = 1;
  document.getElementById('purchases-price').value = 0;
  document.getElementById('purchases-discount').value = 0;

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

window.addPurchasesLine = function() {
  const itemIdStr = document.getElementById('purchases-item').value;
  if(!itemIdStr) { alert('اختر صنفاً أولاً'); return; }
  
  const itemId = parseInt(itemIdStr);
  const qty = parseFloat(document.getElementById('purchases-qty').value) || 1;
  const price = parseFloat(document.getElementById('purchases-price').value) || 0;
  const discount = parseFloat(document.getElementById('purchases-discount').value) || 0;
  
  currentPurchasesLines.push({ item_id: itemId, qty, price, discount });
  
  document.getElementById('purchases-item').value = '';
  document.getElementById('purchases-qty').value = 1;
  document.getElementById('purchases-price').value = 0;
  document.getElementById('purchases-discount').value = 0;
  
  renderPurchasesLines();
}

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

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

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);
      }
    } else {
      const newId = await window.DB.add('transactions', obj);
      obj.id = newId;
      if(status === 'posted') {
         await generatePurchasesJournal(obj);
      }
    }
    
    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 = currentAccounts.find(a => a.name === 'الموردين');
  const invAcc = currentAccounts.find(a => a.name === 'المخزون' || a.name === 'مخزون');
  
  if(!supplierAcc || !invAcc) {
     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: invAcc.id, debit: invoice.total, credit: 0, project_id: invoice.project_id },
      { account_id: supplierAcc.id, debit: 0, credit: invoice.total, project_id: invoice.project_id }
    ]
  };
  
  await window.DB.add('journal_entries', journal);
}

window.sendInvoiceToStore = async function(invId) {
  const inv = allInvoices.find(x => x.id === 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.role === 'أمين مخزن');
  
  for (let sk of storekeepers) {
      const notifObj = {
        user: sk.username,
        invoice_id: inv.id,
        message: inv.type === 'purchases' ? 'إذن استلام مشتريات وارد لك للتأكيد' : 'إذن صرف مبيعات وارد لك للتأكيد',
        date: new Date().toISOString(),
        read: false
      };
      await window.DB.add('notifications', notifObj);
  }

  await loadData();
  alert('تم الإرسال للمخزن بنجاح.');
};


window.sendApproverNotifications = async function(newApproversStr, oldApproversStr, message, linkStr = null) {
    if (!newApproversStr) return;
    const newArr = newApproversStr.split(',').map(s=>s.trim()).filter(Boolean);
    const oldArr = (oldApproversStr || '').split(',').map(s=>s.trim()).filter(Boolean);
    
    for (const u of newArr) {
        if (!oldArr.includes(u)) {
            const notifObj = {
                user: u,
                message: message,
                date: new Date().toISOString(),
                read: false
            };
            if (linkStr) notifObj.link = linkStr;
            await window.DB.add('notifications', notifObj);
        }
    }
};
