const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    
    // 1. Populate the user-custody dropdown in openUserModal
    const openUserModalRegex = /window\.openUserModal\s*=\s*function\(id\s*=\s*null\)\s*\{([^]*?)(if\s*\(\s*isEdit\s*\)\s*\{)/;
    const match = js.match(openUserModalRegex);
    if (match) {
        const custodyPopulation = `  const custodySel = document.getElementById('user-custody');
  if (custodySel) {
      custodySel.innerHTML = '<option value="">-- إنشاء حساب عهدة تلقائياً --</option>' + 
          currentAccounts.filter(a => a.name.includes('عهد')).map(a => \`<option value="\${a.id}">\${a.name}</option>\`).join('');
  }
  `;
        js = js.replace(match[0], match[0].replace(match[2], custodyPopulation + match[2]));
    }
    
    // 2. Set the selected value if isEdit
    const editUserRegex = /if\s*\(u\.project_id\)\s*document\.getElementById\('user-project'\)\.value\s*=\s*u\.project_id;\s*else\s*document\.getElementById\('user-project'\)\.value\s*=\s*'';/;
    if (js.match(editUserRegex)) {
        js = js.replace(editUserRegex, `if(u.project_id) document.getElementById('user-project').value = u.project_id;
    else document.getElementById('user-project').value = '';
    if(u.custody_account_id && document.getElementById('user-custody')) document.getElementById('user-custody').value = u.custody_account_id;
    else if(document.getElementById('user-custody')) document.getElementById('user-custody').value = '';`);
    }

    // 3. Update btn-save-user to read custody_account_id and auto-create
    const saveUserRegex = /const obj = \{ username, password: pass, role, warehouse_id, project_id, allowed_modules, allowed_warehouses, allowed_projects \};/g;
    
    // First, we need to inject the custody_account_id logic right before "if(username && pass)"
    const ifUserPassRegex = /if\(\s*username\s*&&\s*pass\s*\)\s*\{/;
    
    const autoCreateLogic = `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 = currentAccounts.find(a => a.name === accName);
          if (existingAcc) {
              custody_account_id = existingAcc.id;
          } else {
              let parent = currentAccounts.find(a => a.name === 'العهد' || a.name === 'عهد الموظفين') || currentAccounts.find(a => a.name.includes('عهد') && a.type === 'رئيسي');
              if (!parent) parent = currentAccounts.find(a => a.name.includes('صول') && a.type === 'رئيسي');
              
              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);
              currentAccounts.push(newAcc);
              custody_account_id = newAcc.id;
          }
      }
      
      if(username && pass) {`;
      
    js = js.replace(ifUserPassRegex, autoCreateLogic);
    
    // Replace the obj creation
    js = js.replace(saveUserRegex, "const obj = { username, password: pass, role, warehouse_id, project_id, allowed_modules, allowed_warehouses, allowed_projects, custody_account_id };");

    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Patched user custody in app_final.js');
}

// Cache buster
let html = fs.readFileSync('index.html', 'utf8');
html = html.replace(/v=\d+/g, 'v=' + Date.now());
fs.writeFileSync('index.html', html, 'utf8');
