<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title> DMS 2025</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap 5 -->
  <link rel="stylesheet" href="<?= base_url('public/assets/css/bootstrap.min.css') ?>">
  <!-- FontAwesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <link rel="stylesheet" href="<?= base_url('public/assets/css/newstyle.css') ?>">

  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
  
  <style>
    /* Sidebar Toggle Button */
    .sidebar-toggle-btn {
      background: none;
      border: none;
      color: #64748b;
      font-size: 1.25rem;
      padding: 0.5rem 0.75rem;
      margin-right: 0.75rem;
      cursor: pointer;
      border-radius: 8px;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .sidebar-toggle-btn:hover {
      background: #f1f5f9;
      color: #1e3a5f;
    }
    
    /* Collapsed Sidebar Styles */
    .sidebar {
      transition: width 0.3s ease;
    }
    
    .sidebar.collapsed {
      width: 70px !important;
      overflow: hidden;
    }
    
    .sidebar.collapsed .brand {
      padding: 1rem 0.5rem;
      justify-content: center;
    }
    
    .sidebar.collapsed .brand-text,
    .sidebar.collapsed .link-text,
    .sidebar.collapsed .arrow-icon {
      display: none !important;
    }
    
    .sidebar.collapsed .nav-link {
      padding: 0.75rem;
      justify-content: center;
      text-align: center;
    }
    
    .sidebar.collapsed .nav-link i {
      margin-right: 0;
      font-size: 1.2rem;
    }
    
    /* Collapsed sidebar - Masters flyout submenu */
    .sidebar.collapsed .nav-item {
      position: relative;
    }
    
    .sidebar.collapsed .masters-submenu {
      display: none;
      position: absolute;
      left: 100%;
      top: 0;
      background: #1e293b;
      min-width: 220px;
      border-radius: 8px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.3);
      padding: 8px 0;
      margin-left: 10px;
      z-index: 1100;
    }
    
    .sidebar.collapsed .masters-submenu::before {
      content: '';
      position: absolute;
      left: -10px;
      top: 12px;
      border: 6px solid transparent;
      border-right-color: #1e293b;
    }
    
    .sidebar.collapsed .nav-item:hover .masters-submenu {
      display: block !important;
    }
    
    .sidebar.collapsed .masters-submenu .nav {
      margin-left: 0 !important;
    }
    
    .sidebar.collapsed .masters-submenu .nav-link {
      padding: 10px 16px !important;
      justify-content: flex-start !important;
      text-align: left !important;
      color: #94a3b8;
      font-size: 0.85rem;
      border-radius: 0;
    }
    
    .sidebar.collapsed .masters-submenu .nav-link,
    .sidebar.collapsed .masters-submenu ul li a.nav-link {
      cursor: default !important;
      background: transparent !important;
    }
    
    .sidebar.collapsed .masters-submenu .nav-link:hover,
    .sidebar.collapsed .masters-submenu ul li a.nav-link:hover {
      background: transparent !important;
      color: #94a3b8 !important;
    }
    
    .sidebar.collapsed .masters-submenu .nav-link.active,
    .sidebar.collapsed .masters-submenu ul li a.nav-link.active {
      background: rgba(59, 130, 246, 0.2) !important;
      color: #3b82f6 !important;
    }
    
    .sidebar.collapsed .masters-submenu .nav-link i {
      margin-right: 10px !important;
      width: 18px;
      text-align: center;
    }
    
    .sidebar.collapsed .masters-toggle {
      justify-content: center;
    }
    
    /* Active indicator for Masters when submenu item is active (collapsed mode) */
    .sidebar.collapsed .masters-toggle.has-active-child {
      background: rgba(59, 130, 246, 0.15) !important;
      border-left: 3px solid #3b82f6;
    }
    
    .sidebar.collapsed .masters-toggle.has-active-child i {
      color: #3b82f6 !important;
    }
    
    /* Active submenu name tooltip on hover for collapsed sidebar */
    .sidebar.collapsed .masters-toggle.has-active-child::after {
      content: attr(data-active-submenu);
      position: absolute;
      left: 100%;
      top: 50%;
      transform: translateY(-50%);
      background: #3b82f6;
      color: #fff;
      padding: 0.4rem 0.75rem;
      border-radius: 6px;
      font-size: 0.75rem;
      white-space: nowrap;
      margin-left: 10px;
      z-index: 999;
      box-shadow: 0 2px 8px rgba(59,130,246,0.3);
      opacity: 0;
      transition: opacity 0.2s;
      pointer-events: none;
    }
    
    .sidebar.collapsed .masters-toggle.has-active-child:hover::after {
      opacity: 0; /* Hide default tooltip when flyout shows */
    }
    
    /* Small dot indicator for active submenu */
    .sidebar.collapsed .masters-toggle.has-active-child::before {
      content: '';
      position: absolute;
      top: 8px;
      right: 8px;
      width: 8px;
      height: 8px;
      background: #3b82f6;
      border-radius: 50%;
      box-shadow: 0 0 6px rgba(59,130,246,0.6);
    }
    
    /* Adjust dashboard container when sidebar is collapsed */
    body.sidebar-collapsed .dashboard-container {
      margin-left: 70px !important;
    }
    
    /* Tooltip for collapsed sidebar items */
    .sidebar.collapsed .nav-link {
      position: relative;
    }
    
    .sidebar.collapsed .nav-link:hover::after {
      content: attr(data-title);
      position: absolute;
      left: 100%;
      top: 50%;
      transform: translateY(-50%);
      background: #1e293b;
      color: #fff;
      padding: 0.5rem 0.75rem;
      border-radius: 6px;
      font-size: 0.8rem;
      white-space: nowrap;
      margin-left: 10px;
      z-index: 1000;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    }
    
    .sidebar.collapsed .nav-link:hover::before {
      content: '';
      position: absolute;
      left: 100%;
      top: 50%;
      transform: translateY(-50%);
      border: 6px solid transparent;
      border-right-color: #1e293b;
      margin-left: -2px;
      z-index: 1000;
    }
  </style>
  <!-- code for curve background ends here -->
    
    <script src="<?= base_url('public/assets/js/jquery-3.6.0.min.js') ?>"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <!--<script src="<?= base_url('public/assets/js/script.js') ?>"></script>-->
    <script src="<?= base_url('public/assets/js/bootstrap-datepicker.min.js') ?>"></script>

    <!-- js and css for dashboard -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- ends here for dashboard -->
    
<!-- Page Loader Styles - Must be in head to work on initial load -->
<style>
#page-loader-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.95);
    z-index: 999999;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: opacity 0.3s ease, visibility 0.3s ease;
}
#page-loader-overlay.hidden {
    opacity: 0;
    visibility: hidden;
    pointer-events: none;
}
.page-loader-box {
    text-align: center;
}
.page-loader-box .spinner {
    width: 50px;
    height: 50px;
    border: 4px solid #e2e8f0;
    border-top-color: #3b82f6;
    border-radius: 50%;
    animation: page-spin 0.8s linear infinite;
    margin: 0 auto 12px;
}
@keyframes page-spin {
    to { transform: rotate(360deg); }
}
.page-loader-box .loader-text {
    color: #64748b;
    font-size: 14px;
    font-weight: 500;
}
/* Gray out content while loading */
body.page-loading .content,
body.page-loading .dashboard-container,
body.page-loading .sidebar,
body.page-loading .topbar {
    filter: grayscale(30%);
    pointer-events: none;
}
</style>

</head>
<?php
// Determine if this is a page that needs initial loading state
$needs_loader = in_array($this->uri->segment(1) . '/' . $this->uri->segment(2), [
    'dashboard/',
    'company/newDocuments', 
    'company/view_documents',
    'company/new_documents'
]) || $this->uri->segment(1) === 'dashboard';
?>
<body class="<?= $needs_loader ? 'page-loading' : '' ?>">

<?php if ($needs_loader): ?>
<!-- Page Loader Overlay - Shown immediately for dashboard/view documents -->
<div id="page-loader-overlay">
    <div class="page-loader-box">
        <div class="spinner"></div>
        <div class="loader-text">Loading...</div>
    </div>
</div>
<script>
// Hide loader when page fully loads
window.addEventListener('load', function() {
    setTimeout(function() {
        var loader = document.getElementById('page-loader-overlay');
        if (loader) {
            loader.classList.add('hidden');
            document.body.classList.remove('page-loading');
        }
    }, 300);
});
</script>
<?php endif; ?>

<?php

// Current menu info
//$current_menu = $this->uri->segment(1);
//$current_sub_menu = $this->uri->segment(1) . '/' . $this->uri->segment(2);

$current_menu     = $this->uri->segment(1);
$current_method   = $this->uri->segment(2);
$current_sub_menu = $current_menu . '/' . $current_method;

/**
 * Pages where company_id is EXPECTED in URL
 * (context-setting pages only)
 */
$company_context_pages = [
    'authority/index',
    'type/allType',
    'type/reorder_all',
    'document/groupList',
    'document/allDocuments',
    'upload/index',
    'company/newDocuments',
    'upload/reminder',
    'report/reminder'
];

// Default: use session value
$company_id = $this->session->userdata('company_id');

// Update session ONLY for context pages (NOT dashboard - dashboard has its own dropdown)
if (in_array($current_sub_menu, $company_context_pages)) {
    $url_company_id = $this->uri->segment(3);
    if (is_numeric($url_company_id)) {
        $company_id = (int) $url_company_id;
        $this->session->set_userdata('company_id', $company_id);
    }
}
$company_name = $company_id ? get_company_name($company_id) : ''

/*
// Get the first segment of URL (controller name)
  $current_menu = $this->uri->segment(1);
  $current_sub_menu = $this->uri->segment(1) . '/' . $this->uri->segment(2);
  
  // Get company_id from session first (controller should have set it)
  // Only try URL segment as fallback for specific patterns
  $company_id = $this->session->userdata('company_id');
  
  // If session doesn't have company_id, try URL segments based on URL pattern
  if (empty($company_id)) {
      $segment2 = $this->uri->segment(2);
      // For URLs like /type/allType/14 or /authority/index/14 - company_id is segment 3
      if (in_array($segment2, ['allType', 'index', 'allDocuments', 'companies'])) {
          $company_id = $this->uri->segment(3);
      }
      // For URLs like /type/editType/62/14 - company_id is segment 4
      elseif (in_array($segment2, ['editType', 'viewType', 'editDocument', 'edit'])) {
          $company_id = $this->uri->segment(4);
      }
      // Default: try segment 3
      else {
          $company_id = $this->uri->segment(3);
      }
      
      // If found in URL, set to session
      if ($company_id) {
          $this->session->set_userdata('company_id', $company_id);
      }
  }

  $company_name = '';
  if ($company_id) {
      $company_name = get_company_name($company_id);
  } */
?>

<?php /*
echo "<pre>";
echo "MENU: " . ($current_menu ?? 'null') . "\n";
echo "SUBMENU: " . ($current_sub_menu ?? 'null') . "\n";
echo "</pre>"; */
?>

<!-- Sidebar -->
<div class="sidebar" id="sidebar">
    <div class="brand">
      <i class="fa-solid fa-file-lines"></i>
      <span class="brand-text">DMS 2025</span>
    </div>

  <!-- Dashboard -->
  <a class="nav-link <?= ($current_menu == 'dashboard') ? 'active' : '' ?>" href="<?= base_url('dashboard') ?>" style="cursor: default !important;" data-title="Dashboard">
      <i class="fa-solid fa-gauge"></i>
      <span class="link-text">Dashboard</span>
  </a>
    
  <!-- Masters Dropdown -->
<?php 
$isMasterActive = isset($isMasterActive) ? $isMasterActive : false; 

$full_name = $this->session->userdata('full_name');
$disableMaster = ($full_name === 'Rajesh'); 

// Determine which submenu is active for collapsed sidebar indicator
$activeSubmenuName = '';
$hasMasterSubActive = false;
if (in_array($current_menu, ['authority', 'type', 'company', 'document', 'role', 'users', 'user', 'holiday']) && $current_sub_menu != 'company/newDocuments') {
    $hasMasterSubActive = true;
    if ($current_menu == 'authority') $activeSubmenuName = 'Authority';
    elseif ($current_menu == 'type' && in_array($current_sub_menu, ['type/allType', 'type/addType', 'type/editType'])) $activeSubmenuName = 'Document Head';
    elseif ($current_sub_menu == 'type/reorder_all') $activeSubmenuName = 'Re-order Doc Head';
    elseif ($current_menu == 'company') $activeSubmenuName = 'Company';
    elseif (in_array($current_sub_menu, ['document/groupList', 'document/addDocumentGroup'])) $activeSubmenuName = 'Document Group';
    elseif (in_array($current_sub_menu, ['document/allDocuments', 'document/addDocument'])) $activeSubmenuName = 'Document';
    elseif ($current_menu == 'role') $activeSubmenuName = 'User Role';
    elseif (in_array($current_menu, ['users', 'user'])) $activeSubmenuName = 'User';
    elseif ($current_menu == 'holiday') $activeSubmenuName = 'Holidays';
}

// View-only users (is_user() returns true for role_id=3 with no edit permission)
$is_view_only = function_exists('is_user') && is_user() && function_exists('can_edit') && !can_edit();
// User role (role_id=3) - restricted to only assigned masters
$is_user_role = function_exists('is_user') && is_user();

if (!$disableMaster): ?>
    <!-- Master menu - User role only sees: Authority, Document Head, Documents, Document Group, Reorder Documents -->
  <div class="nav-item">
    <a 
      class="nav-link masters-toggle <?= $isMasterActive ? 'active' : '' ?> <?= $hasMasterSubActive ? 'has-active-child' : '' ?>" 
      href="javascript:void(0);"
      id="mastersToggleBtn"
      data-title="Masters<?= $activeSubmenuName ? ' → ' . $activeSubmenuName : '' ?>"
      data-active-submenu="<?= $activeSubmenuName ?>"
    >
      <i class="fa-solid fa-sitemap"></i>
      <span class="link-text">Masters</span>
      <i class="fa-solid fa-angle-down ms-auto arrow-icon"></i>
    </a>

    <div id="mastersMenu" class="masters-submenu <?= (in_array($current_menu, ['authority', 'type', 'company', 'document', 'holiday']) 
        && $current_sub_menu != 'company/newDocuments') ? 'open' : '' ?>">
      <ul class="nav flex-column ms-3">
          <!-- Document Head - shown to all -->
          <li>
              <a class="nav-link submenu-link
                  <?= (
                        $current_menu == 'type' && 
                        in_array($current_sub_menu, [
                              'type/allType', 
                              'type/addType', 
                              'type/editType'
                        ])
                  ) ? 'active' : '' 
                  ?>" 
                  href="<?= base_url('type') ?>" style="cursor: default !important;">
                  
                  <i class="fa-solid fa-diagram-project"></i> Document Head
              </a>
          </li>
          <!-- Authority - shown to all -->
          <li>
          <a class="nav-link submenu-link <?= ($current_menu == 'authority') ? 'active' : '' ?>" href="<?= base_url('authority') ?>" style="cursor: default !important;">
                  <i class="fa-solid fa-building"></i> Authority
              </a>
          </li>
          <!-- Document - shown to all -->
          <li>
              <a class="nav-link submenu-link <?= ($current_sub_menu == 'document/allDocuments' || $current_sub_menu == 'document/addDocument') ? 'active' : '' ?>" href="<?= base_url('document/allDocuments') ?>" style="cursor: default !important;">
                  <i class="fa-solid fa-file"></i> Document
              </a>
          </li>
          <!-- Reorder Documents - shown to all -->
          <li>
              <a class="nav-link submenu-link <?= ($current_menu == 'type' && $current_sub_menu == 'type/reorder_all') ? 'active' : '' ?>"
                href="<?= base_url('type/reorder_all') ?>" style="cursor: default !important;">
                  <i class="fa-solid fa-arrow-up-short-wide"></i> Reorder Documents
              </a>
          </li>
          <!-- Document Group - shown to all -->
          <li>
              <a class="nav-link submenu-link <?= ($current_sub_menu == 'document/groupList' || $current_sub_menu == 'document/addDocumentGroup') ? 'active' : '' ?>" href="<?= base_url('document/groupList') ?>" style="cursor: default !important;">
                  <i class="fa-solid fa-file"></i> Document Group
              </a>
          </li>
          <?php if (!$is_user_role): ?>
          <!-- User, Holidays - hidden for User role (role_id=3) -->
          <li>
              <a class="nav-link submenu-link <?= ($current_menu == 'users') ? 'active' : '' ?>" href="<?= base_url('user') ?>" style="cursor: default !important;">
                  <i class="fa-solid fa-user"></i> User
              </a>
          </li>
          <li>
              <a class="nav-link submenu-link <?= ($current_menu == 'holiday') ? 'active' : '' ?>" href="<?= base_url('holiday') ?>" style="cursor: default !important;">
                  <i class="fa-solid fa-calendar-alt"></i> Holidays
              </a>
          </li>
          <?php endif; ?>
          <?php if (is_super_admin()): ?>
          <li>
              <a class="nav-link submenu-link <?= ($current_menu == 'company') ? 'active' : '' ?>" href="<?= base_url('company') ?>" style="cursor: default !important;">
                  <i class="fa-solid fa-industry"></i> Company
              </a>
          </li>
          <?php endif; ?>
          <?php if (function_exists('can') && can('company_doc_heads.view')): ?>
          <?php 
          $pending_count = 0;
          try {
              if (function_exists('get_pending_doc_heads_count')) {
                  $pending_count = get_pending_doc_heads_count();
              }
          } catch (Exception $e) {
              $pending_count = 0;
          }
          ?>
          <!--<li>
              <a class="nav-link submenu-link <?= ($current_menu == 'company_doc_heads') ? 'active' : '' ?>" href="javascript:void(0);" onclick="openCompanyDocHeadsModal()" style="cursor: default !important;">
                  <i class="fa-solid fa-tasks"></i> Company Doc Heads <?php if ($pending_count > 0): ?><span class="badge bg-danger rounded-pill" style="font-size: 0.65rem;"><?= $pending_count > 99 ? '99+' : $pending_count ?></span><?php endif; ?>
              </a>
          </li>-->
          <?php endif; ?>
          
          <?php if (is_super_admin()): ?>
          <li>
              <!-- User & Role Management - Super Admin only -->
              <a class="nav-link submenu-link <?= ($current_menu == 'role') ? 'active' : '' ?>" href="<?= base_url('role') ?>" style="cursor: default !important;">
                  <i class="fa-solid fa-users-gear"></i> User Role
              </a>
          </li>
          <?php endif; ?>
          
      </ul>
    </div>
  </div>
<?php endif; ?>

  <!-- Upload Documents - Hidden for view-only users -->
  <?php if (!$is_view_only): ?>
  <a class="nav-link <?= ($current_menu == 'upload') ? 'active' : '' ?>" href="<?= base_url('upload') ?>" id="uploadMenu" data-title="Upload Documents">
      <i class="fa-solid fa-upload"></i>
      <span class="link-text">Upload Documents</span>
  </a>
  <?php endif; ?>

  <!-- View Documents -->
  <a class="nav-link <?= ($current_sub_menu == 'company/newDocuments') ? 'active' : '' ?>" href="<?= base_url('upload/view') ?>" id="viewMenu" data-title="View Documents">
      <i class="fa-solid fa-eye"></i>
      <span class="link-text">View Documents</span>
  </a>

  <!-- Reminders -->
  <!--<a class="nav-link <?= ($current_menu == 'upload/reminder') ? 'active' : '' ?>" href="<?= base_url('upload/reminder') ?>" id="reminders" data-title="Reminders">
      <i class="fa-solid fa-bell"></i>
      <span class="link-text">Reminders</span>
  </a>-->

  <a class="nav-link <?= ($current_menu == 'report/reminder') ? 'active' : '' ?>" href="<?= base_url('report/reminder') ?>" id="complianceStatus" data-title="Compliance Status">
      <i class="fa-solid fa-clipboard-check"></i>
      <span class="link-text">Compliance Status</span>
  </a>

  <?php if (is_super_admin() || is_admin()): ?>
  <a class="nav-link <?= ($current_menu == 'reminder') ? 'active' : '' ?>" href="<?= base_url('reminder/report') ?>" data-title="Reminder Report">
      <i class="fa-solid fa-bell"></i>
      <span class="link-text">Reminder Report</span>
  </a>
  <?php endif; ?>

</div>
<div class="topbar">
  <button type="button" class="sidebar-toggle-btn" id="sidebarToggleBtn" onclick="toggleSidebar()" title="Toggle Sidebar">
    <i class="fa fa-bars"></i>
  </button>
  <h3>
    <?php 
        if ($current_sub_menu === 'company/newDocuments') {
            echo ($company_name ?: "Select Company") . " / View";
        }

        // Special label for Upload Documents
        else if ($current_sub_menu === 'upload/index') {
            echo ($company_name ?: "Select Company") . " / Upload";
        }

        // Document Head static name
        else if (
            $current_menu === 'type' &&
            in_array($current_sub_menu, [
                'type/allType',
                'type/addType',
                'type/editType'
            ])
        ) {
          echo ($company_name ?: "Select Company") . " / Document Head";
        }

        else if ($current_sub_menu === 'type/reorder_all') {
            echo ($company_name ?: "Select Company") ." / Reorder Documents";
        }

        // Compliance Status Report
        else if ($current_sub_menu === 'report/reminder' || $current_menu === 'report/reminder') {
            echo ($company_name ?: "Select Company") ." / Compliance Status";
        }

        else if($current_menu === 'dashboard') {
            echo "Dashboard";
        }

        // Default Case (for ALL other pages)
        else {
            if ($company_name) {
                echo $company_name . " / ";
            }
            echo ucfirst($current_menu);
        }
    ?>
  </h3>
  <div class="user-profile dropdown">
    <a class="dropdown-toggle d-flex align-items-center text-decoration-none" href="#" role="button">
        <?php 
          $role_id = $this->session->userdata('role_id');
          $role_names = [1 => 'Super Admin', 2 => 'Admin', 3 => 'User'];
          $role_name = isset($role_names[$role_id]) ? $role_names[$role_id] : 'User';
          $role_class = ($role_id == 1) ? 'super-admin' : (($role_id == 2) ? 'admin' : 'user');
          $role_icon = ($role_id == 1) ? 'fa-crown' : (($role_id == 2) ? 'fa-user-shield' : 'fa-user');
        ?>
        <span class="header-role-badge header-role-badge--<?= $role_class ?>" style="margin-right: 10px; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; <?= $role_id == 1 ? 'background: linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%); color: #fff;' : ($role_id == 2 ? 'background: linear-gradient(135deg, #059669 0%, #047857 100%); color: #fff;' : 'background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: #fff;') ?>">
          <i class="fa <?= $role_icon ?>" style="margin-right: 4px;"></i><?= $role_name ?>
        </span>
        <span class="fw-semibold me-2">
            <?php echo $this->session->userdata('full_name'); ?>
        </span>
        <img src="https://cdn-icons-png.flaticon.com/512/847/847969.png" width="40" class="rounded-circle" alt="User Avatar">
    </a>
    <ul class="dropdown-menu dropdown-menu-end mt-2">
        <li><a class="dropdown-item" href="<?= base_url('login/logout') ?>">Logout</a></li>
    </ul>
</div>
</div>

<?php 
// Check if user has single company for auto-redirect
$get_companies = get_all_company();
$has_single_company = (count($get_companies) === 1 && !is_super_admin());
$single_company_id = $has_single_company ? $get_companies[0]['id'] : null;
?>

<!-- JavaScript variables for single company auto-redirect -->
<script>
var hasSingleCompany = <?= $has_single_company ? 'true' : 'false' ?>;
var singleCompanyId = <?= $single_company_id ? $single_company_id : 'null' ?>;
</script>

<div class="modal fade" id="companyModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Select Company</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <!-- Hidden input to store which menu was clicked -->
        <input type="hidden" id="menu_target">
        <label for="company" class="form-label">Choose Company:</label>
        <select id="company" class="form-select">
		
          <option value="">-- Select Company --</option>
		  <?php foreach($get_companies as $company) { ?>
          <option value="<?php echo $company['id'];?>"><?php echo $company['company_name'];?></option>
		  <?php } ?>
          
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" id="goUpload" class="btn btn-success">Go</button>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="viewcompany" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Select Company</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
	  
	  <?php $get_companies = get_all_company();?>
      <div class="modal-body">
        <label for="company" class="form-label">Choose Company:</label>
        <select id="view_company" class="form-select">
		
          <option value="">-- Select Company --</option>
          <?php foreach($get_companies as $company) { ?>
              <option value="<?php echo $company['id'];?>"><?php echo $company['company_name'];?></option>
          <?php } ?>
          
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" id="view" class="btn btn-success">Go to View Documents</button>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="viewreminder" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Select User</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
	  
	  <?php $get_user = get_all_user(); ?>
      
	  <div class="modal-body">
        <label for="company" class="form-label">Choose User:</label>
        <select id="view_user" class="form-select">
		
          <option value="">-- Select --</option>
		  <?php foreach($get_user as $user) { ?>
          <option value="<?php echo $user['id'];?>"><?php echo $user['first_name'],' '.$user['last_name'];?></option>
		  <?php } ?>
          
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" id="goCompany" class="btn btn-success">Go to Companies</button>
      </div>
    </div>
  </div>
</div>

<script>

// Sidebar Toggle Function
function toggleSidebar() {
  var sidebar = document.getElementById('sidebar');
  var body = document.body;
  
  if (sidebar.classList.contains('collapsed')) {
    sidebar.classList.remove('collapsed');
    body.classList.remove('sidebar-collapsed');
    localStorage.setItem('sidebarCollapsed', 'false');
  } else {
    sidebar.classList.add('collapsed');
    body.classList.add('sidebar-collapsed');
    localStorage.setItem('sidebarCollapsed', 'true');
  }
}

// Company Document Heads - Open Modal
function openCompanyDocHeadsModal() {
  document.getElementById('menu_target').value = 'company_doc_heads';
  var modal = new bootstrap.Modal(document.getElementById('companyModal'));
  modal.show();
}

// Restore sidebar state on page load
(function() {
  var isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
  if (isCollapsed) {
    document.getElementById('sidebar').classList.add('collapsed');
    document.body.classList.add('sidebar-collapsed');
  }
})();

// Masters Menu Toggle - Clean Implementation
(function() {
  var initialized = false;
  
  function initMastersToggle() {
    if (initialized) return;
    initialized = true;
    
    var toggleBtn = document.getElementById('mastersToggleBtn');
    var menu = document.getElementById('mastersMenu');
    var arrow = toggleBtn ? toggleBtn.querySelector('.arrow-icon') : null;
    
    if (!toggleBtn || !menu) return;
    
    toggleBtn.onclick = function(e) {
      e.preventDefault();
      
      if (menu.classList.contains('open')) {
        menu.classList.remove('open');
        if (arrow) arrow.classList.remove('rotate');
      } else {
        menu.classList.add('open');
        if (arrow) arrow.classList.add('rotate');
      }
      
      return false;
    };
  }
  
  // Initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initMastersToggle);
  } else {
    initMastersToggle();
  }
})();
$(document).ready(function(){

  /***********************
   * Ask Company for Menus
   ************************/

  // Helper function to handle menu click with single company auto-redirect
  function handleMenuClick(e, target, directUrl) {
    e.preventDefault();
    
    // If user has single company, redirect directly without modal
    if (hasSingleCompany && singleCompanyId) {
      window.location.href = directUrl + singleCompanyId;
      return;
    }
    
    // Otherwise show the company selection modal
    $("#menu_target").val(target);
    $("#companyModal").modal("show");
  }

  // Authority
  $("a[href='<?= base_url('authority') ?>']").click(function(e){
      handleMenuClick(e, "authority", "<?= base_url('authority/index/') ?>");
  });

  // Document Head
  $("a[href='<?= base_url('type') ?>']").click(function(e){
      handleMenuClick(e, "type", "<?= base_url('type/allType/') ?>");
  });

  // Re-order Document Head
  $("a[href='<?= base_url('type/reorder_all') ?>']").click(function(e){
      handleMenuClick(e, "reorder", "<?= base_url('type/reorder_all/') ?>");
  });

  // Document Group
  $("a[href='<?= base_url('document/groupList') ?>']").click(function(e){
      handleMenuClick(e, "group", "<?= base_url('document/groupList/') ?>");
  });

  // Document
  $("a[href='<?= base_url('document/allDocuments') ?>']").click(function(e){
      handleMenuClick(e, "document", "<?= base_url('document/allDocuments/') ?>");
  });

  // Upload Documents
  $("#uploadMenu").click(function(e){
    handleMenuClick(e, "upload_docs", "<?= base_url('upload/index/') ?>");
  });

  // View Documents
  $("#viewMenu").click(function(e){
    handleMenuClick(e, "company", "<?= base_url('company/newDocuments/') ?>");
  });

  // Reminders
  $("#reminders").click(function(e){
    handleMenuClick(e, "upload_reminder", "<?= base_url('upload/reminder/') ?>");
  });

  // Compliance Status
  $("#complianceStatus").click(function(e){
    handleMenuClick(e, "compliance_status", "<?= base_url('report/reminder/') ?>");
  });

  // Company Document Heads - using jQuery event delegation removed, using onclick instead

  // Redirect on button click
  $("#goUpload").click(function(){

    var companyId = $("#company").val();
    var target = $("#menu_target").val();

    if(!companyId){
      alert("Please select a company first.");
      return;
    }

    if(target == "authority"){
      window.location.href = "<?= base_url('authority/index/') ?>" + companyId;
    }
    else if(target == "type"){
      window.location.href = "<?= base_url('type/allType/') ?>" + companyId;
    }
    else if(target == "reorder"){
      window.location.href = "<?= base_url('type/reorder_all/') ?>" + companyId;
    }
    else if(target == "group"){
      window.location.href = "<?= base_url('document/groupList/') ?>" + companyId;
    }
    else if(target == "document"){
      window.location.href = "<?= base_url('document/allDocuments/') ?>" + companyId;
    }
    else if(target == "upload_docs"){
      window.location.href = "<?= base_url('upload/index/'); ?>" + companyId;
    }
    else if(target == "company"){
      window.location.href = "<?= base_url('company/newDocuments/'); ?>" + companyId;
    }
    else if(target == "upload_reminder"){
      window.location.href = "<?= base_url('upload/reminder/'); ?>" + companyId;
    }
    else if(target == "compliance_status"){
      window.location.href = "<?= base_url('report/reminder/'); ?>" + companyId;
    }
    else if(target == "company_doc_heads"){
      window.location.href = "<?= base_url('companydocheads/index/'); ?>" + companyId;
    }
    else {
      // Default for Upload
      window.location.href = "<?= base_url('upload/index/') ?>" + companyId;
    }

    /*var companyId = $("#company").val();
    if(companyId){
      // Redirect (change URL as per your route)
      window.location.href = "<?php echo base_url('upload/index/'); ?>" + companyId;

    } else {
      alert("Please select a company first.");
    }*/
  });
});

  document.addEventListener('DOMContentLoaded', function () {
    const sidebar = document.getElementById('sidebar');
    const content = document.getElementById('mainContent');
    const toggleArrow = document.getElementById('sidebarToggle');

    // If any required element is missing, just skip this logic on this page
    if (!sidebar || !content || !toggleArrow) {
      return;
    }
    
    const icon = toggleArrow.querySelector('i');

    if (!icon) {
      return;
    }

    toggleArrow.addEventListener('click', function () {
      sidebar.classList.toggle('collapsed');
      content.classList.toggle('expanded');

      // Change arrow direction
      if (sidebar.classList.contains('collapsed')) {
        icon.classList.remove('fa-angle-left');
        icon.classList.add('fa-angle-right');
      } else {
        icon.classList.remove('fa-angle-right');
        icon.classList.add('fa-angle-left');
      }
    });
  });

    // --- Custom user-profile dropdown (Logout) ---
  document.addEventListener('DOMContentLoaded', function () {
    const userProfile = document.querySelector('.user-profile');
    if (!userProfile) return;

    const toggle = userProfile.querySelector('.dropdown-toggle');
    const menu   = userProfile.querySelector('.dropdown-menu');

    if (!toggle || !menu) return;

    // Open/close on click
    toggle.addEventListener('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      menu.classList.toggle('show');
    });

    // Close when clicking outside
    document.addEventListener('click', function (e) {
      if (!userProfile.contains(e.target)) {
        menu.classList.remove('show');
      }
    });
  });

</script>

<style>

.nav-link.dropdown-toggle::after {
  display: none !important;
}
.arrow-icon {
  transition: transform 0.3s ease;
}
.arrow-icon.rotate {
  transform: rotate(180deg);
}

/* Masters Menu Toggle Styles */
.masters-submenu {
  display: none;
  padding: 5px 0;
  margin-top: 5px;
}
.masters-submenu.open {
  display: block;
}
/* Remove pointer cursor from entire submenu area */
/*.masters-submenu,
.masters-submenu *,
.masters-submenu ul,
.masters-submenu ul li,
.masters-submenu ul li a,
.nav-item .masters-submenu,
#mastersMenu,
#mastersMenu * {
  cursor: default !important;
}*/
/* Child menu items (submenu-link) - remove pointer and hover effects */
.sidebar .submenu-link,
.sidebar .nav-link.submenu-link,
.sidebar .masters-submenu .submenu-link {
  padding: 8px 15px !important;
  font-size: 0.9rem !important;
  cursor: default !important;
  background: transparent !important;
  color: #cbd5e1 !important;
  pointer-events: auto;
}
.sidebar .submenu-link:hover,
.sidebar .nav-link.submenu-link:hover,
.sidebar .masters-submenu .submenu-link:hover {
  background: transparent !important;
  color: #cbd5e1 !important;
  cursor: default !important;
}
/* Only active state shows color */
.sidebar .submenu-link.active,
.sidebar .nav-link.submenu-link.active,
.sidebar .masters-submenu .submenu-link.active {
  background: rgba(59, 130, 246, 0.2) !important;
  color: #3b82f6 !important;
}
.masters-toggle {
  cursor: pointer;
}
/* Sidebar default state */
.sidebar {
  width: 250px;
  background-color: #2c3e50;
  color: white;
  height: 100vh;
  position: fixed;
  transition: width 0.3s ease;
  overflow-x: visible;
  overflow-y: auto;
}

/* Custom scrollbar for sidebar */
.sidebar::-webkit-scrollbar {
  width: 6px;
}
.sidebar::-webkit-scrollbar-track {
  background: #1a252f;
}
.sidebar::-webkit-scrollbar-thumb {
  background: #4a6785;
  border-radius: 3px;
}
.sidebar::-webkit-scrollbar-thumb:hover {
  background: #5a7795;
}

/* Collapsed state */
.sidebar.collapsed {
  /*width: 60px;*/
  overflow: visible !important;
}

.sidebar .brand {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  /*justify-content: space-between;*/
}

.brand-text {
  margin-left: 10px;
  font-size: 18px;
  white-space: nowrap;
}

.sidebar.collapsed .brand-text {
  display: none;
}

.sidebar .toggle-arrow {
  cursor: pointer;
  font-size: 16px;
}

.sidebar .nav-link {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: white;
  text-decoration: none;
  transition: background-color 0.2s;
}

.sidebar .nav-link i {
  width: 20px;
  font-size: 18px;
  text-align: center;
}

.link-text {
  margin-left: 10px;
  white-space: nowrap;
}

.sidebar.collapsed .link-text {
  display: none;
}

/* Main content area */
.content {
  margin-left: 250px;
  transition: margin-left 0.3s ease;
  padding: 20px;
}

.content.expanded {
  margin-left: 60px;
}

.user-profile {
  position: relative;
}

/* Position the logout dropdown nicely below the username/avatar */
.user-profile .dropdown-menu {
  position: absolute;
  top: 100%;          /* show below the trigger */
  right: 0;           /* align to the right edge */
  left: auto;         /* ignore left positioning */
  margin-top: 0.35rem;
  z-index: 2000;
  min-width: 160px;   /* optional: ensure a decent width */
}

.sidebar {
  z-index: 2000;
}

.sidebar.collapsed .nav-link:hover::after,
.sidebar.collapsed .nav-link:hover::before {
  z-index: 99999;
}

/* FINAL OVERRIDE: Submenu links - no pointer, no hover effect */
.sidebar .masters-submenu a.submenu-link,
.sidebar .masters-submenu a.nav-link.submenu-link,
a.nav-link.submenu-link,
.submenu-link {
  cursor: default !important;
}
.sidebar .masters-submenu a.submenu-link:hover,
.sidebar .masters-submenu a.nav-link.submenu-link:hover,
a.nav-link.submenu-link:hover,
.submenu-link:hover {
  background: transparent !important;
  background-image: none !important;
  color: #cbd5e1 !important;
  cursor: default !important;
}
.sidebar .masters-submenu a.submenu-link.active,
.sidebar .masters-submenu a.nav-link.submenu-link.active,
a.nav-link.submenu-link.active,
.submenu-link.active {
  background: rgba(59, 130, 246, 0.25) !important;
  background-image: none !important;
  color: #3b82f6 !important;
}

/* FINAL FIX: allow Masters submenu to fully render */
.sidebar .masters-submenu {
  max-height: calc(100vh - 160px);
  overflow-y: auto;
  overflow-x: hidden;
}

.sidebar .masters-submenu ul {
  margin: 0;
  padding-bottom: 10px;
}
</style>