<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<link rel="stylesheet" href="<?= base_url('public/assets/css/dashboard.css') ?>">

<div class="dashboard-container content">
  <!-- Dashboard Filters -->
  <div class="dashboard-filters">
    <div class="dashboard-filters__group">
      <label class="dashboard-filters__label">Company:</label>
      <div class="company-dropdown-wrapper">
        <button type="button" class="company-dropdown-btn" id="company-dropdown-btn" onclick="toggleCompanyDropdown(event)">
          <span id="company-dropdown-text">
            <?php 
              $selectedCount = empty($selected_companies) ? count($allowed_companies) : count($selected_companies);
              $totalCount = count($allowed_companies);
              if ($selectedCount == $totalCount) {
                echo 'All Companies (' . $totalCount . ')';
              } elseif ($selectedCount == 0) {
                echo 'Select Companies...';
              } else {
                echo $selectedCount . ' of ' . $totalCount . ' Companies';
              }
            ?>
          </span>
          <i class="fa fa-chevron-down company-dropdown-arrow"></i>
        </button>
        <div class="company-dropdown-menu" id="company-dropdown-menu">
          <div class="company-dropdown-actions">
            <button type="button" class="company-action-btn" onclick="event.stopPropagation(); selectAllCompanies();">Select All</button>
            <button type="button" class="company-action-btn" onclick="event.stopPropagation(); deselectAllCompanies();">Clear All</button>
          </div>
          <div class="company-dropdown-list">
            <?php if (!empty($allowed_companies)): ?>
              <?php foreach ($allowed_companies as $company): 
                $isSelected = empty($selected_companies) || in_array($company['id'], $selected_companies);
                
                $startYear = 2024; // default fallback
                if (!empty($company['co_start_date']) && $company['co_start_date'] !== '0000-00-00') {
                    $ts = strtotime($company['co_start_date']);
                    if ($ts !== false) {
                        $startYear = date('Y', $ts);
                    }
                }
              ?>
                <label class="company-checkbox-item">
                  <input type="checkbox" class="company-checkbox" value="<?= $company['id'] ?>" data-start-year="<?= $startYear ?>" <?= $isSelected ? 'checked' : '' ?>>
                  <span><?= htmlspecialchars($company['company_name']) ?></span>
                </label>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
      </div>
      <!-- Hidden select for form submission -->
      <select id="filter-company" class="dashboard-filters__select" multiple style="display: none;">
        <?php if (!empty($allowed_companies)): ?>
          <?php foreach ($allowed_companies as $company): 
            $isSelected = empty($selected_companies) || in_array($company['id'], $selected_companies);
          ?>
            <option value="<?= $company['id'] ?>" <?= $isSelected ? 'selected' : '' ?>><?= htmlspecialchars($company['company_name']) ?></option>
          <?php endforeach; ?>
        <?php endif; ?>
      </select>
    </div>
    
    <div class="dashboard-filters__group">
      <label class="dashboard-filters__label">Year: </label>
        <select id="filter-year" class="dashboard-filters__select">
          <option value="all" <?= $selected_year === 'all' ? 'selected' : '' ?>>Select All</option>
          <?php 
              $currentYear = date('Y');
              for ($y = $currentYear; $y >= 2020; $y--): 
          ?>
              <option value="<?= $y ?>" <?= $selected_year == $y ? 'selected' : '' ?>><?= $y ?></option>
          <?php endfor; ?>
      </select>
    </div>

    <button type="button" class="dashboard-filters__btn" onclick="applyFilters()">
      <i class="fa fa-search"></i> Apply
    </button>
    
    <button type="button" class="dashboard-filters__btn dashboard-filters__btn--reset" onclick="resetFilters()">
      <i class="fa fa-undo"></i> Reset
    </button>
    
    <!--<div class="filter-tags" id="filter-tags">
       Active filter tags will appear here 
    </div>-->
  </div>

  <!-- Stats Cards -->
  <div class="stats-grid">
    <!-- Favourite Card -->
    <div class="stat-card stat-card--favourite active" data-tab="favourite">
      <div class="stat-card__icon">
        <i class="fa fa-star"></i>
      </div>
      <div class="stat-card__badge">
        <span id="count-favourite"><?= $counts['favourites'] ?? 0 ?></span>
        <span>Favourites</span>
      </div>
    </div>

    <!-- Current Card -->
    <div class="stat-card stat-card--pending" data-tab="pending">
      <div class="stat-card__icon">
        <i class="fa fa-clock"></i>
      </div>
      <div class="stat-card__badge">
        <span id="count-pending"><?= $counts['pending'] ?? 0 ?></span>
        <span>Current (<?= date('M Y') ?>)</span>
      </div>
  </div>

    <!-- Overdue Card -->
    <div class="stat-card stat-card--overdue" data-tab="overdue">
      <div class="stat-card__icon">
        <i class="fa fa-exclamation-triangle"></i>
      </div>
      <div class="stat-card__badge">
        <span id="count-overdue"><?= $counts['overdue'] ?? 0 ?></span>
        <span>Overdue</span>
      </div>
    </div>

    <!-- Upcoming Card -->
    <div class="stat-card stat-card--upcoming" data-tab="upcoming">
      <div class="stat-card__icon">
        <i class="fa fa-calendar-alt"></i>
      </div>
      <div class="stat-card__badge">
        <span id="count-upcoming"><?= $counts['upcoming'] ?? 0 ?></span>
        <!--<span>Upcoming (<?= date('M Y', strtotime('+1 month')) ?>)</span>-->
        <span>Upcoming (<?= date('M Y', strtotime('first day of next month')) ?>)</span>
      </div>
    </div>

    <!-- Uploaded Card -->
    <div class="stat-card stat-card--uploaded" data-tab="uploaded">
      <div class="stat-card__icon">
        <i class="fa fa-check-circle"></i>
      </div>
      <div class="stat-card__badge">
        <span id="count-uploaded"><?= $counts['uploaded'] ?? 0 ?></span>
        <span>Completed</span>
      </div>
      </div>
    </div>

  <!-- Tab Content Area -->
  <div class="tab-content-area">
    <!-- Tab Header -->
    <div class="tab-header tab-header--favourite" id="tab-header">
      <h3 id="tab-title">
        <i class="fa fa-star"></i>
        <span>Favourite Documents</span>
        <span class="tab-header__badge" id="tab-count"><?= isset($counts['favourites']) ? $counts['favourites'] : 0 ?> items</span>
      </h3>
      <div class="tab-actions">
        <button type="button" class="btn btn-reset-search" onclick="resetColumnSearch()" title="Reset Search">
          <i class="fa fa-undo"></i> Reset
        </button>
        <a href="javascript:void(0)" class="btn" id="export-excel-btn" onclick="exportCurrentTab()">
          <i class="fa fa-download"></i> Export Excel
        </a>
      </div>
    </div>

    <!-- Tab Body -->
    <div class="tab-body" id="tab-content">
      <!-- Uploaded Tab -->
      <div id="tab-uploaded" class="tab-pane" style="display:none;">
        <table class="data-table" id="uploaded-table">
          <thead>
            <tr>
              <th width="5%">#</th>
              <th width="11%" class="sortable" data-sort="company">Company</th>
              <th width="9%" class="sortable" data-sort="authority">Authority</th>
              <th width="14%" class="sortable" data-sort="dochead">Document Head</th>
              <th width="9%" class="sortable" data-sort="frequency">Frequency</th>
              <th width="9%" class="sortable sort-desc" data-sort="period">Period</th>
              <th width="10%" class="sortable" data-sort="uploaded">Uploaded</th>
              <th width="8%">Action</th>
            </tr>
            <tr class="column-search">
              <th></th>
              <th><input type="text" class="column-search-input" data-column="1" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="2" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="3" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="4" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="5" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="6" placeholder="Search..."></th>
              <th></th>
            </tr>
          </thead>
           <tbody>
            <?php if (!empty($lazy_loading)): ?>
              <!-- Lazy loading: Show loading placeholder -->
              <tr class="loading-row">
                <td colspan="8">
                  <div class="tab-loading">
                    <div class="spinner"></div>
                    <span style="margin-left: 10px;">Loading uploaded documents...</span>
                  </div>
                </td>
              </tr>
            <?php elseif (!empty($show_documents)): ?>
              <?php $i = 1; foreach ($show_documents as $row): ?>
                <tr>
                  <td><?= $i++ ?>Test</td>
                  <td><span class="company-badge"><i class="fa fa-building"></i> <?= htmlspecialchars($row['company_name'] ?? '') ?></span></td>
                  <td><?= htmlspecialchars($row['authority_name'] ?? '') ?></td>
                  <td>
                    <strong><?= htmlspecialchars($row['type_name'] ?? '') ?></strong>
                    <br>
                    <small>
                      <span class="doc-count doc-count--uploaded"><?= $row['uploaded_count'] ?? 0 ?> uploaded</span>
                    </small>
                  </td>
                  <td><span class="frequency-badge"><?= htmlspecialchars($row['frequency'] ?? '') ?></span></td>
                  <td>
                    <?php 
                      $monthNum = (int)($row['document_month'] ?? 0);
                      $monthName = ($monthNum >= 1 && $monthNum <= 12) ? date("M", mktime(0, 0, 0, $monthNum, 1)) : '';
                    ?>
                    <span class="month-badge" style="background:#d1fae5; color:#059669;">
                      <?= $monthName ?> <?= $row['document_year'] ?? '' ?>
                    </span>
                  </td>
                  <td><?= !empty($row['uploaded_date']) ? date("d M Y", strtotime($row['uploaded_date'])) : '' ?></td>
                  <td>
                    <?php if (!empty($row['documents'])): ?>
                      <?php 
                        $monthNum = (int)($row['document_month'] ?? 1);
                        $monthName = date('F', mktime(0, 0, 0, $monthNum, 1));
                        $viewUrl = base_url('company/view_documents') . '/' . ($row['type_id'] ?? '') . '/' . ($row['company_id'] ?? '') . '/' . ($row['document_year'] ?? '') . '/' . $monthName;
                        $downloadUrl = base_url('company/download_month') . '/' . ($row['type_id'] ?? '') . '/' . ($row['company_id'] ?? '') . '/' . ($row['document_year'] ?? '') . '/' . $monthName;
                      ?>
                      <div class="action-dropdown">
                        <button class="action-dropdown__btn action-dropdown__btn--upcoming" onclick="toggleActionDropdown(this)">
                          <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="<?= $viewUrl ?>" target="_blank" class="action-dropdown__item action-dropdown__item--view"><i class="fa fa-eye text-primary"></i> View</a>
                          <a href="<?= $downloadUrl ?>" class="action-dropdown__item action-dropdown__item--download"><i class="fa fa-download text-success"></i> Download</a>
                          <div class="action-dropdown__divider"></div>
                          <div class="action-dropdown__submenu-label">Share Documents</div>
                          <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail" onclick="handleUploadedNotification('mail', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $monthName ?>', '<?= $row['document_year'] ?? '' ?>', '<?= $row['type_id'] ?? '' ?>', '<?= $row['company_id'] ?? '' ?>')"><i class="fa fa-envelope"></i> Email</a>
                          <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp" onclick="handleUploadedNotification('whatsapp', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $monthName ?>', '<?= $row['document_year'] ?? '' ?>', '<?= $row['type_id'] ?? '' ?>', '<?= $row['company_id'] ?? '' ?>')"><i class="fab fa-whatsapp"></i> WhatsApp</a>
                        </div>
                      </div>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr>
                <td colspan="8">
                  <div class="empty-state">
                    <i class="fa fa-folder-open"></i>
                    <p>No uploaded documents found</p>
                  </div>
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Favourite Tab (Default) -->
      <div id="tab-favourite" class="tab-pane">
        <table class="data-table" id="favourite-table">
          <thead>
            <tr>
              <th width="5%">#</th>
              <th width="12%" class="sortable" data-sort="company">Company</th>
              <th width="10%" class="sortable" data-sort="authority">Authority</th>
              <th width="12%" class="sortable" data-sort="dochead">Document Head</th>
              <th width="18%" class="sortable" data-sort="document">Document</th>
              <th width="8%" class="sortable" data-sort="frequency">Frequency</th>
              <th width="6%" class="sortable sort-desc" data-sort="period">Year</th>
              <th width="8%" class="sortable" data-sort="month">Month</th>
              <th width="11%">Action</th>
            </tr>
            <tr class="column-search">
              <th></th>
              <th><input type="text" class="column-search-input" data-column="1" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="2" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="3" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="4" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="5" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="6" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="7" placeholder="Search..."></th>
              <th></th>
            </tr>
          </thead>
          
          <tbody id="favourite-tbody">
            <?php if (!empty($favourites)): ?>
              <?php $i = 1; foreach ($favourites as $row): ?>
                <?php
                  $favMonthNum = (int)($row['document_month'] ?? 0);
                  $favMonthName = ($favMonthNum >= 1 && $favMonthNum <= 12) ? date("F", mktime(0, 0, 0, $favMonthNum, 1)) : '';
                  $favMonthShort = ($favMonthNum >= 1 && $favMonthNum <= 12) ? date("M", mktime(0, 0, 0, $favMonthNum, 1)) : '';
                  $favYear = $row['document_year'] ?? '';
                  $favTypeId = $row['type_id'] ?? '';
                  $favCompanyId = $row['company_id'] ?? '';
                  $isMonthLevel = ($row['favourite_type'] ?? 'individual') === 'month_level';
                  $docCount = $row['document_count'] ?? 0;
                  $favouriteId = $row['favourite_id'] ?? '';
                  
                  // Build View and Download URLs for favourite
                  $favViewUrl = base_url('company/view_documents') . '/' . $favTypeId . '/' . $favCompanyId . '/' . $favYear . '/' . $favMonthName;
                  $favDownloadUrl = !empty($row['file_path']) ? base_url($row['file_path']) : '#';
                  
                  // For month-level, download URL should trigger the ZIP download
                  $monthDownloadUrl = base_url('dashboard/downloadMonthFavourite') . '?company_id=' . $favCompanyId . '&type_id=' . $favTypeId . '&year=' . $favYear . '&month=' . $favMonthNum;
                ?>
                <?php if ($isMonthLevel): ?>
                <!-- Month-level favourite -->
                <tr data-favourite-id="<?= $favouriteId ?>" data-favourite-type="month_level" class="month-level-favourite">
                  <td><?= $i++ ?></td>
                  <td><span class="company-badge"><i class="fa fa-building"></i> <?= htmlspecialchars($row['company_name'] ?? '') ?></span></td>
                  <td><?= htmlspecialchars($row['authority_name'] ?? '') ?></td>
                  <td><strong><?= htmlspecialchars($row['type_name'] ?? '') ?></strong></td>
                  <td><span class="badge bg-info text-white"><i class="fa fa-folder"></i> All (<?= $docCount ?> docs)</span></td>
                  <td><span class="frequency-badge"><?= htmlspecialchars($row['frequency'] ?? '') ?></span></td>
                  <td><?= htmlspecialchars($favYear) ?></td>
                  <td><?= $favMonthShort ?></td>
                  <td>
                    <div class="action-dropdown">
                      <button class="action-dropdown__btn action-dropdown__btn--info" onclick="toggleActionDropdown(this)">
                        <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="<?= $favViewUrl ?>" target="_blank" class="action-dropdown__item action-dropdown__item--view">
                          <i class="fa fa-eye text-primary"></i> View All
                        </a>
                        <a href="<?= $monthDownloadUrl ?>" class="action-dropdown__item action-dropdown__item--download">
                          <i class="fa fa-download text-success"></i> Download ZIP
                        </a>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--favourite remove-month-fav-btn" 
                           data-favourite-id="<?= $favouriteId ?>">
                          <i class="fa fa-star text-warning"></i> Remove Favourite
                        </a>
                        <div class="action-dropdown__divider"></div>
                        <div class="action-dropdown__submenu-label">Share Documents</div>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail"
                           onclick="handleMonthFavNotification('mail', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $favMonthName ?>', '<?= $favYear ?>', '<?= $favTypeId ?>', '<?= $favCompanyId ?>')">
                          <i class="fa fa-envelope"></i> Email
                        </a>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp"
                           onclick="handleMonthFavNotification('whatsapp', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $favMonthName ?>', '<?= $favYear ?>', '<?= $favTypeId ?>', '<?= $favCompanyId ?>')">
                          <i class="fab fa-whatsapp"></i> WhatsApp
                        </a>
                      </div>
                    </div>
                  </td>
                </tr>
                <?php else: ?>
                <!-- Individual favourite -->
                <tr data-upload-id="<?= $row['upload_id'] ?>" data-favourite-type="individual">
                  <td><?= $i++ ?></td>
                  <td><span class="company-badge"><i class="fa fa-building"></i> <?= htmlspecialchars($row['company_name'] ?? '') ?></span></td>
                  <td><?= htmlspecialchars($row['authority_name'] ?? '') ?></td>
                  <td><strong><?= htmlspecialchars($row['type_name'] ?? '') ?></strong></td>
                  <td><?= htmlspecialchars($row['document_name'] ?? '') ?></td>
                  <td><span class="frequency-badge"><?= htmlspecialchars($row['frequency'] ?? '') ?></span></td>
                  <td><?= htmlspecialchars($favYear) ?></td>
                  <td><?= $favMonthShort ?></td>
                  <td>
                    <div class="action-dropdown">
                      <button class="action-dropdown__btn action-dropdown__btn--info" onclick="toggleActionDropdown(this)">
                        <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">
                        <?php if (!empty($row['file_path'])): ?>
                          <a href="<?= base_url($row['file_path']) ?>" target="_blank" class="action-dropdown__item action-dropdown__item--view">
                            <i class="fa fa-eye text-primary"></i> View
                          </a>
                          <a href="<?= base_url($row['file_path']) ?>" download class="action-dropdown__item action-dropdown__item--download">
                            <i class="fa fa-download text-success"></i> Download
                          </a>
                        <?php endif; ?>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--favourite fav-btn" data-upload-id="<?= $row['upload_id'] ?>">
                          <i class="fa fa-star text-warning"></i> Remove Favourite
                        </a>
                        <div class="action-dropdown__divider"></div>
                        <div class="action-dropdown__submenu-label">Share Documents</div>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail"
                           onclick="handleUploadedNotification('mail', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $favMonthName ?>', '<?= $favYear ?>', '<?= $favTypeId ?>', '<?= $favCompanyId ?>', '<?= $row['upload_id'] ?>')">
                          <i class="fa fa-envelope"></i> Email
                        </a>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp"
                           onclick="handleUploadedNotification('whatsapp', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $favMonthName ?>', '<?= $favYear ?>', '<?= $favTypeId ?>', '<?= $favCompanyId ?>', '<?= $row['upload_id'] ?>')">
                          <i class="fab fa-whatsapp"></i> WhatsApp
                        </a>
                      </div>
                    </div>
                  </td>
                </tr>
                <?php endif; ?>
              <?php endforeach; ?>
            <?php else: ?>
              <tr>
                <td colspan="9">
                  <div class="empty-state">
                    <i class="fa fa-star"></i>
                    <p>No favourite documents yet. Click the star icon on any document to add it here.</p>
          </div>
                </td>
                  </tr>
            <?php endif; ?>
          </tbody>
        </table>
        </div>

      <!-- Pending Tab -->
      <div id="tab-pending" class="tab-pane" style="display:none;">
        <table class="data-table" id="pending-table">
          <thead>
            <tr>
              <th width="5%">#</th>
              <th width="11%" class="sortable" data-sort="company">Company</th>
              <th width="9%" class="sortable" data-sort="authority">Authority</th>
              <th width="14%" class="sortable" data-sort="dochead">Document Head</th>
              <th width="9%" class="sortable" data-sort="frequency">Frequency</th>
              <th width="9%" class="sortable" data-sort="period">Period</th>
              <th width="10%" class="sortable sort-asc" data-sort="due-date">Due Date</th>
              <th width="8%" class="sortable" data-sort="status">Status</th>
              <th width="10%">Action</th>
            </tr>
            <tr class="column-search">
              <th></th>
              <th><input type="text" class="column-search-input" data-column="1" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="2" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="3" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="4" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="5" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="6" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="7" placeholder="Search..."></th>
              <th></th>
            </tr>
          </thead>
          <tbody id="pending-tbody">
            <?php if (!empty($lazy_loading)): ?>
              <tr class="loading-row">
                <td colspan="9">
                  <div class="tab-loading">
                    <div class="spinner"></div>
                    <span style="margin-left: 10px;">Loading pending documents...</span>
                  </div>
                </td>
              </tr>
            <?php elseif (!empty($pending_documents)): ?>
              <?php $i = 1; foreach ($pending_documents as $row): ?>
                <tr>
                  <td><?= $i++ ?>dd</td>
                  <td><span class="company-badge"><i class="fa fa-building"></i> <?= htmlspecialchars($row['company_name'] ?? '') ?></span></td>
                  <td><?= htmlspecialchars($row['authority_name'] ?? '') ?></td>
                  <td>
                    <strong><?= htmlspecialchars($row['type_name'] ?? '') ?></strong>
                    <br>
                    <small>
                      <span class="doc-count doc-count--uploaded"><?= $row['uploaded_count'] ?? 0 ?> uploaded</span>
                      <span class="doc-count doc-count--pending"><?= $row['pending_count'] ?? 0 ?> pending</span>
                    </small>
                  </td>
                  <td><span class="frequency-badge"><?= htmlspecialchars($row['frequency'] ?? 'Monthly') ?></span></td>
                  <td>
                    <?php 
                      $periodMonth = isset($row['doc_period_month']) ? (int)$row['doc_period_month'] : (int)date('n');
                      $periodYear = isset($row['doc_period_year']) ? $row['doc_period_year'] : date('Y');
                      $periodMonthName = ($periodMonth >= 1 && $periodMonth <= 12) ? date("M", mktime(0, 0, 0, $periodMonth, 1)) : '';
                    ?>
                    <span class="month-badge" style="background:#fef3c7; color:#d97706;">
                      <?= $periodMonthName ?> <?= $periodYear ?>
                    </span>
                  </td>
                  <td>
                    <?php 
                      // Calculate due month based on due_in_same_next_month
                      $dueInNext = isset($row['due_in_same_next_month']) && $row['due_in_same_next_month'] == 1;
                      if ($dueInNext) {
                        $dueMonth = $periodMonth + 1;
                        $dueYear = $periodYear;
                        if ($dueMonth > 12) { $dueMonth = 1; $dueYear++; }
                      } else {
                        $dueMonth = $periodMonth;
                        $dueYear = $periodYear;
                      }
                      $dueMonthName = date("M", mktime(0, 0, 0, $dueMonth, 1));
                    ?>
                    <?php
                      // Get adjusted due day if available
                      $displayDueDay = isset($row['adjusted_due_day']) ? $row['adjusted_due_day'] : ($row['due_day'] ?? '-');
                      $hasAdjustment = isset($row['adjusted_due_reason']) && !empty($row['adjusted_due_reason']);
                      $adjustReason = isset($row['adjusted_due_reason']) ? $row['adjusted_due_reason'] : '';
                    ?>
                    <div class="due-date" <?= $hasAdjustment ? 'title="Original: ' . ($row['due_day'] ?? '-') . '. ' . htmlspecialchars($adjustReason) . '"' : '' ?>>
                      <span class="due-date__day_pending"><?= $displayDueDay ?></span>
                      <span><?= $dueMonthName ?> <?= $dueYear ?></span>
                      <?php if ($hasAdjustment): ?>
                        <i class="fa fa-info-circle text-warning" style="font-size:0.7rem; margin-left:3px;" title="<?= htmlspecialchars($adjustReason) ?>"></i>
                      <?php endif; ?>
                    </div>
                  </td>
                  <td><span class="status-badge status-badge--pending"><i class="fa fa-clock"></i> Pending</span></td>
                  <td>
                    <?php 
                      $uploadMonth = str_pad($row['doc_period_month'] ?? date('n'), 2, '0', STR_PAD_LEFT);
                      $uploadYear = $row['doc_period_year'] ?? date('Y');
                      $companyId = $row['company_id'] ?? '';
                      $authorityId = $row['authority_id'] ?? '';
                      $typeId = $row['type_id'] ?? '';
                      $pendingCount = $row['pending_count'] ?? 0;
                      $totalDocs = ($row['uploaded_count'] ?? 0) + $pendingCount;
                    ?>
                    <div class="action-dropdown">
                      <button class="action-dropdown__btn action-dropdown__btn--warning" onclick="toggleActionDropdown(this)">
                        <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">
                        <?php if (isset($can_edit) && $can_edit): ?>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--upload" 
                           onclick="handleUploadClick(<?= $companyId ?>, <?= $authorityId ?>, <?= $typeId ?>, '<?= $uploadMonth ?>', '<?= $uploadYear ?>', <?= $pendingCount ?>, <?= $totalDocs ?>)">
                          <i class="fa fa-upload"></i> Upload
                        </a>
                        <div class="action-dropdown__divider"></div>
                        <?php endif; ?>
                        <div class="action-dropdown__submenu-label">Send Notification</div>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail"
                           onclick="handleNotification('mail', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $uploadMonth ?>', '<?= $uploadYear ?>', '<?= $typeId ?>', '<?= $companyId ?>', '<?= $authorityId ?>')">
                          <i class="fa fa-envelope"></i> Mail
                        </a>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp"
                           onclick="handleNotification('whatsapp', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $uploadMonth ?>', '<?= $uploadYear ?>', '<?= $typeId ?>', '<?= $companyId ?>', '<?= $authorityId ?>')">
                          <i class="fab fa-whatsapp"></i> WhatsApp
                        </a>
                      </div>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr>
                <td colspan="9">
                  <div class="empty-state">
                    <i class="fa fa-check-circle"></i>
                    <p>All documents for this month are uploaded!</p>
        </div>
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      
      <!-- Overdue Tab -->
      <div id="tab-overdue" class="tab-pane" style="display:none;">
        <table class="data-table" id="overdue-table">
          <thead>
            <tr>
              <th width="5%">#</th>
              <th width="10%" class="sortable" data-sort="company">Company</th>
              <th width="9%" class="sortable" data-sort="authority">Authority</th>
              <th width="13%" class="sortable" data-sort="dochead">Document Head</th>
              <th width="9%" class="sortable" data-sort="frequency">Frequency</th>
              <th width="10%" class="sortable" data-sort="period">Period</th>
              <th width="11%" class="sortable sort-asc" data-sort="due-date">Due Date</th>
              <th width="9%" class="sortable" data-sort="status">Status</th>
              <th width="10%">Action</th>
            </tr>
            <tr class="column-search">
              <th></th>
              <th><input type="text" class="column-search-input" data-column="1" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="2" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="3" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="4" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="5" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="6" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="7" placeholder="Search..."></th>
              <th></th>
            </tr>
          </thead>
          <tbody id="overdue-tbody">
            <?php if (!empty($lazy_loading)): ?>
              <tr class="loading-row">
                <td colspan="9">
                  <div class="tab-loading">
                    <div class="spinner"></div>
                    <span style="margin-left: 10px;">Loading overdue documents...</span>
                  </div>
                </td>
              </tr>
            <?php elseif (!empty($overdue_documents)): ?>

              <?php $i = 1; foreach ($overdue_documents as $row): ?>
                <tr>
                  <td><?= $i++ ?></td>
                  <td><span class="company-badge"><i class="fa fa-building"></i> <?= htmlspecialchars($row['company_name'] ?? '') ?></span></td>
                  <td><?= htmlspecialchars($row['authority_name'] ?? '') ?></td>
                  <td>
                    <strong><?= htmlspecialchars($row['type_name'] ?? '') ?></strong>
                    <br>
                    <small>
                      <span class="doc-count doc-count--uploaded"><?= $row['uploaded_count'] ?? 0 ?> uploaded</span>
                      <span class="doc-count doc-count--pending"><?= $row['pending_count'] ?? 0 ?> pending</span>
                    </small>
                  </td>
                  <td><span class="frequency-badge"><?= htmlspecialchars($row['frequency'] ?? 'Monthly') ?></span></td>
                  <td>
                            <?php 
                      $overdueMonth = isset($row['overdue_month']) ? (int)$row['overdue_month'] : (int)date('n');
                      $overdueYear = isset($row['overdue_year']) ? $row['overdue_year'] : date('Y');
                      $monthName = ($overdueMonth >= 1 && $overdueMonth <= 12) ? date("M", mktime(0, 0, 0, $overdueMonth, 1)) : '';
                    ?>
                    <span class="month-badge" style="background:#fee2e2; color:#dc2626;">
                      <?= $monthName ?> <?= $overdueYear ?>
                    </span>
                  </td>
                  <td>
                    <?php 
                      // Calculate due month based on due_in_same_next_month
                      $dueInNext = isset($row['due_in_same_next_month']) && $row['due_in_same_next_month'] == 1;
                      if ($dueInNext) {
                        $dueMonth = $overdueMonth + 1;
                        $dueYear = $overdueYear;
                        if ($dueMonth > 12) { $dueMonth = 1; $dueYear++; }
                      } else {
                        $dueMonth = $overdueMonth;
                        $dueYear = $overdueYear;
                      }
                      $dueMonthName = date("M", mktime(0, 0, 0, $dueMonth, 1));
                    ?>
                    <?php
                      // Get adjusted due day if available for overdue
                      $displayDueDay = isset($row['adjusted_due_day']) ? $row['adjusted_due_day'] : ($row['due_day'] ?? '-');
                      $hasAdjustment = isset($row['adjusted_due_reason']) && !empty($row['adjusted_due_reason']);
                      $adjustReason = isset($row['adjusted_due_reason']) ? $row['adjusted_due_reason'] : '';
                    ?>
                    <div class="due-date" <?= $hasAdjustment ? 'title="Original: ' . ($row['due_day'] ?? '-') . '. ' . htmlspecialchars($adjustReason) . '"' : '' ?>>
                      <span class="due-date__day"><?= $displayDueDay ?></span>
                      <span><?= $dueMonthName ?> <?= $dueYear ?></span>
                      <?php if ($hasAdjustment): ?>
                        <i class="fa fa-info-circle text-warning" style="font-size:0.7rem; margin-left:3px;" title="<?= htmlspecialchars($adjustReason) ?>"></i>
                      <?php endif; ?>
                    </div>
                  </td>
                  <td><span class="status-badge status-badge--overdue"><i class="fa fa-exclamation-circle"></i> Overdue</span></td>
                          <td>
                          <?php 
                      $uploadMonth = str_pad($row['overdue_month'] ?? date('n'), 2, '0', STR_PAD_LEFT);
                      $uploadYear = $row['overdue_year'] ?? date('Y');
                      $companyId = $row['company_id'] ?? '';
                      $authorityId = $row['authority_id'] ?? '';
                      $typeId = $row['type_id'] ?? '';
                      $pendingCount = $row['pending_count'] ?? 0;
                      $totalDocs = ($row['uploaded_count'] ?? 0) + $pendingCount;
                    ?>
                    <div class="action-dropdown">
                      <button class="action-dropdown__btn action-dropdown__btn--danger" onclick="toggleActionDropdown(this)">
                        <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">
                        <?php if (isset($can_edit) && $can_edit): ?>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--upload" 
                           onclick="handleUploadClick(<?= $companyId ?>, <?= $authorityId ?>, <?= $typeId ?>, '<?= $uploadMonth ?>', '<?= $uploadYear ?>', <?= $pendingCount ?>, <?= $totalDocs ?>)">
                          <i class="fa fa-upload"></i> Upload
                        </a>
                        <div class="action-dropdown__divider"></div>
                        <?php endif; ?>
                        <div class="action-dropdown__submenu-label">Send Notification</div>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail"
                           onclick="handleNotification('mail', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $uploadMonth ?>', '<?= $uploadYear ?>', '<?= $typeId ?>', '<?= $companyId ?>', '<?= $authorityId ?>')">
                          <i class="fa fa-envelope"></i> Mail
                        </a>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp"
                           onclick="handleNotification('whatsapp', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $uploadMonth ?>', '<?= $uploadYear ?>', '<?= $typeId ?>', '<?= $companyId ?>', '<?= $authorityId ?>')">
                          <i class="fab fa-whatsapp"></i> WhatsApp
                        </a>
                      </div>
                    </div>
                          </td>
                      </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr>
                <td colspan="9">
                  <div class="empty-state">
                    <i class="fa fa-smile"></i>
                    <p>Great! No overdue documents.</p>
  </div>
                </td>
                  </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      
      <!-- Upcoming Tab -->
      <div id="tab-upcoming" class="tab-pane" style="display:none;">
        <table class="data-table" id="upcoming-table">
          <thead>
            <tr>
              <th width="5%">#</th>
              <th width="10%" class="sortable" data-sort="company">Company</th>
              <th width="9%" class="sortable" data-sort="authority">Authority</th>
              <th width="13%" class="sortable" data-sort="dochead">Document Head</th>
              <th width="9%" class="sortable" data-sort="frequency">Frequency</th>
              <th width="10%" class="sortable" data-sort="period">Period</th>
              <th width="11%" class="sortable sort-asc" data-sort="due-date">Due Date</th>
              <th width="9%" class="sortable" data-sort="status">Status</th>
              <th width="10%">Action</th>
            </tr>
            <tr class="column-search">
              <th></th>
              <th><input type="text" class="column-search-input" data-column="1" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="2" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="3" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="4" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="5" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="6" placeholder="Search..."></th>
              <th><input type="text" class="column-search-input" data-column="7" placeholder="Search..."></th>
              <th></th>
            </tr>
          </thead>
          <tbody id="upcoming-tbody">
            <?php if (!empty($lazy_loading)): ?>
              <tr class="loading-row">
                <td colspan="9">
                  <div class="tab-loading">
                    <div class="spinner"></div>
                    <span style="margin-left: 10px;">Loading upcoming documents...</span>
                  </div>
                </td>
              </tr>
            <?php elseif (!empty($upcoming_documents)): ?>
              <?php $i = 1; foreach ($upcoming_documents as $row): ?>
                <tr>
                  <td><?= $i++ ?></td>
                  <td><span class="company-badge"><i class="fa fa-building"></i> <?= htmlspecialchars($row['company_name'] ?? '') ?></span></td>
                  <td><?= htmlspecialchars($row['authority_name'] ?? '') ?></td>
                  <td>
                    <strong><?= htmlspecialchars($row['type_name'] ?? '') ?></strong>
                    <br>
                    <small>
                      <span class="doc-count doc-count--uploaded"><?= $row['uploaded_count'] ?? 0 ?> uploaded</span>
                      <span class="doc-count doc-count--pending"><?= $row['pending_count'] ?? 0 ?> pending</span>
                    </small>
                  </td>
                  <td><span class="frequency-badge"><?= htmlspecialchars($row['frequency'] ?? 'Monthly') ?></span></td>
                  <td>
                    <?php 
                      $upcomingPeriodMonth = isset($row['doc_period_month']) ? (int)$row['doc_period_month'] : (int)date('n', strtotime('+1 month'));
                      $upcomingPeriodYear = isset($row['doc_period_year']) ? $row['doc_period_year'] : date('Y', strtotime('+1 month'));
                      $upcomingMonthName = ($upcomingPeriodMonth >= 1 && $upcomingPeriodMonth <= 12) ? date("M", mktime(0, 0, 0, $upcomingPeriodMonth, 1)) : '';
                    ?>
                    <span class="month-badge" style="background:#dbeafe; color:#2563eb;">
                      <?= $upcomingMonthName ?> <?= $upcomingPeriodYear ?>
                    </span>
                  </td>
                  <td>
                    <?php 
                      // Calculate due month based on due_in_same_next_month
                      $dueInNext = isset($row['due_in_same_next_month']) && $row['due_in_same_next_month'] == 1;
                      if ($dueInNext) {
                        $dueMonth = $upcomingPeriodMonth + 1;
                        $dueYear = $upcomingPeriodYear;
                        if ($dueMonth > 12) { $dueMonth = 1; $dueYear++; }
                      } else {
                        $dueMonth = $upcomingPeriodMonth;
                        $dueYear = $upcomingPeriodYear;
                      }
                      $dueMonthName = date("M", mktime(0, 0, 0, $dueMonth, 1));
                    ?>
                    <?php
                      // Get adjusted due day if available for upcoming
                      $displayDueDay = isset($row['adjusted_due_day']) ? $row['adjusted_due_day'] : ($row['due_day'] ?? '-');
                      $hasAdjustment = isset($row['adjusted_due_reason']) && !empty($row['adjusted_due_reason']);
                      $adjustReason = isset($row['adjusted_due_reason']) ? $row['adjusted_due_reason'] : '';
                    ?>
                    <div class="due-date due-date--upcoming" <?= $hasAdjustment ? 'title="Original: ' . ($row['due_day'] ?? '-') . '. ' . htmlspecialchars($adjustReason) . '"' : '' ?>>
                      <span class="due-date__day_upcoming"><?= $displayDueDay ?></span>
                      <span><?= $dueMonthName ?> <?= $dueYear ?></span>
                      <?php if ($hasAdjustment): ?>
                        <i class="fa fa-info-circle text-warning" style="font-size:0.7rem; margin-left:3px;" title="<?= htmlspecialchars($adjustReason) ?>"></i>
                      <?php endif; ?>
                    </div>
                  </td>
                  <td><span class="status-badge status-badge--upcoming"><i class="fa fa-calendar"></i> Upcoming</span></td>
                  <td>
                    <?php 
                      $uploadMonth = str_pad($row['doc_period_month'] ?? $upcomingPeriodMonth, 2, '0', STR_PAD_LEFT);
                      $uploadYear = $row['doc_period_year'] ?? $upcomingPeriodYear;
                      $companyId = $row['company_id'] ?? '';
                      $authorityId = $row['authority_id'] ?? '';
                      $typeId = $row['type_id'] ?? '';
                      $pendingCount = $row['pending_count'] ?? 0;
                      $totalDocs = ($row['uploaded_count'] ?? 0) + $pendingCount;
                    ?>
                    <div class="action-dropdown">
                      <button class="action-dropdown__btn action-dropdown__btn--pending" onclick="toggleActionDropdown(this)">
                        <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">
                        <!-- Upload button removed from Upcoming tab as per requirement -->
                        <div class="action-dropdown__submenu-label">Send Notification</div>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail"
                           onclick="handleNotification('mail', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $uploadMonth ?>', '<?= $uploadYear ?>', '<?= $typeId ?>', '<?= $companyId ?>', '<?= $authorityId ?>')">
                          <i class="fa fa-envelope"></i> Mail
                        </a>
                        <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp"
                           onclick="handleNotification('whatsapp', '<?= htmlspecialchars($row['type_name'] ?? '') ?>', '<?= htmlspecialchars($row['company_name'] ?? '') ?>', '<?= $uploadMonth ?>', '<?= $uploadYear ?>', '<?= $typeId ?>', '<?= $companyId ?>', '<?= $authorityId ?>')">
                          <i class="fab fa-whatsapp"></i> WhatsApp
                        </a>
      </div>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr>
                <td colspan="9">
                  <div class="empty-state">
                    <i class="fa fa-calendar-check"></i>
                    <p>No upcoming documents for next month.</p>
                  </div>
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  </div>

<script>
// Permission flags from server
const canView = <?= isset($can_view) && $can_view ? 'true' : 'false' ?>;
const canEdit = <?= isset($can_edit) && $can_edit ? 'true' : 'false' ?>;
const canDelete = <?= isset($can_delete) && $can_delete ? 'true' : 'false' ?>;

function calculateDayDifference(dueDateStr) {
  const today = new Date();
  today.setHours(0,0,0,0);

  const dueDate = new Date(dueDateStr);
  dueDate.setHours(0,0,0,0);

  const diffMs = dueDate - today;
  return Math.ceil(diffMs / (1000 * 60 * 60 * 24));
}

// Track current active tab for export (global scope)
var currentActiveTab = 'favourite';

$(document).ready(function() {
  const baseUrl = '<?= base_url() ?>';
  
  // Tab configurations
  const tabConfig = {
    favourite: {
      icon: 'fa-star',
      title: 'Favourite Documents',
      color: '#f59e0b'
    },
    pending: {
      icon: 'fa-clock',
      title: 'Current Documents (<?= date("M Y") ?>)',
      color: '#6366f1'
    },
    overdue: {
      icon: 'fa-exclamation-triangle',
      title: 'Overdue Documents',
      color: '#ef4444'
    },
    upcoming: {
      icon: 'fa-calendar-alt',
      title: 'Upcoming Documents (<?= date("M Y", strtotime("+1 month")) ?>)',
      color: '#10b981'
    },
    uploaded: {
      icon: 'fa-check-circle',
      title: 'Completed Documents',
      color: '#3b82f6'
    }
  };
  
  // Track which tabs have been loaded (for lazy loading)
  const loadedTabs = { favourite: true }; // Favourite is loaded by default
  
  // Handle stat card clicks
  $('.stat-card').on('click', function() {
    const tab = $(this).data('tab');
    currentActiveTab = tab;
    
    // Update active state
    $('.stat-card').removeClass('active');
    $(this).addClass('active');
    
    // Update header with tab-specific color
    const config = tabConfig[tab];
    $('#tab-header')
      .removeClass('tab-header--favourite tab-header--pending tab-header--overdue tab-header--upcoming tab-header--uploaded')
      .addClass('tab-header--' + tab);
    
    $('#tab-title').html(`
      <i class="fa ${config.icon}"></i>
      <span>${config.title}</span>
      <span class="tab-header__badge" id="tab-count">${$('#count-' + tab).text()} items</span>
    `);
    
    // Show/hide tab panes
    $('.tab-pane').hide();
    $('#tab-' + tab).show();
    
    // Reset column search when switching tabs
    resetColumnSearch();
    
    // Lazy load tab data if not already loaded
    if (!loadedTabs[tab]) {
      loadTabData(tab);
    } else {
      // Apply default sorting for each tab
      applyDefaultSorting(tab);
    }
  });
  
  // Lazy load tab data via AJAX
  function loadTabData(tab) {
    const selectedYear = '<?= $selected_year ?? date("Y") ?>';
    const selectedCompanies = '<?= is_array($selected_companies ?? null) ? implode(",", $selected_companies) : "" ?>';
    
    $.ajax({
      url: baseUrl + 'dashboard/getTabData',
      type: 'POST',
      data: { 
        tab: tab,
        year: selectedYear,
        companies: selectedCompanies
      },
      dataType: 'json',
      success: function(response) {
        if (response.success) {
          loadedTabs[tab] = true;
          renderTabData(tab, response.data);
          applyDefaultSorting(tab);
        } else {
          showEmptyState(tab, response.message || 'Failed to load data');
        }
      },
      error: function() {
        showEmptyState(tab, 'Error loading data. Please try again.');
      }
    });
  }
  
  // Render tab data based on tab type
  function renderTabData(tab, data) {
    const tbodyId = '#' + tab + '-tbody';
    let $tbody = $(tbodyId);
    
    // For uploaded tab, tbody doesn't have an id, find it differently
    if (tab === 'uploaded') {
      $tbody = $('#uploaded-table tbody');
    }
    
    if (!$tbody.length) return;
    
    $tbody.empty();
    
    if (!data || data.length === 0) {
      showEmptyState(tab);
      return;
    }
    
    // Render based on tab type
    if (tab === 'uploaded') {
      renderUploadedTab($tbody, data);
    } else if (tab === 'pending') {
      renderPendingTab($tbody, data);
    } else if (tab === 'overdue') {
      renderOverdueTab($tbody, data);
    } else if (tab === 'upcoming') {
      renderUpcomingTab($tbody, data);
    }
  }
  
  function showEmptyState(tab, message) {
    const tbodyId = tab === 'uploaded' ? '#uploaded-table tbody' : '#' + tab + '-tbody';
    const $tbody = $(tbodyId);
    const emptyMessages = {
      uploaded: 'No uploaded documents found',
      pending: 'All documents for this month are uploaded!',
      overdue: 'No overdue documents. Great job!',
      upcoming: 'No upcoming documents for next month'
    };
    const icons = {
      uploaded: 'fa-folder-open',
      pending: 'fa-check-circle',
      overdue: 'fa-thumbs-up',
      upcoming: 'fa-calendar-check'
    };
    
    $tbody.html(`
      <tr>
        <td colspan="9">
          <div class="empty-state">
            <i class="fa ${icons[tab] || 'fa-folder-open'}"></i>
            <p>${message || emptyMessages[tab] || 'No data found'}</p>
          </div>
        </td>
      </tr>
    `);
  }
  
  // Render functions for each tab type
  function renderUploadedTab($tbody, data) {
    let html = '';
    data.forEach((row, index) => {
      const monthNum = parseInt(row.document_month) || 0;
      const periodMonth = parseInt(row.document_month) || 0;
      const periodYear  = parseInt(row.document_year) || 0;
      const monthName = monthNum >= 1 && monthNum <= 12 ? new Date(2000, monthNum - 1, 1).toLocaleString('en', {month: 'short'}) : '';
      const monthNameFull = monthNum >= 1 && monthNum <= 12 ? new Date(2000, monthNum - 1, 1).toLocaleString('en', {month: 'long'}) : '';
      const viewUrl = baseUrl + 'company/view_documents/' + (row.type_id || '') + '/' + (row.company_id || '') + '/' + (row.document_year || '') + '/' + monthNameFull;
      const downloadUrl = baseUrl + 'company/download_month/' + (row.type_id || '') + '/' + (row.company_id || '') + '/' + (row.document_year || '') + '/' + monthNameFull;
      const uploadedDate = row.uploaded_date ? new Date(row.uploaded_date).toLocaleDateString('en-GB', {day: '2-digit', month: 'short', year: 'numeric'}) : '';
      
      html += `<tr>
        <td>${index + 1}</td>
        <td><span class=""><i class="fa fa-building"></i> ${escapeHtml(row.company_name || '')}</span></td>
        <td>${escapeHtml(row.authority_name || '')}</td>
        <td><strong>${escapeHtml(row.type_name || '')}</strong><br><small><span class="doc-count doc-count--uploaded">${row.uploaded_count || 0} uploaded</span></small></td>
        <td><span class="frequency-badge">${escapeHtml(row.frequency || '')}</span></td>
        <td data-sort-date="${periodYear}-${String(periodMonth).padStart(2,'0')}-01"><span class="month-badge" style="background:#d1fae5; color:#059669;">${monthName} ${row.document_year || ''}</span></td>
        <td>${uploadedDate}</td>
         <td>
            <div class="action-dropdown">
              <button class="action-dropdown__btn action-dropdown__btn--upcoming"
                onclick="toggleActionDropdown(this)">
                <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="${viewUrl}" target="_blank" class="action-dropdown__item action-dropdown__item action-dropdown__item--view">
                  <i class="fa fa-eye text-primary"></i> View
                </a>

                <a href="${downloadUrl}" class="action-dropdown__item action-dropdown__item action-dropdown__item--download">
                  <i class="fa fa-download text-success"></i> Download
                </a>

                <div class="action-dropdown__divider"></div>
                <div class="action-dropdown__submenu-label">Share Documents</div>

                <a href="javascript:void(0)"
                  class="action-dropdown__item action-dropdown__item--mail"
                  onclick="handleUploadedNotification(
                    'mail',
                    '${escapeHtml(row.type_name || '')}',
                    '${escapeHtml(row.company_name || '')}',
                    '${monthNameFull}',
                    '${row.document_year}',
                    '${row.type_id}',
                    '${row.company_id}'
                  )">
                  <i class="fa fa-envelope"></i> Email
                </a>

                <a href="javascript:void(0)"
                  class="action-dropdown__item action-dropdown__item--whatsapp"
                  onclick="handleUploadedNotification(
                    'whatsapp',
                    '${escapeHtml(row.type_name || '')}',
                    '${escapeHtml(row.company_name || '')}',
                    '${monthNameFull}',
                    '${row.document_year}',
                    '${row.type_id}',
                    '${row.company_id}'
                  )">
                  <i class="fab fa-whatsapp"></i> WhatsApp
                </a>
              </div>
            </div>
          </td>
        </tr>`;
    });
    $tbody.html(html);
  }
  
  function renderPendingTab($tbody, data) {
    let html = '';
    data.forEach((row, index) => {
      const periodMonth = parseInt(row.doc_period_month) || parseInt(new Date().getMonth() + 1);
      const periodYear = parseInt(row.doc_period_year) || new Date().getFullYear();
      const periodMonthName = new Date(2000, periodMonth - 1, 1).toLocaleString('en', {month: 'short'});
      const dueInNext = row.due_in_same_next_month == '1' || row.due_in_same_next_month == 1;
      let dueMonth = periodMonth, dueYear = periodYear;
      if (dueInNext) { dueMonth++; if (dueMonth > 12) { dueMonth = 1; dueYear++; } }
      const dueMonthName = new Date(2000, dueMonth - 1, 1).toLocaleString('en', {month: 'short'});
      const displayDueDay = row.adjusted_due_day || row.due_day || '-';
      const uploadMonth = String(periodMonth).padStart(2, '0');
      
      const dueDateStr = `${dueYear}-${String(dueMonth).padStart(2,'0')}-${String(displayDueDay).padStart(2,'0')}`;
      const diffDays = calculateDayDifference(dueDateStr);

      let daysHtml = '';
      if (diffDays >= 0) {
        daysHtml = `<span class="days-badge days-badge--remaining">Due in ${diffDays} days</span>`;
      }

      const adjustReason = row.adjusted_due_reason || '';
      const isPublicHolidayAdjustment = adjustReason && !/sunday/i.test(adjustReason);
      const adjustedBadgeHtml = isPublicHolidayAdjustment
      ? `<span class="due-adjusted-badge" title="${escapeHtml(adjustReason)}">
          <i class="fa fa-info-circle"></i>
        </span>`
      : '';
      
      html += `<tr>
        <td>${index + 1}</td>
        <td><span class="company-badge"><i class="fa fa-building"></i> ${escapeHtml(row.company_name || '')}</span></td>
        <td>${escapeHtml(row.authority_name || '')}</td>
        <td><strong>${escapeHtml(row.type_name || '')}</strong><br><small><span class="doc-count doc-count--uploaded">${row.uploaded_count || 0} uploaded</span> <span class="doc-count doc-count--pending">${row.pending_count || 0} pending</span></small></td>
        <td><span class="frequency-badge">${escapeHtml(row.frequency || 'Monthly')}</span></td>
        <td data-sort-date="${periodYear}-${String(periodMonth).padStart(2,'0')}-01"><span class="month-badge" style="background:#fef3c7; color:#d97706;">${periodMonthName} ${periodYear}</span></td>
        <td data-sort-date="${dueYear}-${String(dueMonth).padStart(2,'0')}-${String(displayDueDay).padStart(2,'0')}">
          <div class="due-date">
            <span class="due-date__day_pending">${displayDueDay}</span><span>${dueMonthName} ${dueYear}
            </span>
            ${adjustedBadgeHtml}
          </div></td>
        <td>
          <div class="status-wrapper">
            <span class="status-badge status-badge--pending"><i class="fa fa-clock"></i> <span class="status-text">Pending</span></span>
            ${diffDays >= 0 ? `<div class="status-days">${diffDays} Days</div>` : ''}
          </div>
        </td>
        <td>
          <div class="action-dropdown">
            <button class="action-dropdown__btn action-dropdown__btn--warning" onclick="toggleActionDropdown(this)"><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">
              ${canEdit ? `<a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--upload" onclick="handleUploadClick(${row.company_id}, ${row.authority_id || 0}, ${row.type_id}, '${uploadMonth}', ${periodYear}, ${row.pending_count || 0}, ${(row.uploaded_count || 0) + (row.pending_count || 0)})"><i class="fa fa-upload"></i> Upload</a>
              <div class="action-dropdown__divider"></div>` : ''}
              <div class="action-dropdown__submenu-label">Send Notification</div>
              <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail" 
              onclick="handleNotification('mail', '${escapeHtml(row.type_name || '')}', '${escapeHtml(row.company_name || '')}', '${uploadMonth}', '${periodYear}', '${row.type_id}', '${row.company_id}', '${row.authority_id || ''}','${displayDueDay}','${dueMonth}','${dueYear}','${escapeHtml(adjustReason)}')"><i class="fa fa-envelope"></i> Mail</a>
              <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp" onclick="handleNotification('whatsapp', '${escapeHtml(row.type_name || '')}', '${escapeHtml(row.company_name || '')}', '${uploadMonth}', '${periodYear}', '${row.type_id}', '${row.company_id}', '${row.authority_id || ''}')"><i class="fab fa-whatsapp"></i> WhatsApp</a>
            </div>
          </div>
        </td>
      </tr>`;
    });
    $tbody.html(html);
  }
  
  function renderOverdueTab($tbody, data) {
    let html = '';
    data.forEach((row, index) => {
      // Period = overdue_month/year from SQL (the month the document is FOR)
      const periodMonth = parseInt(row.overdue_month) || parseInt(new Date().getMonth() + 1);
      const periodYear = parseInt(row.overdue_year) || new Date().getFullYear();
      const periodMonthName = new Date(2000, periodMonth - 1, 1).toLocaleString('en', {month: 'short'});
      
      // Check due_in_same_next_month (SQL returns this field name)
      const dueInNext = row.due_in_same_next_month == '1' || row.due_in_same_next_month == 1;
      
      // Calculate Due date: if due_in_next, add 1 month to period; otherwise due = period
      let dueMonth = periodMonth, dueYear = periodYear;
      if (dueInNext) { 
        dueMonth++; 
        if (dueMonth > 12) { dueMonth = 1; dueYear++; } 
      }
      const dueMonthName = new Date(2000, dueMonth - 1, 1).toLocaleString('en', {month: 'short'});
      const displayDueDay = row.adjusted_due_day || row.due_day || '-';
      const uploadMonth = String(periodMonth).padStart(2, '0');

      // Period display = what month the document is FOR
      const displayPeriodMonth = periodMonth;
      const displayPeriodYear = periodYear;
      const displayPeriodMonthName = periodMonthName;

      const dueDateStr = `${dueYear}-${String(dueMonth).padStart(2,'0')}-${String(displayDueDay).padStart(2,'0')}`;
      const diffDays = calculateDayDifference(dueDateStr);

      const overdueDays = Math.abs(diffDays);

      const daysHtml = `
        <span class="days-badge days-badge--overdue">
          ${overdueDays} days overdue
        </span>
      `;

      const adjustReason = row.adjusted_due_reason || '';
      const isPublicHolidayAdjustment = adjustReason && !/sunday/i.test(adjustReason);
      const adjustedBadgeHtml = isPublicHolidayAdjustment
      ? `<span class="due-adjusted-badge" title="${escapeHtml(adjustReason)}">
          <i class="fa fa-info-circle"></i>
        </span>`
      : '';

      html += `<tr>
        <td>${index + 1}</td>
        <td><span class="company-badge"><i class="fa fa-building"></i> ${escapeHtml(row.company_name || '')}</span></td>
        <td>${escapeHtml(row.authority_name || '')}</td>
        <td><strong>${escapeHtml(row.type_name || '')}</strong><br><small><span class="doc-count doc-count--uploaded">${row.uploaded_count || 0} uploaded</span> <span class="doc-count doc-count--pending">${row.pending_count || 0} pending</span></small></td>
        <td><span class="frequency-badge">${escapeHtml(row.frequency || 'Monthly')}</span></td>
        <td data-sort-date="${periodYear}-${String(periodMonth).padStart(2,'0')}-01"><span class="month-badge" style="background:#fee2e2; color:#dc2626;">${displayPeriodMonthName} ${displayPeriodYear}</span></td>
        <td data-sort-date="${dueYear}-${String(dueMonth).padStart(2,'0')}-${String(displayDueDay).padStart(2,'0')}">
          <div class="due-date">
            <span class="due-date__day">${displayDueDay}</span><span>${dueMonthName} ${dueYear}</span>
            ${adjustedBadgeHtml}
          </div>
        </td>
        <td>
          <div class="status-wrapper">
            <span class="status-badge status-badge--overdue"><i class="fa fa-exclamation-triangle"></i> <span class="status-text">Overdue</span></span>
            <div class="status-days">${overdueDays} Days</div>
          </div>
        </td>
        <td>
          <div class="action-dropdown">
            <button class="action-dropdown__btn action-dropdown__btn--danger" onclick="toggleActionDropdown(this)"><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">
              ${canEdit ? `<a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--upload" onclick="handleUploadClick(${row.company_id}, ${row.authority_id || 0}, ${row.type_id}, '${uploadMonth}', ${periodYear}, ${row.pending_count || 0}, ${(row.uploaded_count || 0) + (row.pending_count || 0)})"><i class="fa fa-upload"></i> Upload</a>
              <div class="action-dropdown__divider"></div>` : ''}
              <div class="action-dropdown__submenu-label">Send Notification</div>
              <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail" onclick="handleNotification('mail', '${escapeHtml(row.type_name || '')}', '${escapeHtml(row.company_name || '')}', '${uploadMonth}', '${periodYear}', '${row.type_id}', '${row.company_id}', '${row.authority_id || ''}','${displayDueDay}','${String(dueMonth).padStart(2, '0')}','${dueYear}','${escapeHtml(adjustReason)}')"><i class="fa fa-envelope"></i> Mail</a>
              <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp" onclick="handleNotification('whatsapp', '${escapeHtml(row.type_name || '')}', '${escapeHtml(row.company_name || '')}', '${uploadMonth}', '${periodYear}', '${row.type_id}', '${row.company_id}', '${row.authority_id || ''}')"><i class="fab fa-whatsapp"></i> WhatsApp</a>
            </div>
          </div>
        </td>
      </tr>`;
    });
    $tbody.html(html);
  }
  
  function renderUpcomingTab($tbody, data) {
    let html = '';
    data.forEach((row, index) => {
      const periodMonth = parseInt(row.doc_period_month) || parseInt(new Date().getMonth() + 2);
      const periodYear = parseInt(row.doc_period_year) || new Date().getFullYear();
      const periodMonthName = new Date(2000, periodMonth - 1, 1).toLocaleString('en', {month: 'short'});
      const dueInNext = row.due_in_same_next_month == '1' || row.due_in_same_next_month == 1;
      let dueMonth = periodMonth, dueYear = periodYear;
      if (dueInNext) { dueMonth++; if (dueMonth > 12) { dueMonth = 1; dueYear++; } }
      const dueMonthName = new Date(2000, dueMonth - 1, 1).toLocaleString('en', {month: 'short'});
      const displayDueDay = row.adjusted_due_day || row.due_day || '-';
      const uploadMonth = String(periodMonth).padStart(2, '0');
      
      const dueDateStr = `${dueYear}-${String(dueMonth).padStart(2,'0')}-${String(displayDueDay).padStart(2,'0')}`;
      const diffDays = calculateDayDifference(dueDateStr);

      const adjustReason = row.adjusted_due_reason || '';
      //const isPublicHolidayAdjustment = adjustReason && !/sunday/i.test(adjustReason);
      const adjustedIconHtml = adjustReason
      ? `<i class="fa fa-info-circle due-adjusted-icon"
          title="${escapeHtml(adjustReason)}"></i>`
      : '';
      
      html += `<tr>
        <td>${index + 1}</td>
        <td><span class="company-badge"><i class="fa fa-building"></i> ${escapeHtml(row.company_name || '')}</span></td>
        <td>${escapeHtml(row.authority_name || '')}</td>
        <td><strong>${escapeHtml(row.type_name || '')}</strong><br><small><span class="doc-count doc-count--uploaded">${row.uploaded_count || 0} uploaded</span> <span class="doc-count doc-count--pending">${row.pending_count || 0} pending</span></small></td>
        <td><span class="frequency-badge">${escapeHtml(row.frequency || 'Monthly')}</span></td>
        <td><span class="month-badge" style="background:#e0e7ff; color:#5b21b6;">${periodMonthName} ${periodYear}</span></td>
        <td data-sort-date="${dueYear}-${String(dueMonth).padStart(2,'0')}-${String(displayDueDay).padStart(2,'0')}">
          <div class="due-date">
            <span class="due-date__day_upcoming">${displayDueDay}</span>
            <span>${dueMonthName} ${dueYear}</span>
            ${adjustedIconHtml}
          </div>
        </td>
        <td>
          <div class="status-wrapper">
            <span class="status-badge status-badge--upcoming"><i class="fa fa-calendar-alt"></i> <span class="status-text">Upcoming</span></span>
            ${diffDays >= 0 ? `<div class="status-days status-days--upcoming">${diffDays} Days</div>` : ''}
          </div>
        </td>
        <td>
          <div class="action-dropdown">
            <button class="action-dropdown__btn action-dropdown__btn--pending" onclick="toggleActionDropdown(this)"><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">
              <div class="action-dropdown__submenu-label">Send Notification</div>
              <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--mail" onclick="handleNotification('mail', '${escapeHtml(row.type_name || '')}', '${escapeHtml(row.company_name || '')}', '${uploadMonth}', '${periodYear}', '${row.type_id}', '${row.company_id}', '${row.authority_id || ''}','${displayDueDay}','${dueMonth}','${dueYear}','${escapeHtml(adjustReason)}')"><i class="fa fa-envelope"></i> Mail</a>
              <a href="javascript:void(0)" class="action-dropdown__item action-dropdown__item--whatsapp" onclick="handleNotification('whatsapp', '${escapeHtml(row.type_name || '')}', '${escapeHtml(row.company_name || '')}', '${uploadMonth}', '${periodYear}', '${row.type_id}', '${row.company_id}', '${row.authority_id || ''}')"><i class="fab fa-whatsapp"></i> WhatsApp</a>
            </div>
          </div>
        </td>
      </tr>`;
    });
    $tbody.html(html);
  }
  
  // Helper function to escape HTML
  function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
  
  // Apply default sorting based on tab
  function applyDefaultSorting(tab) {
    const tableId = '#' + tab + '-table';
    const $table = $(tableId);
    if (!$table.length) return;
    
    // Clear existing sort indicators
    $table.find('th.sortable').removeClass('sort-asc sort-desc');
    
    // Default sorting configuration per tab
    const sortConfig = {
      favourite: { column: 'period', order: 'desc' },      // Month/Year new to old
      pending: { column: 'due-date', order: 'asc' },       // Due date old to new
      overdue: { column: 'due-date', order: 'asc' },       // Due date old to new
      upcoming: { column: 'due-date', order: 'asc' },      // Due date old to new
      uploaded: { column: 'period', order: 'desc' }        // Period/uploaded date new to old
    };
    
    const config = sortConfig[tab];
    if (config) {
      const $th = $table.find('th[data-sort="' + config.column + '"]');
      if ($th.length) {
        $th.addClass(config.order === 'asc' ? 'sort-asc' : 'sort-desc');
        sortTable(tableId, $th.index(), config.order);
      }
    }
  }
  
  $(document).on('click', '.fav-btn', function (e) {
  e.preventDefault();

  const btn = $(this);
  const uploadId = btn.data('upload-id');
  if (!uploadId) return;

  // Find row (normal or floating dropdown)
  const $row =
    btn.closest('tr').length
      ? btn.closest('tr')
      : $('#floating-action-menu').data('source-row');

  // Show confirmation dialog
  Swal.fire({
    title: 'Remove from Favourites?',
    text: 'Are you sure you want to remove this document from favourites?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#f59e0b',
    cancelButtonColor: '#6b7280',
    confirmButtonText: '<i class="fa fa-star"></i> Yes, Remove',
    cancelButtonText: 'Cancel'
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: baseUrl + 'dashboard/toggleFavourite',
        type: 'POST',
        data: { upload_id: uploadId },
        dataType: 'json',
        success: function (response) {
          if (!response || !response.success) return;

          /* 🔥 1. REMOVE row from Favourite tab instantly */
          if ($row && $row.length) {
            $row.fadeOut(250, function () {
              $(this).remove();

              const remainingRows = $('#favourite-tbody tr[data-upload-id]').length;

              if (remainingRows === 0) {
                renderFavouriteEmptyState();
              }
            });
          }

          /* 🔥 2. Update favourite count */
          const $count = $('#count-favourite');
          const current = parseInt($count.text()) || 0;
          $count.text(Math.max(0, current - 1));

          /* 🔥 3. Update star icon everywhere (Uploaded / Pending / etc.) */
          $('.fav-btn[data-upload-id="' + uploadId + '"]')
            .removeClass('active')
            .find('i')
            .removeClass('fa-star')
            .addClass('fa-star-o');

          /* 🔥 4. Close floating menu */
          $('#floating-action-menu').remove();
          $('.action-dropdown').removeClass('open');

          // Show success toast
          Swal.fire({
            icon: 'success',
            title: 'Removed!',
            text: 'Document removed from favourites.',
            timer: 1500,
            showConfirmButton: false
          });
        },
        error: function () {
          Swal.fire('Error', 'Failed to remove favourite', 'error');
        }
      });
    }
  });
});

// Handle month-level favourite removal
$(document).on('click', '.remove-month-fav-btn', function (e) {
  e.preventDefault();

  const btn = $(this);
  const favouriteId = btn.data('favourite-id');
  if (!favouriteId) return;

  const $row = btn.closest('tr');

  Swal.fire({
    title: 'Remove Month Favourite?',
    text: 'Are you sure you want to remove this month from favourites?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#f59e0b',
    cancelButtonColor: '#6b7280',
    confirmButtonText: 'Yes, remove it'
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: base_url + 'dashboard/removeMonthFavourite',
        type: 'POST',
        data: { favourite_id: favouriteId },
        dataType: 'json',
        success: function (response) {
          if (response.success) {
            $row.fadeOut(300, function () {
              $(this).remove();
            });

            const $count = $('#count-favourite');
            const current = parseInt($count.text()) || 0;
            $count.text(Math.max(0, current - 1));

            $('#floating-action-menu').remove();
            $('.action-dropdown').removeClass('open');

            Swal.fire({
              icon: 'success',
              title: 'Removed!',
              text: 'Month removed from favourites.',
              timer: 1500,
              showConfirmButton: false
            });
          } else {
            Swal.fire('Error', response.message || 'Failed to remove favourite', 'error');
          }
        },
        error: function () {
          Swal.fire('Error', 'Failed to remove favourite', 'error');
        }
      });
    }
  });
});

// Handle month-level favourite notifications (Email/WhatsApp)
function handleMonthFavNotification(type, typeName, companyName, month, year, typeId, companyId) {
  const subject = encodeURIComponent(`Documents: ${typeName} - ${companyName} - ${month} ${year}`);
  const body = encodeURIComponent(`Please find the documents for:\n\nCompany: ${companyName}\nDocument Head: ${typeName}\nMonth: ${month} ${year}\n\nView documents at: ${base_url}company/view_documents/${typeId}/${companyId}/${year}/${month}`);
  
  if (type === 'mail') {
    window.location.href = `mailto:?subject=${subject}&body=${body}`;
  } else if (type === 'whatsapp') {
    const text = encodeURIComponent(`Documents: ${typeName} - ${companyName} - ${month} ${year}\n\nView at: ${base_url}company/view_documents/${typeId}/${companyId}/${year}/${month}`);
    window.open(`https://wa.me/?text=${text}`, '_blank');
  }
}

  
  // Auto-refresh of counts disabled - counts are loaded with page filters
  // If needed, manually refresh the page to update counts
  
  // Close dropdowns when clicking outside
  $(document).on('click', function(e) {
    if (!$(e.target).closest('.action-dropdown').length && !$(e.target).closest('#floating-action-menu').length) {
      $('.action-dropdown').removeClass('open');
      $('#floating-action-menu').remove();
    }
  });
  
  // Close floating menu when clicking an item
  $(document).on('click', '#floating-action-menu .action-dropdown__item', function() {
    $('#floating-action-menu').remove();
    $('.action-dropdown').removeClass('open');
  });
  
  // Initialize sortable headers
  $(document).on('click', '.data-table th.sortable', function() {
    const $th = $(this);
    const $table = $th.closest('table');
    const colIndex = $th.index();
    
    // Toggle sort direction
    let order = 'asc';
    if ($th.hasClass('sort-asc')) {
      order = 'desc';
    } else if ($th.hasClass('sort-desc')) {
      order = 'asc';
    }
    
    // Clear other column sorts
    $table.find('th.sortable').removeClass('sort-asc sort-desc');
    $th.addClass(order === 'asc' ? 'sort-asc' : 'sort-desc');
    
    // Sort the table
    sortTable('#' + $table.attr('id'), colIndex, order);
  });
  
  // Apply default sorting on page load for favourite tab
  applyDefaultSorting('favourite');
  
  // Check if there's an active_tab parameter in the URL (for redirect from upload page)
  const urlParams = new URLSearchParams(window.location.search);
  const activeTab = urlParams.get('active_tab');
  
  if (activeTab && ['favourite', 'pending', 'overdue', 'upcoming', 'uploaded'].includes(activeTab)) {
    // Activate the correct tab
    $('.stat-card').removeClass('active');
    $('.stat-card[data-tab="' + activeTab + '"]').addClass('active');
    
    // Load and show the tab
    $('.tab-pane').hide();
    $('#tab-' + activeTab).show();
    
    // Update header
    const config = tabConfig[activeTab];
    $('#tab-header')
      .removeClass('tab-header--favourite tab-header--pending tab-header--overdue tab-header--upcoming tab-header--uploaded')
      .addClass('tab-header--' + activeTab);
    $('#tab-title').html(`
      <i class="fa ${config.icon}"></i>
      <span>${config.title}</span>
      <span class="tab-header__badge" id="tab-count">${$('#count-' + activeTab).text()} items</span>
    `);
    
    // Load tab data if not already loaded
    if (!loadedTabs[activeTab]) {
      loadTabData(activeTab);
    } else {
      applyDefaultSorting(activeTab);
    }
  } else {
    // Initialize: Show favourite tab by default
    $('.tab-pane').hide();
    $('#tab-favourite').show();
  }
});

// Reset column search for current tab
function resetColumnSearch() {
  $('.column-search-input').val('');
  $('.data-table tbody tr').removeClass('hidden-row').show();

  // Reset sorting to tab default
  resetSortingToDefault(currentActiveTab);
}

function resetSortingToDefault(tab) {
  const tableId = '#' + tab + '-table';
  const $table = $(tableId);

  if (!$table.length) return;

  // Remove all sort arrows
  $table.find('th.sortable').removeClass('sort-asc sort-desc');

  // 🔥 Your exact defaults
  const defaults = {
    favourite: { sort: 'period',   order: 'desc' }, // Year ↓
    pending:   { sort: 'due-date', order: 'asc'  }, // Due Date ↑
    overdue:   { sort: 'due-date', order: 'asc'  }, // Due Date ↑
    upcoming:  { sort: 'due-date', order: 'asc'  }, // Due Date ↑
    uploaded:  { sort: 'period',   order: 'desc' }  // Period ↓
  };

  const cfg = defaults[tab];
  if (!cfg) return;

  const $th = $table.find(`th[data-sort="${cfg.sort}"]`);
  if (!$th.length) return;

  // Restore arrow direction
  $th.addClass(cfg.order === 'asc' ? 'sort-asc' : 'sort-desc');

  // Re-sort rows
  sortTable(tableId, $th.index(), cfg.order);
}

// Sort table function
function sortTable(tableId, colIndex, order) {

  const $table = $(tableId);
  const $tbody = $table.find('tbody');
  const rows = $tbody.find('tr').toArray();
  
  rows.sort(function (a, b) {

    const $aCell = $(a).find('td').eq(colIndex);
    const $bCell = $(b).find('td').eq(colIndex);

    // 🔥 1. If data-sort-date exists → use it (Due Date columns)
    const aSortDate = $aCell.data('sort-date');
    const bSortDate = $bCell.data('sort-date');

    if (aSortDate && bSortDate) {
      const aTime = new Date(aSortDate).getTime();
      const bTime = new Date(bSortDate).getTime();
      return order === 'asc' ? aTime - bTime : bTime - aTime;
    }

    // 🔁 2. Fallback to text sorting (other columns)
    const aText = $aCell.text().trim().toLowerCase();
    const bText = $bCell.text().trim().toLowerCase();

    // Numeric comparison
    const aNum = parseFloat(aText.replace(/[^0-9.-]/g, ''));
    const bNum = parseFloat(bText.replace(/[^0-9.-]/g, ''));

    if (!isNaN(aNum) && !isNaN(bNum)) {
      return order === 'asc' ? aNum - bNum : bNum - aNum;
    }

    // String comparison
    return order === 'asc'
      ? aText.localeCompare(bText)
      : bText.localeCompare(aText);
    });
  
  $tbody.append(rows);
  // Recalculate serial numbers (Sr. No.) after sorting - keep them as 1, 2, 3...
  /*$tbody.find('tr:visible').each(function(index) {
    $(this).find('td').first().text(index + 1);
  });*/

  // Recalculate serial numbers (Sr. No.) after sorting
  let sr = 1;

  $tbody.find('tr:visible').each(function () {
    const $cells = $(this).find('td');

    // ❌ Skip empty-state / loading rows (they have single td with colspan)
    if ($cells.length === 1 && $cells.attr('colspan')) return;

    // ✅ Number only real data rows
    $cells.first().text(sr++);
  });

}

// Parse date from table cell text
/*function parseTableDate(text) {
  // Try various date formats: "30 Jan 2025", "7th March 2025", "Jan 2025", etc.
  const months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
  const monthsFull = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
  
  const lowerText = text.toLowerCase().replace(/(\d+)(st|nd|rd|th)/gi, '$1'); // Remove ordinal suffixes
  
  // First, try to extract day if present (e.g., "30 Jan 2025", "7 March 2025")
  let day = 1;
  const dayMatch = lowerText.match(/^(\d{1,2})\s/);
  if (dayMatch) {
    day = parseInt(dayMatch[1]);
  }
  
  // Also try to find day after month (e.g., "Jan 30 2025")
  const dayAfterMonthMatch = lowerText.match(/[a-z]+\s+(\d{1,2})\s+\d{4}/i);
  if (dayAfterMonthMatch) {
    day = parseInt(dayAfterMonthMatch[1]);
  }
  
  for (let i = 0; i < months.length; i++) {
    if (lowerText.includes(months[i]) || lowerText.includes(monthsFull[i])) {
      const yearMatch = text.match(/\d{4}/);
      if (yearMatch) {
        return new Date(parseInt(yearMatch[0]), i, day);
      }
    }
  }
  
  // Try DD/MM/YYYY or MM/DD/YYYY
  const dateMatch = text.match(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/);
  if (dateMatch) {
    return new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1]);
  }
  
  // Try YYYY-MM-DD format
  const isoMatch = text.match(/(\d{4})-(\d{2})-(\d{2})/);
  if (isoMatch) {
    return new Date(isoMatch[1], isoMatch[2] - 1, isoMatch[3]);
  }
  
  return null;
}*/

// Export current tab to Excel
function exportCurrentTab() {
  const tab = currentActiveTab || 'favourite';
  // Get actual selected company name from session/page
  const companyName = '<?= addslashes($company_name ?? "Company") ?>';
  // Get selected year from filter
  const selectedYear = document.getElementById('filter-year') ? document.getElementById('filter-year').value : '<?= date("Y") ?>';
  
  // Build export URL with tab, company and year parameters
  const exportUrl = '<?= base_url("dashboard/export_documents_excel") ?>?tab=' + tab + 
    '&company=' + encodeURIComponent(companyName) + 
    '&year=' + encodeURIComponent(selectedYear);
  
  window.location.href = exportUrl;
}

// Toggle action dropdown - using fixed position popup
function toggleActionDropdown(btn) {
  event.stopPropagation();
  
  // Remove any existing floating menu
  $('#floating-action-menu').remove();
  
  const $btn = $(btn);
  const $dropdown = $btn.closest('.action-dropdown');
  const $menu = $dropdown.find('.action-dropdown__menu');

  const $row = $btn.closest('tr');
  
  // If already open, just close it
  if ($dropdown.hasClass('open')) {
    $dropdown.removeClass('open');
    return;
  }
  
  // Close other dropdowns
  $('.action-dropdown').removeClass('open');
  
  // Clone the menu and append to body with fixed positioning
  const $floatingMenu = $menu.clone().attr('id', 'floating-action-menu');

  if ($row.length) {
    $floatingMenu.data('source-row', $row); // 🔥 safe & optional
  }

  $('body').append($floatingMenu);
  
  // Get button position
  const btnRect = btn.getBoundingClientRect();
  const menuHeight = 180; // approximate menu height
  const viewportHeight = window.innerHeight;
  const spaceBelow = viewportHeight - btnRect.bottom;
  
  // Position the floating menu
  let top, left;
  left = btnRect.right - 180; // align right edge with button
  if (left < 10) left = 10;
  
  if (spaceBelow < menuHeight) {
    // Open upward
    top = btnRect.top - menuHeight - 5;
  } else {
    // Open downward
    top = btnRect.bottom + 5;
  }
  
  $floatingMenu.css({
    position: 'fixed',
    top: top + 'px',
    left: left + 'px',
    opacity: 1,
    visibility: 'visible',
    transform: 'none',
    zIndex: 99999,
    background: '#fff',
    borderRadius: '8px',
    boxShadow: '0 10px 40px rgba(0,0,0,0.2)',
    minWidth: '180px'
  });
  
  $dropdown.addClass('open');
}

// Handle upload click with confirmation - uses plain URL (encryption disabled for now)
function handleUploadClick(companyId, authorityId, typeId, month, year, pendingCount, totalDocs, sourceTab = '') {
  // Close dropdown
  $('.action-dropdown').removeClass('open');
  $('#floating-action-menu').remove();
  
  // Check edit permission
  if (!canEdit) {
    Swal.fire({
      title: 'Permission Denied',
      text: 'You do not have permission to upload documents.',
      icon: 'error',
      confirmButtonColor: '#dc3545',
      confirmButtonText: 'OK'
    });
    return;
  }
  
  // For upcoming documents, only allow upload if it's the current month
  if (sourceTab === 'upcoming') {
    const currentMonth = new Date().getMonth() + 1; // JS months are 0-indexed
    const currentYear = new Date().getFullYear();
    const uploadMonth = parseInt(month);
    const uploadYear = parseInt(year);
    
    // Allow upload only if the period is current month or past (not future months)
    if (uploadYear > currentYear || (uploadYear === currentYear && uploadMonth > currentMonth)) {
      const monthNames = ['', 'January', 'February', 'March', 'April', 'May', 'June', 
                          'July', 'August', 'September', 'October', 'November', 'December'];
      const periodMonthName = monthNames[uploadMonth] || 'Unknown';
      const currentMonthName = monthNames[currentMonth];
      
      Swal.fire({
        title: 'Document Not Due Yet',
        html: `<p>This document is scheduled for <strong>${periodMonthName} ${uploadYear}</strong>.</p>
               <p>You can only upload documents for the current month (<strong>${currentMonthName} ${currentYear}</strong>) or earlier periods.</p>`,
        icon: 'warning',
        confirmButtonColor: '#f59e0b',
        confirmButtonText: 'OK, Got it'
      });
      return;
    }
  }
  
  // Get current tab and year filter for redirect back
  const currentTab = $('.stat-card.active').data('tab') || 'favourite';
  const selectedYear = $('#filter-year').val() || 'all';
  const selectedCompanies = Array.from(document.getElementById('filter-company').selectedOptions)
    .map(option => option.value).join(',');
  
  // Plain URL with all parameters including redirect info
  const uploadUrl = '<?= base_url('upload/index/') ?>' + companyId + 
    '?authority_id=' + authorityId + 
    '&type_id=' + typeId + 
    '&month=' + month + 
    '&year=' + year + 
    '&readonly=1&from=dashboard' +
    '&return_tab=' + currentTab +
    '&return_year=' + selectedYear +
    '&return_companies=' + encodeURIComponent(selectedCompanies);
  
  console.log('Upload URL:', uploadUrl);
  
  // If all documents are already uploaded
  if (pendingCount === 0) {
    Swal.fire({
      title: 'All Documents Uploaded',
      text: 'All ' + totalDocs + ' documents are already uploaded. Do you still want to continue?',
      icon: 'info',
      showCancelButton: true,
      confirmButtonColor: '#3b82f6',
      cancelButtonColor: '#6b7280',
      confirmButtonText: 'Yes, Continue',
      cancelButtonText: 'No, Cancel'
    }).then((result) => {
      if (result.isConfirmed) {
        showLoader();
        window.location.href = uploadUrl;
      }
    });
  } else {
    // Redirect directly
    showLoader();
    window.location.href = uploadUrl;
  }
}

// Handle notification (Mail/WhatsApp)
//function handleNotification(type, typeName, companyName, month, year, typeId, companyId, authorityId) {
  function handleNotification(
  type,
  typeName,
  companyName,
  month,
  year,
  typeId,
  companyId,
  authorityId,
  dueDay = null,
  dueMonth = null,
  dueYear = null,
  adjustReason = ''
) {
// Close dropdown
  $('.action-dropdown').removeClass('open');
  $('#floating-action-menu').remove();
  
  const dueReason = adjustReason || '';
  const baseUrl = '<?= base_url() ?>';
  const monthNames = ['', 'January', 'February', 'March', 'April', 'May', 'June', 
                      'July', 'August', 'September', 'October', 'November', 'December'];
  const monthName = monthNames[parseInt(month)] || month;
  
  // Build upload URL with auth check
  const uploadUrl = baseUrl + 'upload/index/' + companyId + 
    '?authority_id=' + authorityId + 
    '&type_id=' + typeId + 
    '&month=' + month + 
    '&year=' + year +
    '&readonly=1&from=notification';
  
  if (type === 'mail') {
    // Show email dialog
    Swal.fire({
      title: 'Send Email Notification',
      html: `
        <div style="text-align: left;">
          <p style="margin-bottom: 15px; color: #666;">
            Send a reminder email for <strong>${typeName}</strong> - ${monthName} ${year}
          </p>
          <div style="margin-bottom: 10px;">
            <label style="display: block; margin-bottom: 5px; font-weight: 500;">Recipient Email:</label>
            <input type="email" id="swal-recipient" class="swal2-input" placeholder="Enter email address" style="margin: 0; width: 100%;">
      </div>
      </div>
      `,
      icon: 'info',
      showCancelButton: true,
      confirmButtonColor: '#3b82f6',
      cancelButtonColor: '#6b7280',
      confirmButtonText: '<i class="fa fa-paper-plane"></i> Send Email',
      cancelButtonText: 'Cancel',
      showLoaderOnConfirm: true,
      preConfirm: () => {
        const recipient = document.getElementById('swal-recipient').value;
        if (!recipient) {
          Swal.showValidationMessage('Please enter an email address');
          return false;
        }
        if (!recipient.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
          Swal.showValidationMessage('Please enter a valid email address');
          return false;
        }
        
        // Send email via AJAX
        return $.ajax({
          url: baseUrl + 'dashboard/sendNotificationEmail',
          type: 'POST',
          data: {
            recipient: recipient,
            type_name: typeName,
            company_name: companyName,
            month: month,
            year: year,
            type_id: typeId,
            company_id: companyId,
            authority_id: authorityId,
            due_day: dueDay,
            due_month: dueMonth,
            due_year: dueYear,
            due_reason: dueReason
          },
          dataType: 'json',
          timeout: 30000  // 30 second timeout
        }).then(response => {
          if (!response.success) {
            Swal.showValidationMessage(response.message || 'Failed to send email');
            return false;
          }
          return response;
        }).catch(error => {
          console.error('Email AJAX Error:', error);
          Swal.showValidationMessage('Network error or server timeout. Please try again.');
          return false;
        });
      },
      allowOutsideClick: true
    }).then((result) => {
      if (result.isConfirmed && result.value) {
        Swal.fire({
          icon: 'success',
          title: 'Email Sent!',
          text: result.value.message,
          confirmButtonColor: '#10b981'
        });
      }
    });
  } else if (type === 'whatsapp') {
    // WhatsApp - show phone number input
    Swal.fire({
      title: 'Send WhatsApp Message',
      html: `
        <div style="text-align: left;">
          <p style="margin-bottom: 15px; color: #666;">
            Send a reminder for <strong>${typeName}</strong> - ${monthName} ${year}
          </p>
          <div style="margin-bottom: 10px;">
            <label style="display: block; margin-bottom: 5px; font-weight: 500;">Phone Number (with country code):</label>
            <input type="tel" id="swal-phone" class="swal2-input" placeholder="e.g., 919876543210" style="margin: 0; width: 100%;">
    </div>
</div>
      `,
      icon: 'info',
      showCancelButton: true,
      confirmButtonColor: '#25D366',
      cancelButtonColor: '#6b7280',
      confirmButtonText: '<i class="fab fa-whatsapp"></i> Send WhatsApp',
      cancelButtonText: 'Cancel',
      preConfirm: () => {
        const phone = document.getElementById('swal-phone').value.replace(/\D/g, '');
        if (!phone) {
          Swal.showValidationMessage('Please enter a phone number');
          return false;
        }
        if (phone.length < 10) {
          Swal.showValidationMessage('Please enter a valid phone number with country code');
          return false;
        }
        return phone;
      }
    }).then((result) => {
      if (result.isConfirmed && result.value) {
        const phone = result.value;
        const whatsappText = '*Document Pending: ' + typeName + ' - ' + monthName + ' ' + year + '*\n\n' +
          'Company: ' + companyName + '\n' +
          'Document Head: ' + typeName + '\n' +
          'Period: ' + monthName + ' ' + year + '\n\n' +
          'Please upload the documents using this link:\n' + uploadUrl;
        
        // Open WhatsApp with phone number
        const whatsappUrl = 'https://wa.me/' + phone + '?text=' + encodeURIComponent(whatsappText);
        window.open(whatsappUrl, '_blank');
      }
    });
  }
}

// ===== Dashboard Filter Functions =====

function applyFilters() {
  const selectedYear = document.getElementById('filter-year').value;
  const selectedCompanies = Array.from(document.getElementById('filter-company').selectedOptions)
    .map(option => option.value);
  
  // Show loading
  showLoader();
  
  // Build URL with company IDs and year
  let url = '<?= base_url('dashboard/dashboard') ?>?';
  if (selectedCompanies.length > 0) {
    url += 'companies=' + selectedCompanies.join(',') + '&';
  }
  url += 'year=' + selectedYear;
  
  window.location.href = url;
}

function resetFilters() {
  // Reset to all companies (select all options)
  const companySelect = document.getElementById('filter-company');
  Array.from(companySelect.options).forEach(option => option.selected = true);
  
  // Reset to 'all' years
  document.getElementById('filter-year').value = 'all';
  
  // Show loading
  showLoader();
  
  // Redirect with reset filters
  window.location.href = '<?= base_url('dashboard/dashboard') ?>?year=all';
}

// Initialize filter display
$(document).ready(function() {
  // Initialize company dropdown checkboxes
  $('.company-checkbox').on('change', function() {
    syncCompanySelection();
    updateCompanyDropdownText();
    //updateFilterTags();
  });
  
  // Close dropdown when clicking outside
  document.addEventListener('click', function(e) {
    var wrapper = document.querySelector('.company-dropdown-wrapper');
    if (wrapper && !wrapper.contains(e.target)) {
      wrapper.classList.remove('open');
    }
  });
  
  //updateFilterTags();
  
  // Update filter tags when year changes
  $('#filter-year').on('change', function() {
    //updateFilterTags();
  });
});

// Toggle company dropdown
function toggleCompanyDropdown(event) {
  if (event) {
    event.stopPropagation();
  }
  var wrapper = document.querySelector('.company-dropdown-wrapper');
  if (wrapper) {
    wrapper.classList.toggle('open');
  }
}

// Sync checkboxes with hidden select
function syncCompanySelection() {
  $('#filter-company option').each(function() {
    const value = $(this).val();
    const isChecked = $('.company-checkbox[value="' + value + '"]').prop('checked');
    $(this).prop('selected', isChecked);
  });
}

// Update dropdown button text
function updateCompanyDropdownText() {
  const totalCompanies = $('.company-checkbox').length;
  const selectedCount = $('.company-checkbox:checked').length;
  
  let text = '';
  if (selectedCount === 0) {
    text = 'Select Companies...';
  } else if (selectedCount === totalCompanies) {
    text = 'All Companies (' + totalCompanies + ')';
  } else {
    text = selectedCount + ' of ' + totalCompanies + ' Companies';
  }
  
  $('#company-dropdown-text').text(text);
}

// Quick select functions
function selectAllCompanies() {
  $('.company-checkbox').prop('checked', true);
  syncCompanySelection();
  updateCompanyDropdownText();
  //updateFilterTags();
}

function deselectAllCompanies() {
  $('.company-checkbox').prop('checked', false);
  syncCompanySelection();
  updateCompanyDropdownText();
  //updateFilterTags();
}

/*function updateFilterTags() {
  const tagsContainer = document.getElementById('filter-tags');
  tagsContainer.innerHTML = '';
  
  // Get selected companies
  const companySelect = document.getElementById('filter-company');
  const totalCompanies = companySelect.options.length;
  const selectedCompanies = Array.from(companySelect.selectedOptions);
  
  // Only show company tags if not all are selected
  if (selectedCompanies.length > 0 && selectedCompanies.length < totalCompanies) {
    if (selectedCompanies.length <= 2) {
      // Show individual company names
      selectedCompanies.forEach(opt => {
        tagsContainer.innerHTML += `
          <span class="filter-tag">
            <i class="fa fa-building"></i> ${opt.text}
            <span class="filter-tag__remove" onclick="removeCompanyFilter('${opt.value}')">&times;</span>
          </span>
        `;
      });
    } else {
      // Show count
      tagsContainer.innerHTML += `
        <span class="filter-tag">
          <i class="fa fa-building"></i> ${selectedCompanies.length} companies selected
        </span>
      `;
    }
  }
  
  // Show year tag if different from current year or if "all" is selected
  const yearSelect = document.getElementById('filter-year');
  const currentYear = new Date().getFullYear();
  if (yearSelect.value === 'all') {
    tagsContainer.innerHTML += `
      <span class="filter-tag filter-tag--info">
        <i class="fa fa-calendar"></i> All Years
        <span class="filter-tag__remove" onclick="resetYearFilter()">&times;</span>
      </span>
    `;
  } else if (yearSelect.value != currentYear) {
    tagsContainer.innerHTML += `
      <span class="filter-tag">
        <i class="fa fa-calendar"></i> ${yearSelect.value}
        <span class="filter-tag__remove" onclick="resetYearFilter()">&times;</span>
      </span>
    `;
  }
}*/

function removeCompanyFilter(companyId) {
  // Uncheck the checkbox
  $('.company-checkbox[value="' + companyId + '"]').prop('checked', false);
  // Sync with hidden select
  syncCompanySelection();
  updateCompanyDropdownText();
  //updateFilterTags();
}

function resetYearFilter() {
  document.getElementById('filter-year').value = 'all';
  //updateFilterTags();
}

function updateYearDropdown() {
    const yearSelect = document.getElementById('filter-year');
    const checkedCompanies = document.querySelectorAll('.company-checkbox:checked');
    const currentYear = new Date().getFullYear();

    let startYear;

    if (checkedCompanies.length === 1) {
        // ✅ Single company → use its co_start_date year
        startYear = parseInt(checkedCompanies[0].dataset.startYear);
    } else {
        // ✅ Multiple or zero companies → fixed start year 2024
        startYear = 2024;
    }

    // Safety fallback
    if (!startYear || startYear > currentYear) {
        startYear = currentYear;
    }

    const selectedValue = yearSelect.value;

    // Rebuild year dropdown with "All Years" option
    yearSelect.innerHTML = '';
    
    // Add "All Years" option first
    const allOpt = document.createElement('option');
    allOpt.value = 'all';
    allOpt.textContent = 'All Years';
    yearSelect.appendChild(allOpt);
    
    // Add individual year options
    for (let y = currentYear; y >= startYear; y--) {
        const opt = document.createElement('option');
        opt.value = y;
        opt.textContent = y;
        yearSelect.appendChild(opt);
    }

    // Preserve selected year if still valid
    if (selectedValue === 'all') {
        yearSelect.value = 'all';
    } else if (selectedValue >= startYear && selectedValue <= currentYear) {
        yearSelect.value = selectedValue;
    }
}

// 🔁 Update when company selection changes
document.addEventListener('change', function (e) {
    if (e.target.classList.contains('company-checkbox')) {
        updateYearDropdown();
    }
});

// 🔥 Initial load
updateYearDropdown();

// ======== Dashboard Action Dropdown ========
$(document).on('click', '.action-btn--menu', function(e) {
    e.stopPropagation();
    const wrapper = $(this).closest('.action-dropdown-wrapper');
    
    // Close all other dropdowns
    $('.action-dropdown-wrapper').not(wrapper).removeClass('open');
    
    // Toggle this dropdown
    wrapper.toggleClass('open');
});

// Close dropdown when clicking outside
$(document).on('click', function(e) {
    if (!$(e.target).closest('.action-dropdown-wrapper').length) {
        $('.action-dropdown-wrapper').removeClass('open');
    }
});

// Handle notification for uploaded documents
// uploadId is optional - if provided, only that specific document will be attached
function handleUploadedNotification(type, typeName, companyName, monthName, year, typeId, companyId, uploadId = null) {
  // Close dropdown
  $('.action-dropdown').removeClass('open');
  $('#floating-action-menu').remove();
  
  const baseUrl = '<?= base_url() ?>';
  
  if (type === 'mail') {
    // Show email dialog
    Swal.fire({
      title: '<i class="fa fa-envelope text-info"></i> Share Documents',
      html: `
        <div class="text-start">
          <p class="mb-3 text-muted">Share Documents <strong>${companyName}</strong></p>
          <div class="mb-3">
            <label class="form-label fw-bold">Subject</label>
            <input type="text" id="email-subject" class="form-control" value="Document Shared: ${companyName} - ${typeName} - ${monthName} ${year}" style="width: 100%;">
          </div>
          <div class="mb-3">
            <label class="form-label fw-bold">Recipient Email</label>
            <input type="email" id="email-recipient" class="form-control" placeholder="Enter email address" style="width: 100%;">
          </div>
          <div class="mb-3">
            <label class="form-label fw-bold">Additional Message (Optional)</label>
            <textarea id="email-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 recipient = document.getElementById('email-recipient').value;
        const subject = document.getElementById('email-subject').value;
        const message = document.getElementById('email-message').value;
        
        if (!recipient) {
          Swal.showValidationMessage('Please enter recipient email');
          return false;
        }
        if (!recipient.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
          Swal.showValidationMessage('Please enter a valid email address');
          return false;
        }
        
        return { recipient, subject, message };
      }
    }).then((result) => {
      if (result.isConfirmed) {
        // Show loading popup
        Swal.fire({
          title: 'Sending Email...',
          html: '<div class="d-flex flex-column align-items-center"><i class="fa fa-spinner fa-spin fa-3x mb-3" style="color: #3b82f6;"></i><p class="mb-0">Please wait while we send your email.</p></div>',
          allowOutsideClick: false,
          allowEscapeKey: false,
          showConfirmButton: false
        });
        
        // Build data object
        const data = {
          company_id: companyId,
          type_id: typeId,
          month: monthName,
          year: year,
          recipient: result.value.recipient,
          subject: result.value.subject,
          message: result.value.message
        };
        
        // Add upload_id if sending specific document
        if (uploadId) {
          data.upload_id = uploadId;
        }
        
        // Send email via AJAX
        $.ajax({
          url: baseUrl + 'dashboard/send_reminder_email',
          type: 'POST',
          data: data,
          dataType: 'json',
          success: function(response) {
            if (response.success) {
              Swal.fire({
                icon: 'success',
                title: 'Email Sent!',
                text: response.message || '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 email.'
            });
          }
        });
      }
    });
  } else if (type === 'whatsapp') {
    // WhatsApp - show phone number input
    Swal.fire({
      title: 'Send WhatsApp Message',
      html: `
        <div style="text-align: left;">
          <p style="margin-bottom: 15px; color: #666;">
            Send a message for <strong>${typeName}</strong> - ${monthName} ${year}
          </p>
          <div style="margin-bottom: 10px;">
            <label style="display: block; margin-bottom: 5px; font-weight: 500;">Phone Number (with country code):</label>
            <input type="tel" id="swal-phone" class="swal2-input" placeholder="e.g., 919876543210" style="margin: 0; width: 100%;">
          </div>
        </div>
      `,
      icon: 'info',
      showCancelButton: true,
      confirmButtonColor: '#25D366',
      cancelButtonColor: '#6b7280',
      confirmButtonText: '<i class="fab fa-whatsapp"></i> Send WhatsApp',
      cancelButtonText: 'Cancel',
      preConfirm: () => {
        const phone = document.getElementById('swal-phone').value.replace(/\D/g, '');
        if (!phone) {
          Swal.showValidationMessage('Please enter a phone number');
          return false;
        }
        if (phone.length < 10) {
          Swal.showValidationMessage('Please enter a valid phone number with country code');
          return false;
        }
        return phone;
      }
    }).then((result) => {
      if (result.isConfirmed && result.value) {
        const phone = result.value;
        const whatsappText = '*Document: ' + typeName + ' - ' + monthName + ' ' + year + '*\n\n' +
          'Company: ' + companyName + '\n' +
          'Document Head: ' + typeName + '\n' +
          'Period: ' + monthName + ' ' + year + '\n\n' +
          'Documents have been uploaded for this period.';
        
        // Open WhatsApp with phone number
        const whatsappUrl = 'https://wa.me/' + phone + '?text=' + encodeURIComponent(whatsappText);
        window.open(whatsappUrl, '_blank');
      }
    });
  }
}

// ======== Dashboard Notification Handlers ========
$(document).on('click', '.dashboard-notify', function(e) {
    e.preventDefault();
    
    const $this = $(this);
    const type = $this.data('type');
    const company = $this.data('company');
    const dochead = $this.data('dochead');
    const month = $this.data('month');
    const year = $this.data('year');
    const companyId = $this.data('company-id');
    const typeId = $this.data('type-id');
    
    // Close the dropdown
    $('.action-dropdown-wrapper').removeClass('open');
    
    const subject = `${dochead} - ${month} ${year}`;
    
    if (type === 'email') {
        Swal.fire({
            title: '<i class="fa fa-envelope text-info"></i> Send Reminder',
            html: `
                <div class="text-start">
                    <p class="mb-3 text-muted">Send reminder for <strong>${company}</strong></p>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Subject</label>
                        <input type="text" id="email-subject" class="form-control" value="${subject}" style="width: 100%;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Recipient Email</label>
                        <input type="email" id="email-recipient" class="form-control" placeholder="Enter email address" style="width: 100%;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Additional Message (Optional)</label>
                        <textarea id="email-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 recipient = document.getElementById('email-recipient').value;
                const subject = document.getElementById('email-subject').value;
                const message = document.getElementById('email-message').value;
                
                if (!recipient) {
                    Swal.showValidationMessage('Please enter recipient email');
                    return false;
                }
                
                return { recipient, subject, message };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Send email via AJAX
                $.ajax({
                    url: baseUrl + 'dashboard/send_reminder_email',
                    type: 'POST',
                    data: {
                        company_id: companyId,
                        type_id: typeId,
                        month: month,
                        year: year,
                        recipient: result.value.recipient,
                        subject: result.value.subject,
                        message: result.value.message
                    },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Email Sent!',
                                text: 'Reminder email has been sent successfully.',
                                timer: 2000,
                                showConfirmButton: false
                            });
                        } else {
                            Swal.fire('Error', response.message || 'Failed to send email', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error', 'Failed to send email', 'error');
                    }
                });
            }
        });
    } else if (type === 'whatsapp') {
        const message = `Reminder: ${subject}\nCompany: ${company}\nPlease review the uploaded documents.`;
        const whatsappUrl = `https://wa.me/?text=${encodeURIComponent(message)}`;
        window.open(whatsappUrl, '_blank');
    }
});

// Column-wise search functionality
function initColumnSearch(tableId) {
    const $table = $('#' + tableId);
    if (!$table.length) return;
    
    $table.find('.column-search-input').on('keyup change', function() {
        const $inputs = $table.find('.column-search-input');
        const $rows = $table.find('tbody tr');
        
        $rows.each(function() {
            const $row = $(this);
            let show = true;
            
            $inputs.each(function() {
                const col = parseInt($(this).data('column'), 10);
                const searchVal = $(this).val().toLowerCase().trim();
                
                if (searchVal) {
                    const cellText = $row.find('td').eq(col).text().toLowerCase();
                    if (cellText.indexOf(searchVal) === -1) {
                        show = false;
                        return false; // break the loop
                    }
                }
            });
            
            if (show) {
                $row.removeClass('hidden-row');
            } else {
                $row.addClass('hidden-row');
            }
        });
        
        // Update visible row numbers
        let visibleIndex = 1;
        $rows.not('.hidden-row').each(function() {
            $(this).find('td').first().text(visibleIndex++);
        });
    });
}

// Initialize column search for all tables
$(document).ready(function() {
    initColumnSearch('uploaded-table');
    initColumnSearch('favourite-table');
    initColumnSearch('pending-table');
    initColumnSearch('overdue-table');
    initColumnSearch('upcoming-table');
});

function renderFavouriteEmptyState() {
  $('#favourite-tbody').html(`
    <tr>
      <td colspan="9">
        <div class="empty-state">
          <i class="fa fa-star"></i>
          <p>No favourite documents yet. Click the star icon on any document to add it here.</p>
        </div>
      </td>
    </tr>
  `);
}

</script>