<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">

<style>
  .sortable-header {
    cursor: pointer;
    position: relative;
    user-select: none;
    padding-right: 25px !important;
}

.sortable-header:hover {
    background-color: #f8f9fa;
}

.sort-icon {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 12px;
    color: #6c757d;
    transition: color 0.2s;
}

.sort-icon.active {
    color: #0d6efd;
}
</style>

<!-- Table -->
<div class="table-responsive">
  <table class="table table-bordered table-hover align-middle text-center">
   <thead class="table-light">
  <tr>
    <th class="text-nowrap sortable-header" onclick="sortTable('userTable', 0, 'text')">
      SECTION
      <i class="bi bi-arrow-down-up sort-icon"></i>
    </th>
    <th class="text-nowrap sortable-header" onclick="sortTable('userTable', 1, 'text')">
      UNIT/OFFICE
      <i class="bi bi-arrow-down-up sort-icon"></i>
    </th>
    <th class="text-nowrap sortable-header" onclick="sortTable('userTable', 2, 'text')">
      NAME
      <i class="bi bi-arrow-down-up sort-icon"></i>
    </th>
    <th class="text-nowrap sortable-header" onclick="sortTable('userTable', 3, 'text')">
      ROLES
      <i class="bi bi-arrow-down-up sort-icon"></i>
    </th>
    <th class="text-nowrap sortable-header" onclick="sortTable('userTable', 4, 'text')">
      ACCESS STATUS
      <i class="bi bi-arrow-down-up sort-icon"></i>
    </th>
    <th class="text-nowrap sortable-header" onclick="sortTable('userTable', 5, 'text')">
      LAST ACCESS
      <i class="bi bi-arrow-down-up sort-icon"></i>
    </th>
    <th class="text-nowrap sortable-header" onclick="sortTable('userTable', 6, 'text')">
      ACTION
      <i class="bi bi-arrow-down-up sort-icon"></i>
    </th>
  </tr>
</thead>
    <tbody>
      <tr>
        <!-- <td class="text-capitalize small col-division">Promotion & Market Access Division</td> -->
        <td class="text-capitalize small col-section">Europe & Americas Section</td>
        <td class="text-capitalize small col-unit">N/A</td>
        <td class="text-capitalize small col-name">Abdul Halim Mohamed Shariff</td>
        <!-- <td class="small col-email">abdulhalim@gmail.com</td> -->
        <td class="text-capitalize small col-roles">MATRADE Employee</td>
        <td class="col-status"><span class="badge bg-success">Active</span></td>
        <td class="small col-lastaccess">17/06/2023 05:27 PM</td>
        <td class="col-action">
          <a href="{{ route('kpiAdmin-edit') }}">
            <i class="bx bx-edit text-primary cursor-pointer"></i>
          </a>
        </td>
      </tr>
      <tr>
        <td class="text-capitalize small col-section">Europe & Americas Section</td>
        <td class="text-capitalize small col-unit">N/A</td>
        <td class="text-capitalize small col-name">AbdulHalimMustafa</td>
        <td class="text-capitalize small col-roles">MATRADE Employee</td>
        <td class="col-status"><span class="badge bg-danger">Inactive</span></td>
        <td class="small col-lastaccess">11/09/2023 01:35 PM</td>
        <td class="col-action">
          <a href="{{ route('kpiAdmin-edit') }}">
            <i class="bx bx-edit text-primary cursor-pointer"></i>
          </a>
        </td>
      </tr>
    </tbody>
  </table>
</div>

<!-- Column Selector Modal -->
<div class="modal fade" id="columnSelectorModal" tabindex="-1" aria-labelledby="columnSelectorModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="columnSelectorModalLabel">Modify Column - List of User Access Configuration Columns</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body column-selector-modal">
        <p>Select columns to display:</p>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="division" id="divisionColumn">
          <label class="form-check-label" for="divisionColumn">Division</label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="section" id="sectionColumn" checked>
          <label class="form-check-label" for="sectionColumn">Section</label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="unit" id="unitColumn" checked>
          <label class="form-check-label" for="unitColumn">Unit/Office</label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="name" id="nameColumn" checked>
          <label class="form-check-label" for="nameColumn">Name</label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="email" id="emailColumn">
          <label class="form-check-label" for="emailColumn">Email</label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="roles" id="rolesColumn" checked>
          <label class="form-check-label" for="rolesColumn">Roles</label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="status" id="statusColumn" checked>
          <label class="form-check-label" for="statusColumn">Access Status</label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="lastaccess" id="lastAccessColumn" checked>
          <label class="form-check-label" for="lastAccessColumn">Last Access</label>
        </div>
        <div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-column="action" id="actionColumn" checked>
          <label class="form-check-label" for="actionColumn">Action</label>
        </div>
      </div>
      <div class="modal-footer justify-content-end">
        <button type="button" class="btn btn-primary btn-sm" onclick="selectAllColumns()">Select All</button>
        <button type="button" class="btn btn-secondary btn-sm" onclick="deselectAllColumns()">Deselect All</button>
        <button type="button" class="btn btn-success btn-sm" onclick="applyColumnSettings()">Apply</button>
      </div>
    </div>
  </div>
</div>

<!-- JavaScript -->
<script>
  function selectAllColumns() {
    document.querySelectorAll('.column-toggle').forEach(cb => cb.checked = true);
  }

  function deselectAllColumns() {
    document.querySelectorAll('.column-toggle').forEach(cb => {
      if (!cb.disabled) cb.checked = false;
    });
  }

  function applyColumnSettings() {
    const checkboxes = document.querySelectorAll('.column-toggle');

    checkboxes.forEach(cb => {
      const columnClass = 'col-' + cb.dataset.column;
      const cells = document.querySelectorAll('.' + columnClass);
      cells.forEach(cell => {
        cell.style.display = cb.checked ? '' : 'none';
      });
    });
  });

  // ADD THESE SORTING FUNCTIONS
let sortDirections = {}; // Track sort direction for each column

function sortTable(tableId, columnIndex, dataType) {
    const table = document.getElementById(tableId);
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const header = table.querySelector(`thead th:nth-child(${columnIndex + 1})`);
    const sortIcon = header.querySelector('.sort-icon');
    
    // Clear other active sort icons
    table.querySelectorAll('.sort-icon').forEach(icon => {
        if (icon !== sortIcon) {
            icon.classList.remove('active');
            icon.className = 'bi bi-arrow-down-up sort-icon';
        }
    });
    
    // Determine sort direction
    const sortKey = `${tableId}_${columnIndex}`;
    const currentDirection = sortDirections[sortKey] || 'asc';
    const newDirection = currentDirection === 'asc' ? 'desc' : 'asc';
    sortDirections[sortKey] = newDirection;
    
    // Update sort icon
    sortIcon.classList.add('active');
    sortIcon.className = newDirection === 'asc' ? 
        'bi bi-arrow-up sort-icon active' : 
        'bi bi-arrow-down sort-icon active';
    
    // Sort rows
    rows.sort((a, b) => {
        const aCell = a.cells[columnIndex];
        const bCell = b.cells[columnIndex];
        
        let aValue = aCell.textContent.trim();
        let bValue = bCell.textContent.trim();
        
        // Handle status badges - extract text content
        if (aCell.querySelector('.badge')) {
            aValue = aCell.querySelector('.badge').textContent.trim();
        }
        if (bCell.querySelector('.badge')) {
            bValue = bCell.querySelector('.badge').textContent.trim();
        }
        
        // Convert to appropriate data type
        if (dataType === 'number') {
            // Remove commas and convert to number
            aValue = parseFloat(aValue.replace(/,/g, '')) || 0;
            bValue = parseFloat(bValue.replace(/,/g, '')) || 0;
            
            if (newDirection === 'asc') {
                return aValue - bValue;
            } else {
                return bValue - aValue;
            }
        } else {
            // Text sorting (alphabetical)
            aValue = aValue.toLowerCase();
            bValue = bValue.toLowerCase();
            
            if (newDirection === 'asc') {
                return aValue.localeCompare(bValue);
            } else {
                return bValue.localeCompare(aValue);
            }
        }
    });
    
    // Clear tbody and re-append sorted rows
    tbody.innerHTML = '';
    rows.forEach(row => tbody.appendChild(row));
    
    // Add visual feedback
    header.style.backgroundColor = '#e3f2fd';
    setTimeout(() => {
        header.style.backgroundColor = '';
    }, 300);
}
</script>
