<!-- Header Navigation Bar -->

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">


<div class="top-navbar">
    <div class="navbar-left">
      <div class="brand-logo">
        <img id="brandLogo" src="/uploads/cyber.jpeg" alt="Brand Logo" />
      </div>
      <span class="brand-name" id="brandName">Restaurant </span>
    </div>
  
    <div class="navbar-center-and-right">
      <div>
        <button class="toggle-sidebar-btn"><i class="fas fa-bars"></i></button>
      </div>
  
      <div class="navbar-right">

      
        

        <div> <span id="branchNameDisplay" style="color: rgb(45, 98, 172);"></span></div>
        <div>
        
          <select id="allowedBranchList"  name="allowedBranchList" style="color: rgb(45, 98, 172);">
            <!-- Options will be dynamically populated -->
          </select>
        </div>
        <div class="user-profile">
          <img id="userAvatar" src="/uploads/cyber.jpeg" alt="User Avatar" class="user-avatar" />
          <span class="username">
            Hello, 
            <% if (!user) { %>
              <% if(currentPage!='forgot-password-page') { %>
              <script>
                window.location.href = '/';
              </script>
            <% } } else { %>
              <%- user.username %>
            <% } %>
          </span>
          
          <div class="dropdown">
            <button class="dropdown-toggle">Options <i class="fas fa-caret-down"></i></button>
            <div class="dropdown-menu">
              <button onclick=' redirectToChangePassword() '>Change Password</button>
              <button onclick="logout()">Logout</button>
            </div>
          </div>
        </div>
  
        <div class="notifications">
          <i class="fas fa-bell"></i>
          <span class="badge"></span>
        </div>
      </div>
    </div>
  </div>
  
<script>
    const user = <%- JSON.stringify(user || null) %>;
    console.log("user is",user);
    const userPermissions=user.permission;

   
  </script>
<script>
    const branchName = sessionStorage.getItem('branchName');
    document.addEventListener("DOMContentLoaded", function () {
     // document.getElementById('branchNameDisplay').textContent = branchName || 'No branch selected';
  
      const allowedBranchId = JSON.parse(sessionStorage.getItem('allowedBranchId'));
      console.log(allowedBranchId);

const allowedBranchDropdown = document.getElementById('allowedBranchList');


const branchId = sessionStorage.getItem('branchId');
// Clear existing options if any
allowedBranchDropdown.innerHTML = '';

// Populate the dropdown with only allowed branches
allowedBranchId.forEach(branch => {
  const option = document.createElement('option');
  option.value = branch.id; // Set branch ID as the value
  option.textContent = branch.name; // Display branch name
  if(branchId ===branch.id)
  {option.selected = true; // Pre-select the option
  }
  allowedBranchDropdown.appendChild(option);


});

  
  
    });

    const allowedBranchDropdown = document.getElementById('allowedBranchList');

    allowedBranchDropdown.addEventListener('change', () => {
   switchBranch();
});



    function redirectToChangePassword() {
    window.location.href = '/change-password'; // Replace with the actual route to your change password page
  }


function switchBranch(){
  const selectedOption = allowedBranchDropdown.options[allowedBranchDropdown.selectedIndex];
 // branchNameDisplay.textContent = selectedOption.textContent || 'No branch selected';
 
  sessionStorage.setItem('branchName', selectedOption.textContent);    
 sessionStorage.setItem('branchId', selectedOption.value);
 window.location.href = window.location.href;

}


    function changePassword() {
  const newPassword = prompt('Enter your new password:');
  if (newPassword) {
    // Send the new password to the server
    fetch('/api/auth/change-password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ password: newPassword }),
    })
      .then((response) => {
        if (response.ok) {
          alert('Password changed successfully!');
        } else {
          alert('Error changing password. Please try again.');
        }
      })
      .catch((err) => {
        console.error('Error:', err);
        alert('Error changing password. Please try again.');
      });
  }
}

function logout() {
  // Send logout request to the server
  fetch('/api/auth/logout', { method: 'POST' })
    .then((response) => {
      if (response.ok) {
        // Redirect to login page after successful logout
        window.location.href = '/login';
      } else {
        alert('Error logging out. Please try again.');
      }
    })
    .catch((err) => {
      console.error('Error:', err);
      alert('Error logging out. Please try again.');
    });
  }

  // Load and display company name and logo
  (async function() {
    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');
    
    if (companyId && branchId) {
      try {
        const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
        if (response.ok) {
          const data = await response.json();
          if (data.companyName) {
            localStorage.setItem('companyName', data.companyName);
            updateBrandName(data.companyName);
          }
          if (data.companyLogo) {
            localStorage.setItem('companyLogo', data.companyLogo);
            updateLogo(data.companyLogo);
          }
        }
      } catch (error) {
        console.error('Error loading company settings:', error);
      }
    }
    
    // Fallback to localStorage or default
    const companyName = localStorage.getItem('companyName') || 'Zad';
    const companyLogo = localStorage.getItem('companyLogo') || '/uploads/cyber.jpeg';
    updateBrandName(companyName);
    updateLogo(companyLogo);
  })();
  
  function updateBrandName(companyName) {
    const brandElement = document.getElementById('brandName');
    if (brandElement) {
      brandElement.textContent = companyName + ' Restaurant ';
    }
  }

  function updateLogo(logoPath) {
    const brandLogo = document.getElementById('brandLogo');
    const userAvatar = document.getElementById('userAvatar');
    if (brandLogo) {
      brandLogo.src = logoPath;
    }
    if (userAvatar) {
      userAvatar.src = logoPath;
    }
  }

  </script>

