window.saveUserDebug = async function() {
    try {
      const editIdStr = document.getElementById('edit-user-id').value;
      const username = document.getElementById('user-username').value;
      let pass = document.getElementById('user-password').value;
      const role = document.getElementById('user-role').value;
      
      const warehouse_id = document.getElementById('user-warehouse') && document.getElementById('user-warehouse').value ? parseInt(document.getElementById('user-warehouse').value) : null;
      const project_id = document.getElementById('user-project') && document.getElementById('user-project').value ? parseInt(document.getElementById('user-project').value) : null;
      
      let allowed_modules = [];
      let allowed_warehouses = [];
      let allowed_projects = [];
      let allowed_actions = []; // <--- NEW PERMISSIONS
            
      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)));
      document.querySelectorAll('.perm-action:checked').forEach(cb => allowed_actions.push(cb.value)); // <--- COLLECT PERMISSIONS
      
      let custody_account_id = document.getElementById('user-custody') ? document.getElementById('user-custody').value : null;
      if (custody_account_id) custody_account_id = parseInt(custody_account_id);
      
      if (!custody_account_id && username) {
          let accName = 'عهدة - ' + username;
          let existingAcc = window.currentAccounts ? window.currentAccounts.find(a => a.name === accName) : null;
          if (existingAcc) {
              custody_account_id = existingAcc.id;
          } else if (window.currentAccounts) {
              let parent = window.currentAccounts.find(a => a.name === 'الأصول' || a.name === 'أصول متداولة' || (a.name.includes('أصول') && (!a.parent_id || a.type === 'رئيسي')));
              if (!parent) {
                  let assetsAcc = window.currentAccounts.find(a => a.name.includes('أصول') && !a.parent_id);
                  parent = {
                      id: Date.now() - 1000,
                      name: 'أصول متداولة',
                      code: assetsAcc ? assetsAcc.code + '99' : '199',
                      type: 'رئيسي',
                      parent_id: assetsAcc ? assetsAcc.id : null
                  };
                  await window.DB.add('accounts', parent);
                  window.currentAccounts.push(parent);
              }
              const newAcc = {
                  id: Date.now(),
                  name: accName,
                  code: parent ? parent.code + Math.floor(Math.random() * 100) : Math.floor(Math.random() * 100000).toString(),
                  type: 'فرعي',
                  parent_id: parent ? parent.id : null
              };
              await window.DB.add('accounts', newAcc);
              window.currentAccounts.push(newAcc);
              custody_account_id = newAcc.id;
          }
      }
      
      if(editIdStr) {
          // Editing existing user - جلب المستخدم من DB مباشرة لضمان الحصول على البيانات
          let existingUser = (window.currentUsers||[]).find(u => String(u.id) === editIdStr);
          if (!existingUser) {
              try {
                  const allUsers = await window.DB.getAll('users');
                  window.currentUsers = allUsers;
                  existingUser = allUsers.find(u => String(u.id) === editIdStr);
              } catch(e) {}
          }
          if (!existingUser) { alert('خطأ: لم يتم العثور على بيانات المستخدم.'); return; }

          // Password protection logic
          const isSuperAdmin = (existingUser.role === 'مدير عام' || existingUser.role === 'مدير نظام');
          if (isSuperAdmin && window.currentUser && String(window.currentUser.id) !== String(existingUser.id)) {
              pass = existingUser.password;
          } else if (!pass) {
              pass = existingUser.password;
          }
      }
      
      if(username && pass) { 
          const obj = { username, password: pass, role, warehouse_id, project_id, allowed_modules, allowed_warehouses, allowed_projects, allowed_actions, custody_account_id };
          if(editIdStr) { 
              obj.id = parseInt(editIdStr); 
              await window.DB.update('users', obj); 
          } else { 
              await window.DB.add('users', obj); 
          }
          closeModal('user-modal'); 
          await loadData(); 
          alert("تم حفظ بيانات المستخدم بنجاح.");
      } else { 
          alert('الرجاء إدخال اسم المستخدم وكلمة المرور!'); 
      }
    } catch(e) { 
      alert("خطأ أثناء الحفظ: " + e.message); 
    }
};
