const fs = require('fs');

// 1. Update index.html
let html = fs.readFileSync('d:/برنامج مخازن/index.html', 'utf8');

const missingModules = `
            <label class="perm-card"><input type="checkbox" class="perm-module" value="sales"> مبيعات</label>
            <label class="perm-card"><input type="checkbox" class="perm-module" value="purchases"> مشتريات</label>
            <label class="perm-card"><input type="checkbox" class="perm-module" value="accounting"> حسابات</label>
            <label class="perm-card"><input type="checkbox" class="perm-module" value="store"> إدارة المخازن (أمين المخزن)</label>
            <label class="perm-card"><input type="checkbox" class="perm-module" value="contractors"> عقود ومقاولين</label>
            <label class="perm-card"><input type="checkbox" class="perm-module" value="settlements"> عهد وتسويات</label>
            <label class="perm-card"><input type="checkbox" class="perm-module" value="vouchers"> سندات ومرتجعات</label>
`;

if (!html.includes('value="sales"')) {
    html = html.replace('value="units"> إدارة الوحدات</label>', 'value="units"> إدارة الوحدات</label>' + missingModules);
}

// Ensure the custom permissions group is ALWAYS displayed, regardless of role, except we can hide it for مدير عام in JS, but let's just make it always block
if (html.includes('id="custom-permissions-group" style="display:none;')) {
    html = html.replace('id="custom-permissions-group" style="display:none;', 'id="custom-permissions-group" style="display:block;');
}

fs.writeFileSync('d:/برنامج مخازن/index.html', html, 'utf8');
console.log('Updated index.html checkboxes.');


// 2. Update entities_module.js
let entities = fs.readFileSync('d:/برنامج مخازن/entities_module.js', 'utf8');

// Replace role-specific conditions for extracting allowed_modules
// We want EVERY role to save these.
const oldExtract = `      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)));
      }`;
const newExtract = `      
      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 (entities.includes(oldExtract)) {
    entities = entities.replace(oldExtract, newExtract);
} else if (entities.includes("if (role === 'مدير نظام')")) {
    entities = entities.replace(/if \(role === 'مدير نظام'\) \{\s*document\.querySelectorAll\('\.perm-module:checked'\)\.forEach\(cb => allowed_modules\.push\(cb\.value\)\);\s*document\.querySelectorAll\('\.perm-warehouse:checked'\)\.forEach\(cb => allowed_warehouses\.push\(parseInt\(cb\.value\)\)\);\s*document\.querySelectorAll\('\.perm-project:checked'\)\.forEach\(cb => allowed_projects\.push\(parseInt\(cb\.value\)\)\);\s*\}/g, newExtract);
}

// Replace role-specific project/warehouse binding
const oldWh = `const warehouse_id = role === 'أمين مخزن' ? parseInt(document.getElementById('user-warehouse').value) : null;`;
const newWh = `const warehouse_id = document.getElementById('user-warehouse') && document.getElementById('user-warehouse').value ? parseInt(document.getElementById('user-warehouse').value) : null;`;
entities = entities.replace(oldWh, newWh);

const oldProj = `const project_id = role === 'أمين مخزن' && document.getElementById('user-project').value ? parseInt(document.getElementById('user-project').value) : null;`;
const newProj = `const project_id = document.getElementById('user-project') && document.getElementById('user-project').value ? parseInt(document.getElementById('user-project').value) : null;`;
entities = entities.replace(oldProj, newProj);

// Remove the event listener that hides permissions
// We don't have to remove it if it's inline in index.html or bottom of app_final.js. Wait, let's just make sure it's block.

fs.writeFileSync('d:/برنامج مخازن/entities_module.js', entities, 'utf8');
console.log('Updated entities_module.js logic.');


// 3. Update app_final.js updateUIForRole
let appFinal = fs.readFileSync('d:/برنامج مخازن/app_final.js', 'utf8');

const oldUpdateUI = `function updateUIForRole() {
  const allNavs = ['nav-users', 'nav-warehouses', 'nav-items', 'nav-item-card', 'nav-projects', 'nav-project-reports', 'nav-balances', 'nav-transactions', 'nav-decisions', 'nav-sales', 'nav-purchases', 'nav-contacts', 'nav-settlements', 'nav-accounting', 'nav-vouchers'];
  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';
    document.getElementById('nav-contacts').style.display = 'block';
    document.getElementById('nav-settlements').style.display = 'block';
    document.getElementById('nav-accounting').style.display = 'block';
    document.getElementById('nav-vouchers').style.display = 'block';
  }
}`;

const newUpdateUI = `function updateUIForRole() {
  const allNavs = ['nav-users', 'nav-warehouses', 'nav-items', 'nav-item-card', 'nav-projects', 'nav-project-reports', 'nav-balances', 'nav-transactions', 'nav-decisions', 'nav-sales', 'nav-purchases', 'nav-contacts', 'nav-settlements', 'nav-custody-requests', 'nav-accounting', 'nav-vouchers', 'nav-contractors', 'nav-client-abstracts'];
  allNavs.forEach(nav => {
    const el = document.getElementById(nav);
    if(el) el.style.display = 'none';
  });
  const btnAddItem = document.getElementById('btn-add-item-modal');
  if(btnAddItem) btnAddItem.style.display = 'none';

  if (currentUser.role === 'مدير عام') {
    allNavs.forEach(nav => {
      const el = document.getElementById(nav);
      if(el) el.style.display = 'block';
    });
    if(btnAddItem) btnAddItem.style.display = 'inline-block';
    const cuWarehouse = document.getElementById('current-user-warehouse');
    if(cuWarehouse) cuWarehouse.innerText = 'كل المخازن';
  } else {
    // Strict permissions applied to EVERYONE ELSE
    const mods = currentUser.allowed_modules || [];
    if(mods.includes('users')) { const el = document.getElementById('nav-users'); if(el) el.style.display = 'block'; }
    if(mods.includes('warehouses')) { const el = document.getElementById('nav-warehouses'); if(el) el.style.display = 'block'; }
    if(mods.includes('contacts')) { const el = document.getElementById('nav-contacts'); if(el) el.style.display = 'block'; }
    if(mods.includes('units')) { const el = document.getElementById('nav-units'); if(el) el.style.display = 'block'; }
    
    if(mods.includes('items')) {
      const elItems = document.getElementById('nav-items'); if(elItems) elItems.style.display = 'block';
      const elCard = document.getElementById('nav-item-card'); if(elCard) elCard.style.display = 'block';
      if(btnAddItem) btnAddItem.style.display = 'inline-block';
    }
    
    if(mods.includes('projects')) { const el = document.getElementById('nav-projects'); if(el) el.style.display = 'block'; }
    if(mods.includes('project-reports')) { const el = document.getElementById('nav-project-reports'); if(el) el.style.display = 'block'; }
    if(mods.includes('balances')) { const el = document.getElementById('nav-balances'); if(el) el.style.display = 'block'; }
    if(mods.includes('transactions')) { 
      const el1 = document.getElementById('nav-transactions'); if(el1) el1.style.display = 'block';
      const el2 = document.getElementById('nav-decisions'); if(el2) el2.style.display = 'block';
    }
    
    if(mods.includes('sales')) { const el = document.getElementById('nav-sales'); if(el) el.style.display = 'block'; }
    if(mods.includes('purchases')) { const el = document.getElementById('nav-purchases'); if(el) el.style.display = 'block'; }
    if(mods.includes('accounting') || (currentUser.permissions || currentUser.allowed_actions || []).includes('approve-journals')) { const el = document.getElementById('nav-accounting'); if(el) el.style.display = 'block'; }
    if(mods.includes('store')) { const el = document.getElementById('nav-transactions'); if(el) el.style.display = 'block'; } // assuming nav-transactions is storekeeper dashboard
    if(mods.includes('contractors') || (currentUser.permissions || currentUser.allowed_actions || []).includes('approve-client-abstracts')) { 
      const el1 = document.getElementById('nav-contractors'); if(el1) el1.style.display = 'block';
      const el2 = document.getElementById('nav-client-abstracts'); if(el2) el2.style.display = 'block';
    }
    if(mods.includes('settlements') || (currentUser.permissions || currentUser.allowed_actions || []).includes('approve-settlements')) { const el = document.getElementById('nav-settlements'); if(el) el.style.display = 'block'; }
    if(mods.includes('custody-requests') || (currentUser.permissions || currentUser.allowed_actions || []).includes('approve-custody-requests')) { const el = document.getElementById('nav-custody-requests'); if(el) el.style.display = 'block'; }
    if(mods.includes('vouchers')) { const el = document.getElementById('nav-vouchers'); if(el) el.style.display = 'block'; }
    
    let whText = 'مخازن محددة';
    if(currentUser.allowed_warehouses && currentUser.allowed_warehouses.length > 0) whText = currentUser.allowed_warehouses.length + ' مخازن';
    else whText = 'غير مرتبط بمخازن';
    const cuWarehouse = document.getElementById('current-user-warehouse');
    if(cuWarehouse) cuWarehouse.innerText = whText;
  }
}`;

appFinal = appFinal.replace(/function updateUIForRole\(\) \{[\s\S]*?(?=\}\n\n\/\/ ---|\}\n\nfunction renderAccounts)/, newUpdateUI.slice(0, -1));

fs.writeFileSync('d:/برنامج مخازن/app_final.js', appFinal, 'utf8');
console.log('Updated app_final.js updateUIForRole.');

