<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url();?>public/assets/css/choices.min.css">
<script src="<?php echo base_url();?>public/assets/js/choices.min.js"></script>	

  <style>
/* Hide raw select elements until Choices.js initializes - prevents unstyled flash */
select.filter-select:not(.choices__input) {
    visibility: hidden;
    height: 0;
    opacity: 0;
    position: absolute;
}
.choices {
    visibility: visible !important;
    opacity: 1 !important;
}
/* Show loading placeholder while selects initialize */
.filter-item--dochead::before,
.filter-item--year::before {
    content: "Loading...";
    display: block;
    padding: 8px 12px;
    background: #f1f5f9;
    border-radius: 6px;
    color: #94a3b8;
    font-size: 0.85rem;
}
.filter-item--dochead:has(.choices)::before,
.filter-item--year:has(.choices)::before,
.filter-item--dochead.choices-ready::before,
.filter-item--year.choices-ready::before {
    display: none;
}
     body { background: #f9f9f9; padding: 20px; }
  .timeline {
    width: 60%;
    margin: 0 auto;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    padding: 10px 20px;
  }
/* ========== CONSOLIDATED BOX SIZING - ALL SAME SIZE ========== */
/* All 4 boxes: Document Head, Year, Month, Document - SAME SIZE */
.authority, .year, .month, .doc-item { 
    cursor: pointer; 
    padding: 8px 12px !important; 
    margin: 3px 0; 
    border-radius: 6px; 
    font-size: 1rem;
    line-height: 1.4 !important;
    min-height: 38px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.authority { background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%) !important; color: white !important; font-weight: bold; }
.year { background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%) !important; color: white !important; margin-left: 20px; font-weight: 600; }
.month { background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%) !important; color: #1e3a5f !important; margin-left: 40px; font-weight: 600; }
.doc-item { background: white !important; border: 1px solid #e2e8f0 !important; cursor: default; }
.documents { margin-left: 60px; background: white !important; padding: 8px !important; border-radius: 6px; }

/* Year View Mode - Year is parent, Authority is child */
.view-mode-year .year {
    margin-left: 0 !important;
}
.view-mode-year .authority {
    margin-left: 20px !important;
}

.choices__item {
    white-space: normal !important;
    word-wrap: break-word !important;
    word-break: break-word !important;
    overflow-wrap: break-word !important;
    line-height: 1.4 !important;
}

/* Wrap text inside dropdown list */
.choices__list--dropdown .choices__item {
    white-space: normal !important;
}

.choices__list--dropdown {
    z-index: 9999 !important;
    position: absolute !important;
}

.choices__list--dropdown.is-active {
    z-index: 9999 !important;
}

.choices {
    z-index: 999 !important;
}

.doc-meta-row {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: nowrap;        /* ❌ prevent line break */
    overflow: hidden;
}

.doc-name {
    width: 300px;             /* approx 60-char space */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;  /* truncate long names */
}

.doc-size {
    width: 80px;
    white-space: nowrap;
}

.doc-date {
    width: 130px;
    white-space: nowrap;
}

.doc-owner {
    width: 120px;
    white-space: nowrap;
}

/* ========================================
   COMPACT PROFESSIONAL FILTER PANEL
   ======================================== */

.filter-panel {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;
    margin-bottom: 16px;
}

.filter-panel__header {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
    padding: 10px 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 10px 10px 0 0;
}

.filter-panel__title {
    color: white;
    font-size: 0.9rem;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-panel__title i {
    font-size: 0.9rem;
}

.filter-panel__subtitle {
    display: none;
}

.filter-panel__body {
    padding: 12px 16px;
}

/* Filter Row Layout */
.filter-row {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: nowrap;
}

.filter-item select {
    width: 100% !important;
}

.filter-item--toggle {
    flex: 0 0 auto;
}

.filter-item--dochead {
    flex: 1 1 250px;
    min-width: 200px;
}

.filter-item--year {
    flex: 1 1 200px;
    min-width: 150px;
}

.filter-item--actions {
    flex: 0 0 auto;
    margin-left: auto;
}

@media (max-width: 768px) {
    .filter-row {
        flex-wrap: wrap;
    }
    .filter-item--dochead,
    .filter-item--year {
        flex: 1 1 100%;
        max-width: 100%;
    }
}

/* View Toggle - Compact with Blue Active */
.view-toggle-container {
    background: #e2e8f0;
    border-radius: 6px;
    padding: 3px;
    display: inline-flex;
}

.view-toggle-btn {
    padding: 8px 16px;
    border: none;
    background: transparent;
    border-radius: 6px;
    font-size: 0.85rem;
    font-weight: 500;
    color: #64748b;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 6px;
}

.view-toggle-btn:hover {
    opacity: 0.85;
}

/* Doc Head toggle button - Dark Blue */
.view-toggle-btn[data-view="dochead"].active {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
    color: white;
    box-shadow: 0 2px 6px rgba(30, 58, 95, 0.3);
}

/* Year toggle button - Blue */
.view-toggle-btn[data-view="year"].active {
    background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%);
    color: white;
    box-shadow: 0 2px 6px rgba(59, 130, 246, 0.3);
}

.view-toggle-btn i {
    font-size: 0.9rem;
}

/* Filter Labels - Hidden for compact */
.filter-label {
    display: none;
}

/* Filter Group - Minimal */
.filter-group {
    background: transparent;
    border-radius: 0;
    padding: 0;
    border: none;
}

.filter-group:hover {
    border-color: transparent;
    box-shadow: none;
}

/* Action Buttons - Compact */
.filter-actions {
    display: flex;
    gap: 6px;
}

.btn-filter-apply {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    border: none;
    color: white;
    padding: 8px 16px;
    border-radius: 6px;
    font-weight: 500;
    font-size: 0.8rem;
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
}

.btn-filter-apply:hover {
    box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
    color: white;
}

.btn-filter-reset {
    background: #f1f5f9;
    border: none;
    color: #64748b;
    padding: 8px 12px;
    border-radius: 6px;
    font-weight: 500;
    font-size: 0.8rem;
    display: flex;
    align-items: center;
    transition: all 0.2s ease;
}

.btn-filter-reset:hover {
    background: #fee2e2;
    color: #ef4444;
}

/* Active Filters Tags - Hidden */
.active-filters {
    display: none !important;
}

/* Stats Badge */
.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 0.7rem;
    color: white;
}

/* Choices.js Custom Styling - Compact */
.filter-item .choices {
    width: 100% !important;
    display: block !important;
}

.filter-item .choices__inner {
    background: white !important;
    border: 1px solid #e2e8f0 !important;
    border-radius: 6px !important;
    padding: 4px 8px !important;
    min-height: 34px !important;
    font-size: 0.8rem !important;
    width: 100% !important;
    box-sizing: border-box !important;
}

.choices__inner:hover,
.choices.is-focused .choices__inner {
    border-color: #3b82f6 !important;
}

.choices__list--dropdown {
    border-radius: 6px !important;
    border: 1px solid #e2e8f0 !important;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
}

.choices__item--selectable.is-highlighted {
    background: #3b82f6 !important;
}

.choices__item--choice {
    padding: 6px 10px !important;
    font-size: 0.8rem !important;
}

.choices__list--multiple .choices__item {
    background: #3b82f6 !important;
    border: none !important;
    border-radius: 4px !important;
    padding: 2px 6px !important;
    font-size: 0.75rem !important;
}

.choices__input {
    font-size: 0.8rem !important;
}

/* Ensure select elements take full width */
#authoritySelect, #yearSelect {
    width: 100% !important;
}

/* Year level styling for Year View mode - Blue */
.year-level-primary {
    background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%) !important;
    color: white !important;
    font-weight: 600 !important;
    border-radius: 6px !important;
    margin-bottom: 3px !important;
    box-shadow: 0 2px 6px rgba(59, 130, 246, 0.2);
    padding: 8px 12px !important;
    font-size: 1rem !important;
    min-height: 36px;
}

/* Doc Head as secondary in Year View - Dark Blue */
.dochead-level-secondary {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%) !important;
    color: white !important;
    margin-left: 24px !important;
    border-radius: 6px !important;
    margin-bottom: 3px !important;
    padding: 8px 12px !important; 
    font-size: 1rem !important;
    min-height: 36px;
}

/* Enhanced Timeline Styles with proper indentation */
#timeline {
    min-height: 200px;
    padding: 8px;
}

/* Level 1: Authority/Document Head - Dark Blue - inherits from consolidated */
.authority:hover {
    box-shadow: 0 3px 10px rgba(0,0,0,0.12);
}

/* Level 2: Years container */
.years {
    margin-left: 20px !important;
    padding-left: 12px !important;
    border-left: 2px solid #e2e8f0;
}

/* Level 2: Year - Blue - inherits from consolidated */

/* Level 3: Months container */
.months {
    margin-left: 20px !important;
    padding-left: 12px !important;
    border-left: 2px solid #e2e8f0;
}

/* Level 3: Month - Dark Yellow/Amber - inherits from consolidated */

/* Level 4: Documents container - INDENTED under month - White background */
.documents {
    margin-left: 24px !important;
    padding: 10px 12px !important;
    background: white !important;
    border-radius: 8px;
    border-left: 3px solid #3b82f6;
    margin-top: 4px;
    margin-bottom: 8px;
}

/* Level 4: Document items - inherits from consolidated */
.doc-item:hover {
    border-color: #3b82f6 !important;
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.12);
    background: #fafbff;
}

.doc-item:last-child {
    margin-bottom: 0;
}

/* Authorities container for Year View */
.authorities {
    margin-left: 20px !important;
    padding-left: 12px !important;
    border-left: 2px solid #e2e8f0;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #64748b;
}

.empty-state i {
    font-size: 3rem;
    color: #cbd5e1;
    margin-bottom: 16px;
}

.empty-state h5 {
    color: #475569;
    margin-bottom: 8px;
    font-size: 1rem;
}

.empty-state p {
    color: #94a3b8;
    font-size: 0.85rem;
}

/* Action Dropdown Styles */
.action-dropdown {
    position: relative;
    display: inline-block;
}

.action-dropdown__btn {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: white;
    border: none;
    padding: 3px 8px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.7rem;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 3px;
    transition: all 0.2s ease;
    box-shadow: 0 1px 2px rgba(59, 130, 246, 0.2);
    height: 26px;
    line-height: 1;
}

.action-dropdown__btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(59, 130, 246, 0.4);
}

.action-dropdown__btn--success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    box-shadow: 0 2px 4px rgba(16, 185, 129, 0.3);
}

.action-dropdown__btn--success:hover {
    box-shadow: 0 4px 8px rgba(16, 185, 129, 0.4);
}

.action-dropdown__btn--primary {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
}

.action-dropdown__btn--primary:hover {
    box-shadow: 0 4px 8px rgba(59, 130, 246, 0.4);
}

.action-dropdown__menu {
    display: none !important;
}

#floating-action-menu {
    display: block !important;
    position: fixed;
    min-width: 160px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
    z-index: 999999;
    overflow: visible;
    animation: dropdownFade 0.15s ease;
}

@keyframes dropdownFade {
    from { opacity: 0; transform: translateY(-5px); }
    to { opacity: 1; transform: translateY(0); }
}

#floating-action-menu .action-dropdown__item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    color: #374151;
    text-decoration: none;
    font-size: 0.8rem;
    transition: background 0.15s;
    cursor: pointer;
}

#floating-action-menu .action-dropdown__item:hover {
    background: #f3f4f6;
}

#floating-action-menu .action-dropdown__item--upload:hover,
#floating-action-menu .action-dropdown__item--view:hover {
    background: #dbeafe;
    color: #1d4ed8;
}

#floating-action-menu .action-dropdown__item--download:hover {
    background: #cffafe;
    color: #0891b2;
}

#floating-action-menu .action-dropdown__item--favourite:hover {
    background: #fef3c7;
    color: #d97706;
}

#floating-action-menu .action-dropdown__item--edit:hover {
    background: #e0e7ff;
    color: #4f46e5;
}

#floating-action-menu .action-dropdown__item--delete:hover {
    background: #fee2e2;
    color: #dc2626;
}

#floating-action-menu .action-dropdown__item--print:hover {
    background: #CCCCCE;
    color: #374151;
}

#floating-action-menu .action-dropdown__item--mail:hover {
    background: #fef3c7;
    color: #d97706;
}

#floating-action-menu .action-dropdown__item--whatsapp:hover {
    background: #d1fae5;
    color: #059669;
}

#floating-action-menu .action-dropdown__divider {
    height: 1px;
    background: #e5e7eb;
    margin: 4px 0;
}

#floating-action-menu .action-dropdown__submenu-label {
    padding: 6px 12px;
    font-size: 0.7rem;
    color: #9ca3af;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.download-icon {
  color: #fff !important;
  cursor: pointer;
  transition: transform 0.2s;
}

.download-icon:hover {
  transform: scale(1.2);
}

/* Keep document name normal */
.doc-meta-row .doc-name {
  font-size: 1rem;   /* or whatever size you prefer */
  font-weight: 600;
  color: #1f2937;
}

/* Make ONLY meta info smaller */
.doc-meta-row span:not(.doc-name),
.doc-meta-row .meta {
  font-size: 0.85rem;
  color: #64748b;
}

/* ===============================
   DISABLED FAVOURITE STATE
   =============================== */
   .action-dropdown__item.is-disabled {
  color: #9ca3af !important;
  cursor: not-allowed !important;
  pointer-events: none;
  background: transparent !important;
}

.action-dropdown__item.is-disabled i {
  color: #9ca3af !important;
}

</style>

<div class="content-wrapper p-3">
  <section class="content pt-3">
    <div class="container-fluid">

      <!-- ===== Company Info Cards ===== -->
      
      <!-- ===== Compact Filter Panel ===== -->
      <div class="filter-panel">
        <!-- Header with inline filters -->
        <div class="filter-panel__header">
          <h5 class="filter-panel__title">
            <i class="fa fa-filter"></i> Filters
          </h5>
          <div class="stats-badge">
            <i class="fa fa-file-alt me-1"></i> <span id="totalDocCount">--</span> docs
          </div>
        </div>
        
        <!-- Compact Filter Row -->
        <div class="filter-panel__body">
          <div class="filter-row">
            
            <!-- View Toggle -->
            <div class="filter-item filter-item--toggle">
              <div class="view-toggle-container">
                <button type="button" class="view-toggle-btn active" data-view="dochead" id="btnViewDocHead">
                  <i class="fa fa-folder-tree"></i> Doc Head
                </button>
                <button type="button" class="view-toggle-btn" data-view="year" id="btnViewYear">
                  <i class="fa fa-calendar-alt"></i> Year
                </button>
              </div>
            </div>
            
            <!-- Document Head Filter -->
            <div class="filter-item filter-item--dochead">
              <select name="authoritySelect" id="authoritySelect" class="form-control" multiple>
                <?php foreach($type_data1 as $authority): ?>
                  <option value="<?= $authority['type_id']; ?>"><?= $authority['type_name']. ' ('.$authority['alias_name'].')'  ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <!-- Year Filter -->
            <div class="filter-item filter-item--year">
              <select name="yearSelect" id="yearSelect" class="form-control" multiple>
                <?php 
                  $startYear = 2020;
                  if (!empty($company_list[0]['co_start_date'])) {
                    $startDate = $company_list[0]['co_start_date'];
                    $startYear = (int)date('Y', strtotime($startDate));
                  }
                  $currentYear = (int)date('Y');
                  for ($yr = $currentYear; $yr >= $startYear; $yr--): 
                ?>
                  <option value="<?= $yr; ?>"><?= $yr; ?></option>
                <?php endfor; ?>
              </select>
            </div>
            
            <!-- Action Buttons -->
            <div class="filter-item filter-item--actions">
              <div class="filter-actions">
                <button type="button" id="applyFiltersBtn" class="btn-filter-apply">
                  <i class="fa fa-search"></i> Apply
                </button>
                <button type="button" id="resetFiltersBtn" class="btn-filter-reset">
                  <i class="fa fa-undo"></i>
                </button>
              </div>
            </div>
            
          </div>
          <input type="hidden" name="company_id" id="company_id" value="<?= $company_list[0]['id']; ?>">
        </div>
      </div>
      
      <!-- ===== Document Results ===== -->
      <div id="documentResults">
        <div id="timeline"></div>
      </div>

    </div>
  </section>
</div>

<!-- ===== Edit Modal ===== -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog">
    <form id="editForm" enctype="multipart/form-data">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Edit Document</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="doc_id" id="edit_doc_id">
          <input type="hidden" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>">
          <div class="form-group mb-3">
            
            <input type="text" id="edit_document_name" name="document_name" class="form-control" readonly>
			<label>Document Name</label>
          </div>
          <div class="form-group mb-3">
            Current File
            <div id="uploaded_file" class="border rounded p-2 bg-light small text-muted"></div>
          </div>
          <div class="form-group mb-3">
           
            <input type="file" name="file" class="form-control">
			 <label>Replace File</label>
          </div>
          <div id="editMsg" class="small"></div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Save Changes</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- ===== JS Dependencies ===== -->
<script src="https://code.jquery.com/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="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- ===== Custom Script ===== -->
<script>
  const base_url = "<?= base_url(); ?>";
</script>
<script>
// Global variables for Choices instances
let authorityChoices = null;
let yearChoices = null;
let currentViewMode = 'dochead'; // 'dochead' or 'year'
let lastDocumentCount = 0;

$(document).ready(function() {
  // Initialize Authority/Document Head dropdown
  const authoritySelect = document.getElementById('authoritySelect');
  if (authoritySelect) {
    authorityChoices = new Choices(authoritySelect, {
      removeItemButton: true,
      placeholder: true,
      placeholderValue: 'All Document Heads...',
      searchPlaceholderValue: 'Search...',
      itemSelectText: ''
    });
    // Mark container as ready to hide loading placeholder
    $(authoritySelect).closest('.filter-item').addClass('choices-ready');
  }
  
  // Initialize Year dropdown
  const yearSelect = document.getElementById('yearSelect');
  if (yearSelect) {
    yearChoices = new Choices(yearSelect, {
      removeItemButton: true,
      placeholder: true,
      placeholderValue: 'All Years...',
      searchPlaceholderValue: 'Search...',
      itemSelectText: ''
    });
    // Mark container as ready to hide loading placeholder
    $(yearSelect).closest('.filter-item').addClass('choices-ready');
  }
  
  // View toggle button handlers
  $('.view-toggle-btn').on('click', function() {
    const view = $(this).data('view');
    currentViewMode = view;
    
    // Update active state
    $('.view-toggle-btn').removeClass('active');
    $(this).addClass('active');
    
    // Toggle view-mode-year class for proper margin hierarchy
    if (view === 'year') {
      $('#timeline').addClass('view-mode-year');
    } else {
      $('#timeline').removeClass('view-mode-year');
    }
    
    console.log('View mode changed to:', currentViewMode);
    applyFilters();
  });
  
  // Apply Filters button handler
  $('#applyFiltersBtn').on('click', function() {
    applyFilters();
  });
  
  // Reset Filters button handler
  $('#resetFiltersBtn').on('click', function() {
    resetFilters();
  });
  
  // Update filter tags when Choices selection changes
  if (authorityChoices) {
    authoritySelect.addEventListener('change', updateFilterTags);
  }
  if (yearChoices) {
    yearSelect.addEventListener('change', updateFilterTags);
  }
});

// Function to update filter tags display
function updateFilterTags() {
  const container = $('#activeFilters');
  container.empty();
  
  // Get selected authorities
  const selectedAuthorities = authorityChoices ? authorityChoices.getValue() : [];
  const selectedYears = yearChoices ? yearChoices.getValue() : [];
  
  // Add authority tags
  selectedAuthorities.forEach(item => {
    const tag = $(`
      <span class="filter-tag">
        <i class="fa fa-building"></i> ${item.label}
        <i class="fa fa-times filter-tag__remove" data-type="authority" data-value="${item.value}"></i>
      </span>
    `);
    container.append(tag);
  });
  
  // Add year tags
  selectedYears.forEach(item => {
    const tag = $(`
      <span class="filter-tag filter-tag--year">
        <i class="fa fa-calendar"></i> ${item.label}
        <i class="fa fa-times filter-tag__remove" data-type="year" data-value="${item.value}"></i>
      </span>
    `);
    container.append(tag);
  });
  
  // Add view mode tag
  if (currentViewMode === 'year') {
    const tag = $(`
      <span class="filter-tag" style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); color: #92400e;">
        <i class="fa fa-layer-group"></i> View by Year
      </span>
    `);
    container.append(tag);
  }
}

// Handle filter tag removal
$(document).on('click', '.filter-tag__remove', function() {
  const type = $(this).data('type');
  const value = $(this).data('value');
  
  if (type === 'authority' && authorityChoices) {
    authorityChoices.removeActiveItemsByValue(value);
  } else if (type === 'year' && yearChoices) {
    yearChoices.removeActiveItemsByValue(value);
  }
  
  updateFilterTags();
  applyFilters();
});

// Reset all filters
function resetFilters() {
  if (authorityChoices) authorityChoices.removeActiveItems();
  if (yearChoices) yearChoices.removeActiveItems();
  
  currentViewMode = 'dochead';
  $('.view-toggle-btn').removeClass('active');
  $('#btnViewDocHead').addClass('active');
  
  updateFilterTags();
  applyFilters();
}

// Update document count
function updateDocumentCount(count) {
  lastDocumentCount = count;
  $('#totalDocCount').text(count);
}

// Function to apply filters and fetch documents
function applyFilters() {
  const companyId = $('#company_id').val();
  const selectedAuthorities = authorityChoices ? authorityChoices.getValue(true) : [];
  const selectedYears = yearChoices ? yearChoices.getValue(true) : [];
  
  console.log('Applying filters:', {
    viewMode: currentViewMode,
    authorities: selectedAuthorities,
    years: selectedYears
  });
  
  fetchDocumentsWithFilters(selectedAuthorities, selectedYears);
}

// Function to fetch documents with filters
function fetchDocumentsWithFilters(selectedAuthorities = [], selectedYears = []) {
  const companyId = $('#company_id').val();
  
  $.ajax({
    url: '<?= base_url('company/getDocumentsByAuthority'); ?>',
    type: 'POST',
    data: { 
      authority_ids: selectedAuthorities,
      years: selectedYears,
      company_id: companyId
    },
    dataType: 'json',
    beforeSend: function() {
      $("#timeline").html(`
        <div class="text-center py-5">
          <div class="spinner-border text-primary mb-3" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <p class="text-muted">Loading documents...</p>
        </div>
      `);
      $('#totalDocCount').html('<i class="fa fa-spinner fa-spin"></i>');
    },
    success: function(response) {
      // Update document count
      updateDocumentCount(response ? response.length : 0);
      updateFilterTags();
      
      // Apply view-mode-year class for proper margin hierarchy
      if (currentViewMode === 'year') {
        $('#timeline').addClass('view-mode-year');
        buildTimelineByYear(response);
      } else {
        $('#timeline').removeClass('view-mode-year');
        buildTimeline(response, true);
      }
    },
    error: function() {
      $("#timeline").html(`
        <div class="text-center py-5">
          <i class="fa fa-exclamation-triangle fa-3x text-danger mb-3"></i>
          <p class="text-danger">Failed to load data. Please try again.</p>
          <button class="btn btn-outline-primary btn-sm" onclick="applyFilters()">
            <i class="fa fa-redo me-1"></i> Retry
          </button>
        </div>
      `);
      updateDocumentCount(0);
    }
  });
}
$(document).ready(function() {
	 
$("#documentFilterForm").submit(function(e) {
    e.preventDefault();
    $.ajax({
      url: $(this).attr("action"),
      type: "POST",
      data: $(this).serialize(),
      beforeSend: ()=> $("#documentResults").html("<div class='p-3 text-center text-muted'>Loading...</div>"),
      success: (res)=> $("#documentResults").html(res),
      error: ()=> $("#documentResults").html("<div class='p-3 text-danger'>Error loading documents</div>")
    });
  });	
  const editModalEl = document.getElementById('editModal');
  const editModal = new bootstrap.Modal(editModalEl);

  // Collapse header arrow animation
  $(document).on('click', '.gradient-header', function(){
    $(this).find('.arrow-icon').toggleClass('rotate');
  });

  // ===== Open Edit Modal =====
  $(document).on('click', '.openEditModal', function(e){
    e.preventDefault();
    const docId = $(this).data('id');

    $.ajax({
      url: "<?= base_url('company/getDocument'); ?>",
      type: "POST",
      data: { 
        doc_id: docId, 
        "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>" 
      },
      dataType: "json",
      success: function(res){
        if(res.status === 'success'){
          $('#edit_doc_id').val(res.data.id);
          $('#edit_document_name').val(res.data.document_name);
          $('#uploaded_file').html(res.data.file_name || '<i>No file uploaded</i>');
          $('#editMsg').html('');
          editModal.show();
        } else {
          Swal.fire('Error', res.message, 'error');
        }
      },
      error: function(){
        Swal.fire('Error', 'Error fetching document details.', 'error');
      }
    });
  });

  // ===== Save Edited Document =====
  $('#editForm').submit(function(e){
    e.preventDefault();
    const formData = new FormData(this);

    $.ajax({
      url: "<?= base_url('company/updateDocument'); ?>",
      type: "POST",
      data: formData,
      dataType: "json",
      contentType: false,
      processData: false,
      beforeSend: function(){
        $('#editMsg').removeClass().addClass('text-info').html('Saving...');
      },
      success: function(res){
        if(res.status === 'success'){
          $('#editMsg').removeClass().addClass('text-success').html(res.message);
          const docId = res.data.id;
          const newFile = res.data.file_name;

          $('#doc-item-' + docId).find('.file-name').text(newFile);
          $('#doc-item-' + docId).find('.uploaded-on').text('Uploaded: ' + res.data.uploaded_at);

          setTimeout(() => {
            editModal.hide();
            Swal.fire('Updated', 'Document updated successfully!', 'success');
          }, 600);
        } else {
          $('#editMsg').removeClass().addClass('text-danger').html(res.message);
        }
      },
      error: function(){
        $('#editMsg').removeClass().addClass('text-danger').html('Error while saving.');
      }
    });
  });

  // ===== Delete Document =====
    $(document).on('click', '.deleteDocument', function(e){
        e.preventDefault();

        const docId = $(this).data('id');
        const $docItem = $('#doc-item-' + docId);

        // First check if document can be deleted (master/sub validation)
        $.post('<?= base_url('company/checkDocumentDeletable'); ?>', { 
            doc_id: docId, 
            "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>"
        }, checkRes => {
            if (!checkRes.can_delete) {
                Swal.fire({
                    icon: 'error',
                    title: 'Cannot Delete Master Document',
                    html: `<p>${checkRes.message}</p>`,
                    confirmButtonColor: '#dc2626'
                });
                return;
            }

            // Document can be deleted, show confirmation
        Swal.fire({
            title: 'Are you sure?',
            text: 'You will not be able to recover this document!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then(result => {
            if(result.isConfirmed){
                $.post('<?= base_url('company/deleteDocument'); ?>', { 
                    doc_id: docId, 
                    "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>"
                }, res => {
                    if(res.status === "success"){

                        // Remove the document
                        const $parent = $docItem.parent();  // Save parent reference
                        $docItem.remove();

                        // Clean empty containers starting from the parent
                        cleanEmptyContainers($parent);

                        Swal.fire('Deleted!', 'Document deleted successfully.', 'success');

                    } else {
                        Swal.fire('Error', res.message, 'error');
                    }
                }, 'json');
            }
        });
        }, 'json');
    });

});

// Global function to clean empty containers after document deletion
    function cleanEmptyContainers($el) {
  console.log('🧹 Starting cleanEmptyContainers');

  // Run cleanup in a loop until no more changes are made
  let changed = true;
  let iterations = 0;
  const maxIterations = 10; // Safety limit
  
  while (changed && iterations < maxIterations) {
    changed = false;
    iterations++;
    console.log('🔄 Cleanup iteration:', iterations);
    
    // ========== STEP 1: Clean empty .documents and their .month headers ==========
    $('#timeline .documents').each(function() {
      const $docs = $(this);
      const docCount = $docs.children('.doc-item').length;
      console.log('📁 Documents container has', docCount, 'items');
      
      if (docCount === 0) {
        // Find the month header - it's the previous sibling
        const $month = $docs.prev('.month');
        if ($month.length) {
          console.log('🗑 Removing empty month:', $month.data('month'));
          $month.remove();
          changed = true;
        }
        console.log('🗑 Removing empty documents container');
        $docs.remove();
        changed = true;
      }
    });
    
    // ========== STEP 2: Clean empty .months containers ==========
    $('#timeline .months').each(function() {
      const $months = $(this);
      // Check for both .month elements AND .documents elements (since they alternate)
      const monthCount = $months.children('.month').length;
      console.log('📅 Months container has', monthCount, 'months');
      
      if (monthCount === 0) {
        // Could be preceded by .year (Doc Head view) or .authority (Year view)
        const $prevElement = $months.prev();
        if ($prevElement.hasClass('year') && !$prevElement.hasClass('year-level-primary')) {
          console.log('🗑 Removing empty year (Doc Head view):', $prevElement.data('year'));
          $prevElement.remove();
          changed = true;
        } else if ($prevElement.hasClass('authority') && $prevElement.hasClass('dochead-level-secondary')) {
          console.log('🗑 Removing empty authority (Year view):', $prevElement.data('authority'));
          $prevElement.remove();
          changed = true;
        }
        console.log('🗑 Removing empty months container');
          $months.remove();
        changed = true;
        }
      });

    // ========== STEP 3: Clean empty .years containers (Doc Head view) ==========
    $('#timeline .years').each(function() {
      const $years = $(this);
      const yearCount = $years.children('.year').length;
      console.log('📆 Years container has', yearCount, 'years');
      
      if (yearCount === 0) {
        const $authority = $years.prev('.authority');
        if ($authority.length && !$authority.hasClass('dochead-level-secondary')) {
          console.log('🗑 Removing empty authority (Doc Head view):', $authority.data('authority'));
          $authority.remove();
          changed = true;
        }
        console.log('🗑 Removing empty years container');
        $years.remove();
        changed = true;
      }
    });
    
    // ========== STEP 4: Clean empty .authorities containers (Year view) ==========
    $('#timeline .authorities').each(function() {
      const $authorities = $(this);
      const authorityCount = $authorities.children('.authority').length;
      console.log('🏢 Authorities container has', authorityCount, 'authorities');
      
      if (authorityCount === 0) {
        const $yearPrimary = $authorities.prev('.year-level-primary');
        if ($yearPrimary.length) {
          console.log('🗑 Removing empty year (Year view):', $yearPrimary.data('year'));
          $yearPrimary.remove();
          changed = true;
        }
        console.log('🗑 Removing empty authorities container');
        $authorities.remove();
        changed = true;
      }
    });
    
    // ========== STEP 5: Clean any authority-section wrappers ==========
    $('#timeline .authority-section').each(function() {
      const $section = $(this);
      if ($section.find('.doc-item').length === 0) {
        console.log('🗑 Removing empty authority-section');
        $section.remove();
        changed = true;
    }
  });
}

  console.log('🧹 Finished cleanEmptyContainers after', iterations, 'iterations');
}

function buildTimeline(documents) {
  console.log("buildTimeline documents:", documents);

  $("#timeline").empty();

  if (!documents || documents.length === 0) {
    $("#timeline").html(`
      <div class="empty-state">
        <i class="fa fa-folder-open"></i>
        <h5>No Documents Found</h5>
        <p>Try adjusting your filters or upload new documents</p>
      </div>
    `);
    return;
  }

  // Group by authority_type_id and attach authority name + company_id
  const grouped = {}; 
  const order = []; // ✅ store order of authorities
  documents.forEach(d => {
   // const companyId = d.company_id || d.comp_id || 'unknown'; // ✅ NEW
    const companyId = '<?= $company_list[0]['id']; ?>'; // ✅ NEW
    const authorityName = d.authority || d.type_name || 'Unknown Authority';
    const authorityId = d.authority_type_id || d.authority_id || d.type_id || 'unknown';
    const year = d.year || d.document_year || 'Unknown Year';
    const monthRaw = d.month || d.document_month || '01';
    const monthNum = String(monthRaw).padStart(2, '0');
    const monthName = getMonthName(monthNum);
    const doc_alias = d.doc_alias || d.alias_name || ''; // ✅ fallback
    const doc = {
      doc_id: d.doc_id || d.id || d.ud_id,
      name: d.name || d.document_name || 'Untitled',
      file_name: d.file_name || d.uploaded_file || '',
      uploaded_at: d.uploaded_at || d.created_at || d.upload_time || '',
      uploaded_by: d.uploaded_by || d.user_id || d.uploaded_user || '',
      file_size: d.file_size || d.size || "",
      is_favourite: d.is_favourite || 0
    };

    if (!grouped[authorityId]) {
      grouped[authorityId] = { authorityName, doc_alias, companyId, years: {} }; // ✅ store companyId per authority
      order.push({ id: authorityId, name: authorityName });
    }

    if (!grouped[authorityId].years[year]) {
      grouped[authorityId].years[year] = {};
    }

    if (!grouped[authorityId].years[year][monthName]) {
      grouped[authorityId].years[year][monthName] = [];
    }

    grouped[authorityId].years[year][monthName].push(doc);
  });

  // ✅ Sort authorities alphabetically (A → Z)
  order.sort((a, b) => a.name.localeCompare(b.name));
  // Render timeline
  //for (const authorityId in grouped) {
  order.forEach(({ id: authorityId }) => {
    //if (!Object.prototype.hasOwnProperty.call(grouped, authorityId)) continue;
    const authorityData = grouped[authorityId];
    const { doc_alias, authorityName, companyId, years } = authorityData;

    // Authority row
    const authorityEl = $(`
      <div class='authority d-flex align-items-center justify-content-between'
           data-authority='${escapeHtml(authorityName)}'
           data-authorityid='${escapeHtml(authorityId)}'
           data-companyid='${escapeHtml(companyId)}'>
        <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${escapeHtml(authorityName)} (${escapeHtml(doc_alias)})</span>
        <i class="fa-solid fa-download fa-lg text-success download-icon ms-auto"
           title="Download all for ${escapeHtml(authorityName)}"
           data-level="authority"
           data-authorityid="${escapeHtml(authorityId)}"
           data-companyid="${escapeHtml(companyId)}"
           data-value="${escapeHtml(authorityName)}"></i>
      </div>
    `);

    const yearsContainer = $('<div class="years ms-4"></div>').hide();

    for (const year in years) {
      if (!Object.prototype.hasOwnProperty.call(years, year)) continue;
      const yearEl = $(`
        <div class='year d-flex align-items-center justify-content-between'
             data-year='${escapeHtml(year)}'
             data-authorityid='${escapeHtml(authorityId)}'
             data-companyid='${escapeHtml(companyId)}'>
          <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${escapeHtml(year)}</span>
          <i class="fa-solid fa-download fa-md text-primary download-icon"
             title="Download all for ${escapeHtml(authorityName)} ${escapeHtml(year)}"
             data-level="year"
             data-authorityid='${escapeHtml(authorityId)}'
             data-companyid='${escapeHtml(companyId)}'
             data-year='${escapeHtml(year)}'
             data-value='${escapeHtml(year)}'></i>
        </div>
      `);
      const monthsContainer = $('<div class="months"></div>').hide();

      for (const month in years[year]) {
        if (!Object.prototype.hasOwnProperty.call(years[year], month)) continue;
        const monthEl = $(`
          <div class='month d-flex align-items-center justify-content-between'
               data-month='${escapeHtml(month)}'
               data-year='${escapeHtml(year)}'
               data-authorityid='${escapeHtml(authorityId)}'
               data-companyid='${escapeHtml(companyId)}'>

            <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${escapeHtml(month)}</span>

            <div class="d-flex align-items-center ms-auto" style="gap: 6px;">
                <!-- Action Dropdown for Month: View, Download, Favourite -->
                <div class="action-dropdown month-action-dropdown"
                     data-authority-name="${escapeHtml(authorityName)}"
                     data-company-id="${escapeHtml(companyId)}"
                     data-month="${escapeHtml(month)}"
                     data-year="${escapeHtml(year)}"
                     data-authority-id="${escapeHtml(authorityId)}"
                     data-view-url="<?= base_url('company/view_documents/') ?>${escapeHtml(authorityId)}/${escapeHtml(companyId)}/${escapeHtml(year)}/${escapeHtml(month)}">
                  <button type="button" class="action-dropdown__btn action-dropdown__btn--primary action-toggle-btn">
                    <i class="fa fa-cog"></i> Action <i class="fa fa-chevron-down" style="font-size:0.6rem;"></i>
                  </button>
                  <div class="action-dropdown__menu">
                    <a href="<?= base_url('company/view_documents/') ?>${escapeHtml(authorityId)}/${escapeHtml(companyId)}/${escapeHtml(year)}/${escapeHtml(month)}" target="_blank" class="action-dropdown__item action-dropdown__item--view">
                      <i class="fa fa-eye"></i> View
                    </a>
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--download month-download-btn"
                       data-level="month"
                       data-authorityid="${escapeHtml(authorityId)}"
                       data-companyid="${escapeHtml(companyId)}"
                       data-year="${escapeHtml(year)}"
                       data-value="${escapeHtml(month)}">
                      <i class="fa fa-cloud-download"></i> Download
                    </a>
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--favourite month-favourite-btn">
                      <i class="fa fa-star"></i> Favourite
                    </a>
                  </div>
                </div>

                <!-- Notification Dropdown for Month: Print, Email, WhatsApp -->
                <div class="action-dropdown month-notification-dropdown"
                     data-authority-name="${escapeHtml(authorityName)}"
                     data-company-id="${escapeHtml(companyId)}"
                     data-month="${escapeHtml(month)}"
                     data-year="${escapeHtml(year)}"
                     data-authority-id="${escapeHtml(authorityId)}"
                     data-view-url="<?= base_url('company/view_documents/') ?>${escapeHtml(authorityId)}/${escapeHtml(companyId)}/${escapeHtml(year)}/${escapeHtml(month)}">
                  <button type="button" class="action-dropdown__btn action-dropdown__btn--success action-toggle-btn">
                    <i class="fa fa-bell"></i> Notify <i class="fa fa-chevron-down" style="font-size:0.6rem;"></i>
                  </button>
                  <div class="action-dropdown__menu">
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--print month-print-btn">
                      <i class="fa fa-print"></i> Print
                    </a>
                    <div class="action-dropdown__divider"></div>
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail month-notification" data-type="mail">
                      <i class="fa fa-envelope"></i> Email
                    </a>
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp month-notification" data-type="whatsapp">
                      <i class="fab fa-whatsapp"></i> WhatsApp
                    </a>
                  </div>
                </div>
            </div>
          </div>
        `);
        const docsContainer = $('<div class="documents"></div>').hide();

        years[year][month].forEach(doc => {
          console.log("RAW FILE SIZE:", doc.file_size, typeof doc.file_size);
          console.log("FORMATTED:", formatFileSize(doc.file_size));
          const hasFile = doc.file_name && doc.file_name.trim() !== "";
          const docItem = $(`
            <div class="doc-item d-flex justify-content-between align-items-center border-bottom py-1"
                 id="doc-item-${escapeHtml(doc.doc_id)}"
                 data-is-favourite="${doc.is_favourite ? 1 : 0}">
              <div class="doc-meta-row">
                <span class="doc-name">${escapeHtml(doc.name)}</span>
              
                <!-- Meta Info (only if file exists) -->
                ${hasFile ? `
                  <span>Uploaded On: ${escapeHtml(formatDate(doc.uploaded_at))}</span> &nbsp;|&nbsp;
                  <span>By: ${escapeHtml(doc.uploaded_by || "—")}</span>&nbsp;|&nbsp;
                  <span>Size: ${formatFileSize(doc.file_size)}</span> 
                ` : ""}
              </div>
              <div class="doc-actions d-flex align-items-center" style="gap: 4px;">
                ${hasFile ? `
                  <!-- Action Dropdown for Document: View, Download, Favourite, Edit, Delete -->
                  <div class="action-dropdown doc-action-dropdown"
                       data-doc-name="${escapeHtml(doc.name)}"
                       data-doc-id="${escapeHtml(doc.doc_id)}"
                       data-file-name="${escapeHtml(doc.file_name)}"
                       data-file-url="${base_url}uploads/documents/${doc.file_name}">
                    <button type="button" class="action-dropdown__btn action-dropdown__btn--primary action-toggle-btn">
                      <i class="fa fa-cog"></i> Action <i class="fa fa-chevron-down"></i>
                    </button>
                    <div class="action-dropdown__menu">
                      <a href="${base_url}uploads/documents/${doc.file_name}" target="_blank" class="action-dropdown__item action-dropdown__item--view">
                        <i class="fa fa-eye"></i> View
                      </a>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--download doc-download-btn" data-filename="${escapeHtml(doc.file_name)}">
                        <i class="fa fa-cloud-download"></i> Download
                      </a>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--favourite doc-favourite-btn">
                        <i class="fa fa-star"></i> Favourite
                      </a>
                      <div class="action-dropdown__divider"></div>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--edit doc-edit-btn" data-id="${escapeHtml(doc.doc_id)}">
                        <i class="fa fa-edit"></i> Edit
                      </a>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--delete doc-delete-btn" data-id="${escapeHtml(doc.doc_id)}">
                        <i class="fa fa-trash"></i> Delete
                      </a>
                    </div>
                  </div>
                  
                  <!-- Notification Dropdown for Document: Print, Email, WhatsApp -->
                  <div class="action-dropdown doc-notification-dropdown"
                       data-doc-name="${escapeHtml(doc.name)}"
                       data-doc-id="${escapeHtml(doc.doc_id)}"
                       data-file-url="${base_url}uploads/documents/${doc.file_name}">
                    <button type="button" class="action-dropdown__btn action-dropdown__btn--success action-toggle-btn">
                      <i class="fa fa-bell"></i> Notify <i class="fa fa-chevron-down"></i>
                    </button>
                    <div class="action-dropdown__menu">
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--print doc-print-btn">
                        <i class="fa fa-print"></i> Print
                      </a>
                      <div class="action-dropdown__divider"></div>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail doc-notification" data-type="mail">
                        <i class="fa fa-envelope"></i> Email
                      </a>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp doc-notification" data-type="whatsapp">
                        <i class="fab fa-whatsapp"></i> WhatsApp
                      </a>
                    </div>
                  </div>
                ` : `
                  <a href="#" class="openUploadModal" data-id="${doc.doc_id}" title="Upload"><i class="fa fa-upload fa-lg text-secondary"></i></a>
                `}
              </div>
            </div>
          `);
          docsContainer.append(docItem);
        });

        monthsContainer.append(monthEl).append(docsContainer);
      }

      yearsContainer.append(yearEl).append(monthsContainer);
    }

    $("#timeline").append(authorityEl).append(yearsContainer);
  });
}

// Build timeline with Year as primary grouping (Year → Document Head → Month → Documents)
function buildTimelineByYear(documents) {
  console.log("buildTimelineByYear documents:", documents);

  $("#timeline").empty();

  if (!documents || documents.length === 0) {
    $("#timeline").html(`
      <div class="empty-state">
        <i class="fa fa-calendar-times"></i>
        <h5>No Documents Found</h5>
        <p>No documents match the selected year filters</p>
      </div>
    `);
    return;
  }

  const companyId = '<?= $company_list[0]['id']; ?>';
  
  // Group by Year first, then by Authority
  const groupedByYear = {};
  
  documents.forEach(d => {
    const authorityName = d.authority || d.type_name || 'Unknown Authority';
    const authorityId = d.authority_type_id || d.authority_id || d.type_id || 'unknown';
    const year = d.year || d.document_year || 'Unknown Year';
    const monthRaw = d.month || d.document_month || '01';
    const monthNum = String(monthRaw).padStart(2, '0');
    const monthName = getMonthName(monthNum);
    const doc_alias = d.doc_alias || d.alias_name || '';
    
    const doc = {
      doc_id: d.doc_id || d.id || d.ud_id,
      name: d.name || d.document_name || 'Untitled',
      file_name: d.file_name || d.uploaded_file || '',
      uploaded_at: d.uploaded_at || d.created_at || d.upload_time || '',
      uploaded_by: d.uploaded_by || d.user_id || d.uploaded_user || '',
      file_size: d.file_size || d.size || "",
      is_favourite: d.is_favourite || 0
    };

    // Group by Year -> Authority -> Month
    if (!groupedByYear[year]) {
      groupedByYear[year] = {};
    }
    
    if (!groupedByYear[year][authorityId]) {
      groupedByYear[year][authorityId] = { 
        authorityName, 
        doc_alias, 
        months: {} 
      };
    }
    
    if (!groupedByYear[year][authorityId].months[monthName]) {
      groupedByYear[year][authorityId].months[monthName] = [];
    }
    
    groupedByYear[year][authorityId].months[monthName].push(doc);
  });

  // Sort years descending (newest first)
  const sortedYears = Object.keys(groupedByYear).sort((a, b) => b - a);

  // Render timeline with Year as primary
  sortedYears.forEach(year => {
    // Year row (Primary level - blue)
    const yearEl = $(`
      <div class='year year-level-primary d-flex align-items-center justify-content-between'
           data-year='${escapeHtml(year)}'>
        <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${escapeHtml(year)}</span>
        <i class="fa-solid fa-download fa-lg download-icon ms-auto"
           title="Download all for ${escapeHtml(year)}"
           style="color: white;"
           data-level="year-all"
           data-companyid="${escapeHtml(companyId)}"
           data-year="${escapeHtml(year)}"></i>
      </div>
    `);

    const authoritiesContainer = $('<div class="authorities ms-4"></div>').hide();
    
    // Sort authorities alphabetically
    const sortedAuthorities = Object.keys(groupedByYear[year]).sort((a, b) => {
      return groupedByYear[year][a].authorityName.localeCompare(groupedByYear[year][b].authorityName);
    });

    sortedAuthorities.forEach(authorityId => {
      const authorityData = groupedByYear[year][authorityId];
      const { authorityName, doc_alias, months } = authorityData;

      // Authority row (Secondary level - Dark Blue)
      const authorityEl = $(`
        <div class='authority dochead-level-secondary d-flex align-items-center justify-content-between'
             data-authority='${escapeHtml(authorityName)}'
             data-authorityid='${escapeHtml(authorityId)}'
             data-year='${escapeHtml(year)}'
             data-companyid='${escapeHtml(companyId)}'>
          <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${escapeHtml(authorityName)} ${doc_alias ? '(' + escapeHtml(doc_alias) + ')' : ''}</span>
          <i class="fa-solid fa-download fa-md download-icon"
             title="Download all for ${escapeHtml(authorityName)} ${escapeHtml(year)}"
             style="color: white;"
             data-level="authority-year"
             data-authorityid="${escapeHtml(authorityId)}"
             data-companyid="${escapeHtml(companyId)}"
             data-year="${escapeHtml(year)}"></i>
        </div>
      `);

      const monthsContainer = $('<div class="months ms-4"></div>').hide();

      // Sort months
      const monthOrder = ["January", "February", "March", "April", "May", "June", 
                          "July", "August", "September", "October", "November", "December"];
      const sortedMonths = Object.keys(months).sort((a, b) => monthOrder.indexOf(a) - monthOrder.indexOf(b));

      sortedMonths.forEach(month => {
        const monthEl = $(`
          <div class='month d-flex align-items-center justify-content-between'
               data-month='${escapeHtml(month)}'
               data-year='${escapeHtml(year)}'
               data-authorityid='${escapeHtml(authorityId)}'
               data-companyid='${escapeHtml(companyId)}'>
            <span><i class="fa-solid fa-caret-right me-2 toggle-icon"></i> ${escapeHtml(month)}</span>
            
            <div class="d-flex align-items-center ms-auto" style="gap: 6px;">
                <!-- Action Dropdown for Month -->
                <div class="action-dropdown month-action-dropdown"
                     data-authority-name="${escapeHtml(authorityName)}"
                     data-company-id="${escapeHtml(companyId)}"
                     data-month="${escapeHtml(month)}"
                     data-year="${escapeHtml(year)}"
                     data-authority-id="${escapeHtml(authorityId)}"
                     data-view-url="<?= base_url('company/view_documents/') ?>${escapeHtml(authorityId)}/${escapeHtml(companyId)}/${escapeHtml(year)}/${escapeHtml(month)}">
                  <button type="button" class="action-dropdown__btn action-dropdown__btn--primary action-toggle-btn">
                    <i class="fa fa-cog"></i> Action <i class="fa fa-chevron-down" style="font-size:0.6rem;"></i>
                  </button>
                  <div class="action-dropdown__menu">
                    <a href="<?= base_url('company/view_documents/') ?>${escapeHtml(authorityId)}/${escapeHtml(companyId)}/${escapeHtml(year)}/${escapeHtml(month)}" target="_blank" class="action-dropdown__item action-dropdown__item--view">
                      <i class="fa fa-eye"></i> View
                    </a>
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--download month-download-btn"
                       data-level="month"
                       data-authorityid="${escapeHtml(authorityId)}"
                       data-companyid="${escapeHtml(companyId)}"
                       data-year="${escapeHtml(year)}"
                       data-value="${escapeHtml(month)}">
                      <i class="fa fa-cloud-download"></i> Download
                    </a>
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--favourite month-favourite-btn">
                      <i class="fa fa-star"></i> Favourite
                    </a>
                  </div>
                </div>

                <!-- Notification Dropdown for Month -->
                <div class="action-dropdown month-notification-dropdown"
                     data-authority-name="${escapeHtml(authorityName)}"
                     data-company-id="${escapeHtml(companyId)}"
                     data-month="${escapeHtml(month)}"
                     data-year="${escapeHtml(year)}"
                     data-authority-id="${escapeHtml(authorityId)}"
                     data-view-url="<?= base_url('company/view_documents/') ?>${escapeHtml(authorityId)}/${escapeHtml(companyId)}/${escapeHtml(year)}/${escapeHtml(month)}">
                  <button type="button" class="action-dropdown__btn action-dropdown__btn--success action-toggle-btn">
                    <i class="fa fa-bell"></i> Notify <i class="fa fa-chevron-down" style="font-size:0.6rem;"></i>
                  </button>
                  <div class="action-dropdown__menu">
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--print month-print-btn">
                      <i class="fa fa-print"></i> Print
                    </a>
                    <div class="action-dropdown__divider"></div>
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail month-notification" data-type="mail">
                      <i class="fa fa-envelope"></i> Email
                    </a>
                    <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp month-notification" data-type="whatsapp">
                      <i class="fab fa-whatsapp"></i> WhatsApp
                    </a>
                  </div>
                </div>
            </div>
          </div>
        `);

        const docsContainer = $('<div class="documents"></div>').hide();

        months[month].forEach(doc => {
          const hasFile = doc.file_name && doc.file_name.trim() !== "";
          const docItem = $(`
            <div class="doc-item d-flex justify-content-between align-items-center border-bottom py-1"
                 id="doc-item-${escapeHtml(doc.doc_id)}"
                 data-is-favourite="${doc.is_favourite ? 1 : 0}">
              <div class="doc-meta-row">
                <span class="doc-name">${escapeHtml(doc.name)}</span>
                ${hasFile ? `
                  <span>Uploaded On: ${escapeHtml(formatDate(doc.uploaded_at))}</span> &nbsp;|&nbsp;
                  <span>By: ${escapeHtml(doc.uploaded_by || "—")}</span>&nbsp;|&nbsp;
                  <span>Size: ${formatFileSize(doc.file_size)}</span>
                ` : ""}
              </div>
              <div class="doc-actions d-flex align-items-center" style="gap: 4px;">
                ${hasFile ? `
                  <!-- Action Dropdown for Document -->
                  <div class="action-dropdown doc-action-dropdown"
                       data-doc-name="${escapeHtml(doc.name)}"
                       data-doc-id="${escapeHtml(doc.doc_id)}"
                       data-file-name="${escapeHtml(doc.file_name)}"
                       data-file-url="${base_url}uploads/documents/${doc.file_name}">
                    <button type="button" class="action-dropdown__btn action-dropdown__btn--primary action-toggle-btn">
                      <i class="fa fa-cog"></i> Action <i class="fa fa-chevron-down"></i>
                    </button>
                    <div class="action-dropdown__menu">
                      <a href="${base_url}uploads/documents/${doc.file_name}" target="_blank" class="action-dropdown__item action-dropdown__item--view">
                        <i class="fa fa-eye"></i> View
                      </a>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--download doc-download-btn" data-filename="${escapeHtml(doc.file_name)}">
                        <i class="fa fa-cloud-download"></i> Download
                      </a>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--favourite doc-favourite-btn">
                        <i class="fa fa-star"></i> Favourite
                      </a>
                      <div class="action-dropdown__divider"></div>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--edit doc-edit-btn" data-id="${escapeHtml(doc.doc_id)}">
                        <i class="fa fa-edit"></i> Edit
                      </a>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--delete doc-delete-btn" data-id="${escapeHtml(doc.doc_id)}">
                        <i class="fa fa-trash"></i> Delete
                      </a>
                    </div>
                  </div>
                  
                  <!-- Notification Dropdown for Document -->
                  <div class="action-dropdown doc-notification-dropdown"
                       data-doc-name="${escapeHtml(doc.name)}"
                       data-doc-id="${escapeHtml(doc.doc_id)}"
                       data-file-url="${base_url}uploads/documents/${doc.file_name}">
                    <button type="button" class="action-dropdown__btn action-dropdown__btn--success action-toggle-btn">
                      <i class="fa fa-bell"></i> Notify <i class="fa fa-chevron-down"></i>
                    </button>
                    <div class="action-dropdown__menu">
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--print doc-print-btn">
                        <i class="fa fa-print"></i> Print
                      </a>
                      <div class="action-dropdown__divider"></div>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail doc-notification" data-type="mail">
                        <i class="fa fa-envelope"></i> Email
                      </a>
                      <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp doc-notification" data-type="whatsapp">
                        <i class="fab fa-whatsapp"></i> WhatsApp
                      </a>
                    </div>
                  </div>
                ` : `
                  <a href="#" class="openUploadModal" data-id="${doc.doc_id}" title="Upload"><i class="fa fa-upload fa-lg text-secondary"></i></a>
                `}
              </div>
            </div>
          `);
          docsContainer.append(docItem);
        });

        monthsContainer.append(monthEl).append(docsContainer);
      });

      authoritiesContainer.append(authorityEl).append(monthsContainer);
    });

    $("#timeline").append(yearEl).append(authoritiesContainer);
  });
}

function escapeHtml(str) {
  if (str == null) return '';
  return String(str)
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

function getMonthName(num) {
  const months = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
  const index = parseInt(num, 10) - 1;
  return months[index] || num;
}
// Toggle behavior
/*$(document).on('click', '.authority', function() {
  $(this).next('.years').slideToggle();
});
$(document).on('click', '.year', function() {
  $(this).next('.months').slideToggle();
});
$(document).on('click', '.month', function() {
  $(this).next('.documents').slideToggle();
}); */

let clickTimer = null;

$(document).on('click', '.authority, .year, .month', function (e) {
  // Prevent conflict with dropdowns or icons
  if (
    $(e.target).is('select, option, input, textarea, button, label') ||
    $(e.target).closest('.dropdown, .dropdown-menu, .multiselect-container, .action-dropdown').length > 0 ||
    $(e.target).hasClass('download-icon') ||
    $(e.target).hasClass('action-dropdown__btn') ||
    ($(e.target).is('i') && !$(e.target).hasClass('toggle-icon'))
  ) {
    return;
  }

  const $this = $(this);

  // Handle single vs double click with timer
  if (clickTimer) {
    clearTimeout(clickTimer);
    clickTimer = null;
    handleDoubleClick($this);
  } else {
    clickTimer = setTimeout(() => {
      handleSingleClick($this);
      clickTimer = null;
    }, 250); // 250ms threshold for double click
  }
});

function handleSingleClick($this) {
  // Toggle only the immediate next level
  const caret = $this.find('.toggle-icon').first();
  caret.toggleClass('fa-caret-right fa-caret-down');

  // Support both Document Head view and Year view structures
  if ($this.hasClass('authority') && !$this.hasClass('dochead-level-secondary')) {
    // Document Head view: authority -> years
    $this.next('.years').slideToggle(200);
  } else if ($this.hasClass('authority') && $this.hasClass('dochead-level-secondary')) {
    // Year view: authority (secondary) -> months
    $this.next('.months').slideToggle(200);
  } else if ($this.hasClass('year') && $this.hasClass('year-level-primary')) {
    // Year view: year (primary) -> authorities
    $this.next('.authorities').slideToggle(200);
  } else if ($this.hasClass('year') && !$this.hasClass('year-level-primary')) {
    // Document Head view: year -> months
    $this.next('.months').slideToggle(200);
  } else if ($this.hasClass('month')) {
    $this.next('.documents').slideToggle(200);
  }
}

function handleDoubleClick($this) {
  // Toggle all nested levels recursively
  const caret = $this.find('.toggle-icon').first();
  const isOpen = caret.hasClass('fa-caret-down');

  caret.toggleClass('fa-caret-right fa-caret-down');

  let targetContainer = null;
  
  // Support both Document Head view and Year view structures
  if ($this.hasClass('authority') && !$this.hasClass('dochead-level-secondary')) {
    targetContainer = $this.next('.years');
  } else if ($this.hasClass('authority') && $this.hasClass('dochead-level-secondary')) {
    targetContainer = $this.next('.months');
  } else if ($this.hasClass('year') && $this.hasClass('year-level-primary')) {
    targetContainer = $this.next('.authorities');
  } else if ($this.hasClass('year') && !$this.hasClass('year-level-primary')) {
    targetContainer = $this.next('.months');
  } else if ($this.hasClass('month')) {
    targetContainer = $this.next('.documents');
  }

  if (!targetContainer || !targetContainer.length) return;

  if (isOpen) {
    // Collapse all children
    targetContainer.find('.years, .authorities, .months, .documents').slideUp(200);
    targetContainer.slideUp(200);
    targetContainer
      .find('.toggle-icon')
      .removeClass('fa-caret-down')
      .addClass('fa-caret-right');
  } else {
    // Expand all children
    targetContainer.slideDown(200);
    targetContainer.find('.years, .authorities, .months, .documents').slideDown(200);
    targetContainer
      .find('.toggle-icon')
      .removeClass('fa-caret-right')
      .addClass('fa-caret-down');
  }
}

// Fetch data on page load
$(document).ready(function() {
  // ===== On page load - fetch all documents with default view (Document Head)
  fetchDocumentsWithFilters([], []);
});

$(document).on('click', '.download-icon', function (e) {
  e.preventDefault();
  const level = $(this).data('level');
  const authorityId = $(this).data('authorityid');
  const companyId = $('input[name="company_id"]').val();
  
  const year = $(this).data('year');
  const value = $(this).data('value');
	
  let url = '';
  
  // Doc Head View levels
  if (level === 'authority') {
    // Download all documents for an authority (all years)
    url = "<?= base_url('company/download_all/') ?>" + authorityId + "/" + companyId;
  }
  else if (level === 'year') {
    // Download all documents for a specific year under an authority
    url = "<?= base_url('company/download_year/') ?>" + authorityId + "/" + companyId + "/" + year;
  }
  else if (level === 'month') {
    // Download all documents for a specific month
    url = "<?= base_url('company/download_month/') ?>" + authorityId + "/" + companyId + "/" + year + "/" + value;
  }
  // Year View levels
  else if (level === 'year-all') {
    // Download all documents for a year (across all authorities)
    url = "<?= base_url('company/download_year_all/') ?>" + companyId + "/" + year;
  }
  else if (level === 'authority-year') {
    // Download all documents for a specific authority within a year
    url = "<?= base_url('company/download_year/') ?>" + authorityId + "/" + companyId + "/" + year;
  }

  if (url) {
  window.location.href = url;
  }
});


var baseUrl = "<?= base_url(); ?>";

$(document).on('click', '.downloadDocument', function(e) {
    e.preventDefault();
    var docId = $(this).data('id');

    $.ajax({
        url: baseUrl + "company/downloadDocument/" + docId,
        type: "GET",
        dataType: "json",
        success: function(response) {
            if (response.error) {
                alert(response.error);
            } else {
                // Convert base64 file back into a downloadable file
                const link = document.createElement('a');
                link.href = 'data:application/octet-stream;base64,' + response.file_data;
                link.download = response.file_name;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        },
        error: function(xhr, status, error) {
            console.log("AJAX Error:", error);
        }
    });
});

/*function formatDate(dateStr) {
    if (!dateStr) return "—";

    const d = new Date(dateStr);
    if (isNaN(d)) return dateStr; // fallback if date is not valid

    const day = String(d.getDate()).padStart(2, "0");
    const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    const mon = months[d.getMonth()];
    const year = d.getFullYear();

    return `${day}-${mon}-${year}`;
}*/

function formatDate(dateStr) {
    if (!dateStr || dateStr === "0000-00-00" || dateStr === "0000-00-00 00:00:00") {
        return "—";
    }

    const d = new Date(dateStr.replace(/-/g, "/"));

    if (isNaN(d.getTime())) return "—";

    const day = String(d.getDate()).padStart(2, "0");
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const year = d.getFullYear();

    return `${day}-${month}-${year}`;
}

// =============================================
// ACTION DROPDOWN FUNCTIONS
// =============================================

// Store current dropdown context for floating menu actions
let currentDropdownData = {};

// Track if menu is open to prevent immediate close
let menuJustOpened = false;

// Event delegation for action toggle buttons
$(document).on('click', '.action-toggle-btn', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    console.log('Action button clicked');
    const button = this;
    const dropdown = $(button).closest('.action-dropdown');
    
    // Store data attributes for later use
    currentDropdownData = {
        ...dropdown.data(),
        // Also grab data from menu items for month download
        downloadData: dropdown.find('.month-download-btn').data() || {}
    };
    console.log('Dropdown data:', currentDropdownData);
    
    // Check if menu already exists - toggle it off
    const existingMenu = document.getElementById('floating-action-menu');
    if (existingMenu) {
        console.log('Removing existing menu');
        existingMenu.remove();
        document.removeEventListener('click', closeFloatingMenuHandler);
        return; // Toggle off - don't open new one
    }
    
    const menuTemplate = dropdown.find('.action-dropdown__menu')[0];
    console.log('Menu template found:', menuTemplate);
    
    if (!menuTemplate) {
        console.error('Menu template not found!');
        return;
    }
    
    // Clone the menu and create floating version
    const floatingMenu = menuTemplate.cloneNode(true);

    /* ===============================
   DISABLE FAVOURITE IF ALREADY ADDED
   =============================== */
    if (currentDropdownData.docId) {
      const $docItem = $('#doc-item-' + currentDropdownData.docId);
      const isFavourite = $docItem.data('is-favourite') == 1;

      if (isFavourite) {
        $(floatingMenu)
          .find('.doc-favourite-btn')
          .addClass('is-disabled')
          .html('<i class="fa fa-star"></i> Already in Favourites');
      }
    }

    floatingMenu.id = 'floating-action-menu';
    floatingMenu.style.display = 'block';
    floatingMenu.style.cssText = 'display: block !important;';
    
    console.log('Floating menu created:', floatingMenu);
    
    // Mark the dropdown type for styling and behavior
    if (dropdown.hasClass('doc-action-dropdown')) {
        floatingMenu.setAttribute('data-dropdown-type', 'document-action');
    } else if (dropdown.hasClass('doc-notification-dropdown')) {
        floatingMenu.setAttribute('data-dropdown-type', 'document-notification');
    } else if (dropdown.hasClass('month-action-dropdown')) {
        floatingMenu.setAttribute('data-dropdown-type', 'month-action');
    } else if (dropdown.hasClass('month-notification-dropdown')) {
        floatingMenu.setAttribute('data-dropdown-type', 'month-notification');
    } else {
        floatingMenu.setAttribute('data-dropdown-type', 'unknown');
    }
    
    // Get button position
    const rect = button.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    const viewportWidth = window.innerWidth;
    const menuHeight = 200; // Approximate menu height
    
    // Position the menu
    floatingMenu.style.position = 'fixed';
    
    // Adjust left position if it would go off screen
    let leftPos = rect.left;
    if (leftPos + 180 > viewportWidth) {
        leftPos = rect.right - 180;
    }
    floatingMenu.style.left = leftPos + 'px';
    
    // Check if there's enough space below
    if (rect.bottom + menuHeight > viewportHeight) {
        // Show above
        floatingMenu.style.bottom = (viewportHeight - rect.top + 5) + 'px';
        floatingMenu.style.top = 'auto';
    } else {
        // Show below
        floatingMenu.style.top = (rect.bottom + 5) + 'px';
        floatingMenu.style.bottom = 'auto';
    }
    
    floatingMenu.style.zIndex = '999999';
    
    document.body.appendChild(floatingMenu);
    console.log('Menu appended to body');
    
    // Set flag to prevent immediate close
    menuJustOpened = true;
    
    // Close menu when clicking outside - use a longer delay
    setTimeout(() => {
        menuJustOpened = false;
        document.addEventListener('click', closeFloatingMenuHandler);
        console.log('Click listener added');
    }, 100);
});

// Named handler for closing menu
function closeFloatingMenuHandler(e) {
    // Don't close if we just opened the menu
    if (menuJustOpened) {
        console.log('Menu just opened, not closing');
        return;
    }
    
    // Don't close if clicking inside the menu
    const menu = document.getElementById('floating-action-menu');
    if (menu && menu.contains(e.target)) {
        console.log('Click inside menu, not closing');
        return;
    }
    
    console.log('Closing menu');
    closeFloatingMenu();
}

// Event delegation for month-level notification clicks
$(document).on('click', '#floating-action-menu .month-notification', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const type = $(this).data('type');
    const data = currentDropdownData;
    
    handleMonthNotification(
        type,
        data.authorityName,
        data.companyId,
        data.month,
        data.year,
        data.authorityId
    );
});

// Event delegation for document-level notification clicks
$(document).on('click', '#floating-action-menu .doc-notification', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const type = $(this).data('type');
    const data = currentDropdownData;
    
    handleDocNotification(
        type,
        data.docName,
        data.docId,
        data.fileUrl
    );
});

// Event delegation for document print button
$(document).on('click', '#floating-action-menu .doc-print-btn', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const data = currentDropdownData;
    printDocument(data.fileUrl);
});

// Event delegation for month print button
$(document).on('click', '#floating-action-menu .month-print-btn', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const data = currentDropdownData;
    const viewUrl = data.viewUrl;
    if (viewUrl) {
        printDocument(viewUrl);
    } else {
        Swal.fire('Info', 'Print functionality for this month', 'info');
    }
    closeFloatingMenu();
});

// Event delegation for month download button
$(document).on('click', '#floating-action-menu .month-download-btn', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const $this = $(this);
    const level = $this.data('level');
    const authorityId = $this.data('authorityid');
    const companyId = $this.data('companyid');
    const year = $this.data('year');
    const value = $this.data('value');
    
    closeFloatingMenu();
    
    // Trigger existing download functionality
    triggerDownload(level, authorityId, companyId, year, value);
});

// Event delegation for month favourite button
$(document).on('click', '#floating-action-menu .month-favourite-btn', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const data = currentDropdownData;
    closeFloatingMenu();
    
    // In this view, authorityId is actually the document head (sub_type) ID
    // The naming is based on the UI hierarchy: Authority → Year → Month
    const typeId = data.authorityId;
    const companyId = data.companyId;
    const year = data.year;
    const month = data.month;
    const authorityName = data.authorityName;
    
    console.log('Adding month favourite:', { companyId, typeId, year, month });
    
    // Call the month-level favourite API
    $.ajax({
        url: base_url + 'dashboard/addMonthFavourite',
        type: 'POST',
        data: {
            company_id: companyId,
            type_id: typeId,
            authority_id: null, // Optional - actual authority table ID if available
            year: year,
            month: month
        },
        dataType: 'json'
    }).done(function(response) {
        if (response.success) {
            Swal.fire({
                icon: 'success',
                title: 'Added to Favourites',
                text: `${authorityName} - ${month} ${year} added to favourites.`,
                timer: 2500,
                showConfirmButton: false
            });
        } else {
            Swal.fire({
                icon: 'warning',
                title: 'Cannot Add',
                text: response.message || 'Failed to add to favourites.',
                timer: 2500,
                showConfirmButton: false
            });
        }
    }).fail(function() {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Failed to add to favourites. Please try again.',
            timer: 2000,
            showConfirmButton: false
        });
    });
});

// Event delegation for document download button
$(document).on('click', '#floating-action-menu .doc-download-btn', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const data = currentDropdownData;
    closeFloatingMenu();
    
    // Trigger download for single document using query parameter (handles special chars in filename)
    if (data.fileName) {
        window.location.href = base_url + 'company/downloadSingleDocument?file=' + encodeURIComponent(data.fileName);
    } else if (data.fileUrl) {
        window.open(data.fileUrl, '_blank');
    }
});

// Event delegation for document favourite button
$(document).on('click', '#floating-action-menu .doc-favourite-btn', function(e) {

      if ($(this).hasClass('is-disabled')) {
      e.preventDefault();
      return;
    }
    e.stopPropagation();
    e.preventDefault();
    
    const data = currentDropdownData;
    const docId = data.docId;
    closeFloatingMenu();
    
    if (!docId) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Could not identify the document.',
            timer: 2000,
            showConfirmButton: false
        });
        return;
    }
    
    $.ajax({
        url: base_url + 'dashboard/addToFavourite',
        type: 'POST',
        data: { upload_id: docId },
        dataType: 'json',
        success: function(response) {
          if (response.data.is_favourite) {
            $('#doc-item-' + docId)
              .attr('data-is-favourite', '1')
              .data('is-favourite', 1);
          }
            if (response.success) {
                if (response.data.is_favourite) {
    Swal.fire({
        icon: 'success',
        title: 'Added to Favourites',
        text: `"${data.docName}" has been added to favourites.`,
        timer: 2000,
        showConfirmButton: false
                    });
                } else {
                    Swal.fire({
                        icon: 'info',
                        title: 'Removed from Favourites',
                        text: `"${data.docName}" has been removed from favourites.`,
                        timer: 2000,
                        showConfirmButton: false
                    });
                }
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: response.message || 'Failed to update favourite status.',
                    timer: 2000,
                    showConfirmButton: false
                });
            }
        },
        error: function() {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Failed to connect to server.',
                timer: 2000,
                showConfirmButton: false
            });
        }
    });
});

// Event delegation for document edit button
$(document).on('click', '#floating-action-menu .doc-edit-btn', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const data = currentDropdownData;
    const docId = data.docId;
    closeFloatingMenu();
    
    // Trigger the existing edit modal functionality
    $('.openEditModal[data-id="' + docId + '"]').click();
    
    // If the above doesn't work, manually trigger the edit modal
    if (docId) {
        $.ajax({
            url: "<?= base_url('company/getDocument'); ?>",
            type: "POST",
            data: { 
                doc_id: docId, 
                "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>" 
            },
            dataType: "json",
            success: function(res){
                if(res.status === 'success'){
                    $('#edit_doc_id').val(res.data.id);
                    $('#edit_document_name').val(res.data.document_name);
                    $('#uploaded_file').html(res.data.file_name || '<i>No file uploaded</i>');
                    $('#editMsg').html('');
                    const editModal = new bootstrap.Modal(document.getElementById('editModal'));
                    editModal.show();
                } else {
                    Swal.fire('Error', res.message, 'error');
                }
            },
            error: function(){
                Swal.fire('Error', 'Error fetching document details.', 'error');
            }
        });
    }
});

// Event delegation for document delete button
$(document).on('click', '#floating-action-menu .doc-delete-btn', function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    const data = currentDropdownData;
    const docId = data.docId;
    closeFloatingMenu();
    
    if (docId) {
        // First check if document can be deleted (master/sub validation)
        $.post('<?= base_url('company/checkDocumentDeletable'); ?>', { 
            doc_id: docId, 
            "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>"
        }, checkRes => {
            if (!checkRes.can_delete) {
                Swal.fire({
                    icon: 'error',
                    title: 'Cannot Delete Master Document',
                    html: `<p>${checkRes.message}</p>`,
                    confirmButtonColor: '#dc2626'
                });
                return;
            }
            
            // Document can be deleted, show confirmation
        Swal.fire({
            title: 'Are you sure?',
            text: 'You will not be able to recover this document!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#dc2626'
        }).then(result => {
            if(result.isConfirmed){
                $.post('<?= base_url('company/deleteDocument'); ?>', { 
                    doc_id: docId, 
                    "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>"
                }, res => {
                    if(res.status === "success"){
                        const $docItem = $('#doc-item-' + docId);
                        const $parent = $docItem.parent();
                        $docItem.remove();
                        cleanEmptyContainers($parent);
                        Swal.fire('Deleted!', 'Document deleted successfully.', 'success');
                    } else {
                        Swal.fire('Error', res.message, 'error');
                    }
                }, 'json');
            }
        });
        }, 'json');
    }
});

// Helper function to trigger download
function triggerDownload(level, authorityId, companyId, year, value) {
    // Use same URL format as download icons
    let url = '';
    if (level === 'authority') {
        url = base_url + 'company/download_all/' + authorityId + '/' + companyId;
    } else if (level === 'year') {
        url = base_url + 'company/download_year/' + authorityId + '/' + companyId + '/' + year;
    } else if (level === 'month') {
        url = base_url + 'company/download_month/' + authorityId + '/' + companyId + '/' + year + '/' + value;
    }
    
    if (url) {
        window.location.href = url;
    }
}

function closeFloatingMenu() {
    const menu = document.getElementById('floating-action-menu');
    if (menu) {
        menu.remove();
        console.log('Menu removed');
    }
    document.removeEventListener('click', closeFloatingMenuHandler);
    menuJustOpened = false;
}

// Handle month-level notifications
function handleMonthNotification(type, authorityName, companyId, month, year, authorityId) {
    closeFloatingMenu();
    
    const monthName = getMonthName(month);
    const period = monthName + ' ' + year;
    
    if (type === 'mail') {
        Swal.fire({
            title: '<i class="fa fa-envelope text-primary"></i> Send Email Notification',
            html: `
                <div class="text-start">
                    <p class="mb-3 text-muted">Send reminder for <strong>${authorityName}</strong></p>
                    <div class="mb-3">
                        <label class="form-label fw-bold" style="font-size:0.9rem;">Subject</label>
                        <input type="text" id="email-subject" class="form-control" value="Document Shared: ${authorityName} - ${period}" style="width:100%;" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold" style="font-size:0.9rem;">Recipient Email</label>
                        <input type="email" id="recipient-email" class="form-control" placeholder="Enter email address" style="width:100%;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold" style="font-size:0.9rem;">Additional Message (Optional)</label>
                        <textarea id="additional-message" class="form-control" rows="3" placeholder="Add any additional notes..." style="width:100%;"></textarea>
                    </div>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: '<i class="fa fa-paper-plane"></i> Send Email',
            confirmButtonColor: '#3b82f6',
            cancelButtonText: 'Cancel',
            width: '450px',
            preConfirm: () => {
                const email = document.getElementById('recipient-email').value;
                const subject = document.getElementById('email-subject').value;
                const message = document.getElementById('additional-message').value;
                if (!email) {
                    Swal.showValidationMessage('Please enter recipient email');
                    return false;
                }
                return { email, subject, message };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                sendMonthNotificationEmail(result.value.email, result.value.message, authorityName, companyId, month, year, authorityId, result.value.subject);
            }
        });
    } else if (type === 'whatsapp') {
        const uploadLink = `${base_url}upload/index/${companyId}?authority_id=${authorityId}&month=${month}&year=${year}&from=documents`;
        const message = encodeURIComponent(
            `📋 *Document Reminder*\n\n` +
            `Authority: ${authorityName}\n` +
            `Period: ${period}\n\n` +
            `Please upload the pending documents.\n\n` +
            `Upload Link: ${uploadLink}`
        );
        window.open(`https://wa.me/?text=${message}`, '_blank');
    }
}

// Send email for month level
function sendMonthNotificationEmail(email, additionalMessage, authorityName, companyId, month, year, authorityId, subject = null) {
    const monthName = getMonthName(month);
    const period = monthName + ' ' + year;
    const uploadLink = `${base_url}upload/index/${companyId}?authority_id=${authorityId}&month=${month}&year=${year}&from=documents`;
    const emailSubject = subject || `${authorityName} - ${period}`;
    
    Swal.fire({
        title: 'Sending...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });
    
    $.ajax({
        url: '<?= base_url('company/sendDocumentNotification'); ?>',
        type: 'POST',
        data: {
            email: email,
            subject: emailSubject,
            additional_message: additionalMessage,
            authority_name: authorityName,
            company_id: companyId,
            authority_id: authorityId,  // This is the type_id (document head ID)
            month: month,
            year: year,
            period: period,
            upload_link: uploadLink,
            "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>"
        },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                Swal.fire({
                    icon: 'success',
                    title: 'Email Sent!',
                    text: response.message || 'Notification email has been sent successfully.'
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Failed',
                    text: response.message || 'Failed to send email.'
                });
            }
        },
        error: function() {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Failed to send notification email.'
            });
        }
    });
}

// Handle document-level notifications
function handleDocNotification(type, docName, docId, fileUrl) {
    closeFloatingMenu();
    
    if (type === 'mail') {
        Swal.fire({
            title: '<i class="fa fa-envelope text-primary"></i> Send Email Notification',
            html: `
                <div class="text-start">
                    <p class="mb-3 text-muted">Send reminder for <strong>${docName}</strong></p>
                    <div class="mb-3">
                        <label class="form-label fw-bold" style="font-size:0.9rem;">Subject</label>
                        <input type="text" id="email-subject" class="form-control" value="Document: ${docName}" style="width:100%;" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold" style="font-size:0.9rem;">Recipient Email</label>
                        <input type="email" id="recipient-email" class="form-control" placeholder="Enter email address" style="width:100%;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold" style="font-size:0.9rem;">Additional Message (Optional)</label>
                        <textarea id="additional-message" class="form-control" rows="3" placeholder="Add any additional notes..." style="width:100%;"></textarea>
                    </div>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: '<i class="fa fa-paper-plane"></i> Send Email',
            confirmButtonColor: '#3b82f6',
            cancelButtonText: 'Cancel',
            width: '450px',
            preConfirm: () => {
                const email = document.getElementById('recipient-email').value;
                const subject = document.getElementById('email-subject').value;
                const message = document.getElementById('additional-message').value;
                if (!email) {
                    Swal.showValidationMessage('Please enter recipient email');
                    return false;
                }
                return { email, subject, message };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                sendDocumentShareEmail(result.value.email, result.value.message, docName, docId, fileUrl, result.value.subject);
            }
        });
    } else if (type === 'whatsapp') {
        const message = encodeURIComponent(
            `📄 *Document Shared*\n\n` +
            `Document: ${docName}\n\n` +
            `View/Download: ${fileUrl}`
        );
        window.open(`https://wa.me/?text=${message}`, '_blank');
    }
}

// Send email for document share
function sendDocumentShareEmail(email, additionalMessage, docName, docId, fileUrl, subject = null) {
    const emailSubject = subject || `Document Shared: ${docName}`;
    
    Swal.fire({
        title: 'Sending...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });
    
    $.ajax({
        url: '<?= base_url('company/shareDocumentEmail'); ?>',
        type: 'POST',
        data: {
            email: email,
            subject: emailSubject,
            additional_message: additionalMessage,
            document_name: docName,
            document_id: docId,
            file_url: fileUrl,
            "<?= $this->security->get_csrf_token_name(); ?>": "<?= $this->security->get_csrf_hash(); ?>"
        },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                Swal.fire({
                    icon: 'success',
                    title: 'Email Sent!',
                    text: response.message || 'Document shared successfully.'
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Failed',
                    text: response.message || 'Failed to send email.'
                });
            }
        },
        error: function() {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Failed to send email.'
            });
        }
    });
}

// Print document
function printDocument(fileUrl) {
    closeFloatingMenu();
    const printWindow = window.open(fileUrl, '_blank');
    if (printWindow) {
        printWindow.addEventListener('load', function() {
            printWindow.print();
        });
    }
}

function formatFileSize(size) {
  if (!size) return "—";

  const match = String(size).trim().match(/^([\d.]+)\s*(KB|MB)$/i);
  if (!match) return size;

  const value = parseFloat(match[1]);
  const unit = match[2].toUpperCase();

  // Already MB
  if (unit === "MB") {
    return value.toFixed(2) + " MB";
}

  // KB → MB (ALWAYS)
  const mb = value / 1024;
  return mb.toFixed(2) + " MB";
}

</script>
