const fs = require('fs');

// 1. Create save_fix.js
const saveFixContent = `
window.saveUserDebug = async function() {
    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 = 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 = [];
            
      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)));
      
      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(username && pass) { 
          const obj = { username, password: pass, role, warehouse_id, project_id, allowed_modules, allowed_warehouses, allowed_projects, 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(); 
          
          if(allowed_modules.length === 0) {
              alert("تم الحفظ بنجاح! ولكن انتبه: لم تقم باختيار أي شاشات! سيتم حجب كل شيء عن هذا المستخدم.");
          } else {
              alert("تم الحفظ بنجاح! الشاشات المختارة عددها " + allowed_modules.length + " وهي:\\n" + allowed_modules.join(', '));
          }
      } else { 
          alert('الرجاء إدخال اسم المستخدم وكلمة المرور!'); 
      }
    } catch(e) { 
      alert("خطأ أثناء الحفظ: " + e.message); 
    }
};
`;
fs.writeFileSync('d:/برنامج مخازن/save_fix.js', saveFixContent, 'utf8');

// 2. Modify index.html
let indexHtml = fs.readFileSync('d:/برنامج مخازن/index.html', 'utf8');
if (!indexHtml.includes('save_fix.js')) {
    indexHtml = indexHtml.replace('</body>', '  <script src="save_fix.js?v=' + Date.now() + '"></script>\n</body>');
}
if (!indexHtml.includes('onclick="window.saveUserDebug()"')) {
    indexHtml = indexHtml.replace('<button class="btn-primary" id="btn-save-user">', '<button class="btn-primary" id="btn-save-user" onclick="window.saveUserDebug()">');
}
fs.writeFileSync('d:/برنامج مخازن/index.html', indexHtml, 'utf8');

// 3. Strip listeners from entities_module.js and app_final.js to prevent double-saving
let entities = fs.readFileSync('d:/برنامج مخازن/entities_module.js', 'utf8');
// Comment out the listener for btn-save-user
entities = entities.replace(/newBtn\.addEventListener\('click',\s*async\s*\(\)\s*=>\s*\{[\s\S]*?\}\);/g, "/* listener moved to saveUserDebug */");
fs.writeFileSync('d:/برنامج مخازن/entities_module.js', entities, 'utf8');

let appFinal = fs.readFileSync('d:/برنامج مخازن/app_final.js', 'utf8');
// Comment out the listener for btn-save-user in app_final.js
appFinal = appFinal.replace(/document\.getElementById\('btn-save-user'\)\.addEventListener\('click',\s*async\s*\(\)\s*=>\s*\{[\s\S]*?\}\);/g, "/* listener moved to saveUserDebug */");
fs.writeFileSync('d:/برنامج مخازن/app_final.js', appFinal, 'utf8');

console.log("Save fix injected successfully.");
