@extends('layouts/contentNavbarLayout')

@section('title', 'KPI Achievement')

@section('content')
 @php
  $breadcrumbs = [
    ['label' => 'Dashboard', 'url' => route('dashboard-analytics')],
    ['label' => 'KPI Achievement'],
    ['label' => 'List of Achievement']
  ];
@endphp

@include('layouts.partials.page-header', [
  'title' => 'List of Achievement',
  'slot' => view('layouts.partials.breadcrumb', compact('breadcrumbs'))->render()
])
<!-- <script src="{{ asset('js/kpiAchievement.js') }}"></script> -->
 @vite('resources/assets/js/kpiAchievement.js')

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


<!-- Bootstrap Bundle with Popper.js (for modal functionality) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>


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

<!-- Feather Icons -->
<script src="https://unpkg.com/feather-icons"></script>

<script>
    feather.replace(); // untuk aktifkan feather icons
</script>

<style>
  .swal2-container {
    z-index: 11000 !important;
  }

  #achievementDetailsPage {
    transition: all 0.4s ease;
  }

  /* .modal-backdrop {
    display: none !important;
  } */

  body.modal-open {
    overflow: auto !important;
    padding-right: 0 !important;
  }

  .table td, .table th {
    padding: 0.75rem 1rem;
    vertical-align: middle;
    border: 1px solid #dee2e6;
  }

  .table-hover tbody tr:hover {
    background-color: #f8f9fa;
  }

  .table-responsive .table {
    border-radius: 0.75rem;
    overflow: hidden;
  }

  .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>

<!-- Pills -->

    <br>
    <!-- <div class="row">
      <div class="col-12 d-flex justify-content-between align-items-center">
        <h4 class="fw-bold py-2 mb-3"></h4>
        <button type="button" class="btn btn-primary" id="toggleSearchFilter">
        <i class="bi bi-search me-1"></i> Search Filter
      </button>
      </div>
    </div> -->

  <div class="nav-align-top mb-1">
    <ul class="nav nav-pills mb-1" role="tablist">
      <!-- <li class="nav-item">
        <button type="button" class="nav-link" role="tab" data-bs-toggle="tab"
          data-bs-target="#navs-pills-top-home" aria-controls="navs-pills-top-home" aria-selected="true">
          TO UPDATE
        </button>
      </li> -->
      <!-- <li class="nav-item">
        <button type="button" class="nav-link active" role="tab" data-bs-toggle="tab"
            data-bs-target="#navs-pills-top-profile" aria-controls="navs-pills-top-profile" aria-selected="false">
            <i class="bx bx-refresh bx-sm me-1_5"></i>UPDATED
        </button>
      </li>
      <li class="nav-item">
        <button type="button" class="nav-link" role="tab" data-bs-toggle="tab"
          data-bs-target="#navs-pills-top-messages" aria-controls="navs-pills-top-messages" aria-selected="false">
          <i class="bx bx-buildings bx-sm me-1_5"></i>COMPANIES BY SECTORS
        </button>
      </li> -->
    </ul>

    <div class="tab-content">
    <script src="{{ asset('js/kpiAchievement.js') }}"></script>

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


<!-- Bootstrap Bundle with Popper.js (for modal functionality) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- Feather Icons -->
<script src="https://unpkg.com/feather-icons"></script>

<script>
    feather.replace(); // untuk aktifkan feather icons
</script>

<!-- Updated Tab Content -->
 <div class="card-body pt-1">
  <!-- Search Filter Section -->
  <!-- <div id="searchFilterCard" class="card-body pt-1 d-none"> -->
<!-- <div class="card-body pt-1 d-none"> -->
  <form id="formAccountSettings" method="POST" action="{{route('kpiAchievement.updated.search')}}">
      {!! csrf_field() !!}
      <div class="row g-3">

            <div class="col-md-4">
              <label class="form-label" for="year">Year</label>
              <select id="year" name="year" class="select2 form-select">
                <option value="">Please select</option>
                <option value="2018">2018</option>
                <option value="2019">2019</option>
                <option value="2020">2020</option>
                <option value="2021">2021</option>
                <option value="2022">2022</option>
                <option value="2023">2023</option>
                <option value="2024">2024</option>
                <option value="2025">2025</option>
              </select>
            </div>

            <div class="col-md-4">
              <label class="form-label" for="division">Division</label>
              <select id="division" name="division" class="select2 form-select">
                <option value=""> Please select </option>
                <option value="division1">CEO's Office</option>
                <option value="division2">Export Promotion & Market Access</option>
                <option value="division3">Management Services</option>
                <option value="division4">Strategic Planning</option>
                <option value="division5">Transformation and Digital Trade Division</option>
              </select>
            </div>

            <div class="col-md-4">
              <label class="form-label" for="section">Section</label>
              <select id="section" name="section" class="select2 form-select">
                <option value=""> Please select </option>
                <option value="section1">ASEAN & Oceania</option>
                <option value="section2">Central, West, South Asia & Africa Section</option>
                <option value="section3">China & Northeast Asia</option>
                <option value="section4">Construction & Business Services</option>
                <option value="section5">Coordination & Monitoring</option>
                <option value="section6">Corporate Management</option>
                <option value="section7">Customised Programme</option>
                <option value="section8">Development Assistance</option>
                <option value="section9">Digital Trade</option>
                <option value="section10">Electrical & Electronics, ICT, Machinery & Equipment</option>
                <option value="section11">Europe & Americas</option>
                <option value="section12">Export Academy</option>
                <option value="section13">Facility Management</option>
                <option value="section14">Finance Management</option>
                <option value="section15">Halal, Food & Beverages & Agro-based</option>
                <option value="section16">Human Resource</option>
                <option value="section17">Information Technology</option>
                <option value="section18">Lifestyle & Life Sciences</option>
                <option value="section19">N/A</option>
                <option value="section20">Oil & Gas, Chemical & Energy</option>
                <option value="section21">Research</option>
                <option value="section22">Strategic Communication</option>
                <option value="section23">Strategic Development</option>
                <option value="section24">Transport & Logistic</option>
              </select>
            </div>

            <div class="col-md-4">
              <label class="form-label" for="unit">Unit/Office</label>
              <select id="unit" name="unit" class="select2 form-select">
                  <option value="">Please select</option>
                  <?php
                  // Define units as key-value pairs
                  $units = [
                      '' => 'Please select',
                      'account' => 'Account',
                      'administration' => 'Administration',
                      'application_system_management_unit' => 'Application System Management Unit',
                      'asset_management' => 'Asset Management',
                      'business_information_centre' => 'Business Information Centre (BIC)',
                      'competency_talent_development' => 'Competency & Talent Development',
                      'corporate_communication' => 'Corporate Communication',
                      'digital_services' => 'Digital Services',
                      'ecommerce_ecosystem' => 'eCommerce Ecosystem',
                      'exporters_advisory_training' => 'Exporters Advisory & Training (EATU)',
                      'facility_management' => 'Facility Management',
                      'finance' => 'Finance',
                      'human_resource_management' => 'Human Resource Management',
                      'ict_operation_support' => 'ICT Operation & Support',
                      'integrity' => 'Integrity',
                      'internal_audit' => 'Internal Audit',
                      'international_collaboration' => 'International Collaboration',
                      'johor' => 'Johor',
                      'market_development' => 'Market Development',
                      'msme' => 'Micro, Small and Medium Enterprises (MSME)',
                      'mid_tier' => 'Mid Tier',
                      'mo_budapest' => 'MO - BUDAPEST',
                      'mo_buenos_aires' => 'MO - BUENOS AIRES',
                      'mo_doha' => 'MO - DOHA',
                      'mo_hanoi' => 'MO - HANOI',
                      'mo_karachi' => 'MO - KARACHI',
                      'mo_kiev' => 'MO - KIEV',
                      'mo_medan' => 'MO - MEDAN',
                      'mo_nairobi' => 'MO - NAIROBI',
                      'mo_osaka' => 'MO - OSAKA',
                      'mo_phnom_penh' => 'MO - PHNOM PENH',
                      'mo_tashkent' => 'MO - TASHKENT',
                      'mytrade_digital' => 'MyTRADE Digital',
                      'na' => 'N/A',
                      'network_ict_security_unit' => 'Network & ICT Security Unit',
                      'organisational_planning_transformation' => 'Organisational Planning & Transformation',
                      'penang' => 'Penang',
                      'performance_monitoring' => 'Performance Monitoring',
                      'procurement' => 'Procurement',
                      'revenue_generation' => 'Revenue Generation',
                      'sabah' => 'Sabah',
                      'sarawak' => 'Sarawak',
                      'strategic_coordination' => 'Strategic Coordination',
                      'strategic_development' => 'Strategic Development',
                      'tc_almaty' => 'TC - ALMATY',
                      'tc_bangkok' => 'TC - BANGKOK',
                      'tc_beijing' => 'TC - BEIJING',
                      'tc_cairo' => 'TC - CAIRO',
                      'tc_chengdu' => 'TC - CHENGDU',
                      'tc_chennai' => 'TC - CHENNAI',
                      'tc_dubai' => 'TC - DUBAI',
                      'tc_frankfurt' => 'TC - FRANKFURT',
                      'tc_guangzhou' => 'TC - GUANGZHOU',
                      'tc_ho_chi_minh_city' => 'TC - HO CHI MINH CITY',
                      'tc_hong_kong' => 'TC - HONG KONG',
                      'tc_istanbul' => 'TC - ISTANBUL',
                      'tc_jakarta' => 'TC - JAKARTA',
                      'tc_jeddah' => 'TC - JEDDAH',
                      'tc_johannesburg' => 'TC - JOHANNESBURG',
                      'tc_lagos' => 'TC - LAGOS',
                      'tc_london' => 'TC - LONDON',
                      'tc_los_angeles' => 'TC - LOS ANGELES',
                      'tc_manila' => 'TC - MANILA',
                      'tc_melbourne' => 'TC - MELBOURNE',
                      'tc_mexico_city' => 'TC - MEXICO CITY',
                      'tc_miami' => 'TC - MIAMI',
                      'tc_milan' => 'TC - MILAN',
                      'tc_moscow' => 'TC - MOSCOW',
                      'tc_mumbai' => 'TC - MUMBAI',
                      'tc_new_york' => 'TC - NEW YORK',
                      'tc_paris' => 'TC - PARIS',
                      'tc_rotterdam' => 'TC - ROTTERDAM',
                      'tc_santiago' => 'TC - SANTIAGO',
                      'tc_sao_paulo' => 'TC - SAO PAULO',
                      'tc_seoul' => 'TC - SEOUL',
                      'tc_shanghai' => 'TC - SHANGHAI',
                      'tc_singapore' => 'TC - SINGAPORE',
                      'tc_taipei' => 'TC - TAIPEI',
                      'tc_tokyo' => 'TC - TOKYO',
                      'tc_warsaw' => 'TC - WARSAW',
                      'tc_yangon' => 'TC - YANGON',
                      'terengganu' => 'Terengganu',
                      'trade_analysis' => 'Trade Analysis',
                      'trade_publication' => 'Trade Publication',
                      'trade_statistic' => 'Trade Statistic'
                  ];
                  
                  // Generate options from the array
                  foreach ($units as $value => $label) {
                      if ($value === '') {
                          echo "<option value=\"$value\">$label</option>";
                      } else {
                          echo "<option value=\"$value\">$label</option>";
                      }
                  }
                  ?>
              </select>
            </div>

            <div class="col-md-4">
              <label class="form-label" for="indicator_type">Indicator Type</label>
              <select id="indicator_type" name="indicator_type" class="select2 form-select">
                <option value=""> Please select </option>
                @foreach ($achievementTypeList as $item)
                  <option value="{{ $item->kpi_indicator_type_id }}">
                    {{ formatType($item->indicator_type) }}
                  </option>
                @endforeach
              </select>
            </div>

            <!-- drop down form category nak hide -->
            <!-- <div class="col-md-4">
              <label class="form-label" for="category">Category</label>
              <select id="category" name="category" class="select2 form-select">
                <option value="">-- Please select --</option>
                <option value="category1">Customer</option>
                <option value="category2">Finance</option>
                <option value="category3">People</option>
                <option value="category4">Process</option>
              </select>
            </div> -->

            <div class="col-md-4">
              <label class="form-label" for="status">Status</label>
              <select id="status" name="status" class="select2 form-select">
                <option value=""> Please select </option>
                <option value="all">All</option>
                <option value="new">New</option>
                <option value="draft">Draft</option>
                <option value="submitted">Submitted</option>
                <option value="endorsed">Endorsed</option>
                <option value="accepted">Accepted</option>
                <option value="ammendment_required">Ammendment Required</option>
                <option value="verified">Verified</option>
                <option value="rejected">Rejected</option>
              </select>
            </div>

            <div class="col-md-4">
              <label for="indicator" class="form-label">Indicator</label>
              <select id="indicator" name="indicator" class="select2 form-select">
                <option value="">Please select</option>
                <option value="Programme">Programme</option>
                <option value="Export Sales">Export Sales</option>
                <option value="Companies Assisted">Companies Assisted</option>
              </select>
            </div>

            <div class="col-md-4">
              <label for="achievement" class="form-label">Achievement</label>
              <!-- <select id="achievement" name="achievement" class="select2 form-select">
                <option value=""> Please select </option>
              </select> -->
              <input class="form-control" name="achievement" placeholder="Search by achievement" type="text">
            </div>

            <div class="col-md-4">
            <div class="mt-6 d-flex">
              <button type="submit" class="btn btn-primary me-2">Search</button>
              <button type="reset" class="btn btn-secondary">Reset</button>
            </div>
            </div>
          </div>


      <!-- <div class="mt-6 d-flex justify-content-end">
        <button type="submit" class="btn btn-primary me-3">Search</button>
        <button type="reset" class="btn btn-outline-secondary">Reset</button>
      </div> -->
    </form>
    <br><br>
    </div>
<!-- </div> -->


    <div class="d-flex justify-content-end align-items-center gap-2 mb-3">
        <!-- Choose Column Button -->
    <button type="button" class="btn btn-primary btn-sm text-white" data-bs-toggle="modal" data-bs-target="#columnModal">
    <i class="bx bx-columns me-1"></i>
    Modify Column
</button>

      <!-- Sync Button -->
     <button type="button" class="btn btn-success btn-sm text-white" data-bs-toggle="modal" data-bs-target="#">
        <i data-feather="refresh-ccw" class="me-1"></i>
        Sync
      </button>

    <a href="/export/print" class="btn btn-info btn-sm text-white">
        <i data-feather="printer" class="me-1"></i> Print
      </a>
      <div class="dropdown">
       <button class="btn btn-danger btn-sm text-white dropdown-toggle" type="button" id="exportDropdown" data-bs-toggle="dropdown" aria-expanded="false">
          <i data-feather="download" class="me-1"></i> Export
        </button>
        <ul class="dropdown-menu shadow" aria-labelledby="exportDropdown">
          <li><a class="dropdown-item" href="/export/excel"><i data-feather="file" class="me-2"></i>Excel</a></li>
          <li><a class="dropdown-item" href="/export/pdf"><i data-feather="file-minus" class="me-2"></i>Pdf</a></li>
          <li><a class="dropdown-item" href="/export/word"><i data-feather="file-text" class="me-2"></i>Word</a></li>
          <li><a class="dropdown-item" href="/export/jpg"><i data-feather="copy" class="me-2"></i>Jpg</a></li>
        </ul>
      </div>
    </div>

    <script>feather.replace();</script>

    <form method="GET" action="{{ url()->current() }}" class="d-flex align-items-center gap-2 mb-3">
      <label for="perPage" class="form-label mb-0">Show</label>
      <select name="perPage" id="perPage" class="form-select w-auto" onchange="this.form.submit()">
        @php
          $options = [10, 25, 50, 100, 'all'];
          $selectedPerPage = request('perPage', 10);
        @endphp
        @foreach ($options as $option)
          <option value="{{ $option }}" {{ (string)$selectedPerPage === (string)$option ? 'selected' : '' }}>{{ ucfirst($option) }}</option>
        @endforeach
      </select>
      <span>Entries</span>
    </form>

    <!-- Responsive Table -->
    <!-- Modal -->
    <div class="modal fade" id="columnModal" tabindex="-1" aria-labelledby="columnModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="columnModalLabel">Modify Column - List of Achievement Columns</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body row">
            <p>Select columns to display:</p>

            <!-- KIRI -->
            <div class="col-md-6">
              <div class="form-check">
                <input class="form-check-input column-toggle" type="checkbox" data-column="no" checked disabled>
                <label class="form-check-label">No</label>
              </div>
              <div class="form-check">
                <input class="form-check-input column-toggle" type="checkbox" data-column="year" checked>
                <label class="form-check-label">Year</label>
              </div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="division" checked><label class="form-check-label">Division</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="section" checked><label class="form-check-label">Section</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="unit" checked><label class="form-check-label">Unit/Office</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="indicator" checked><label class="form-check-label">Indicator</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="description"><label class="form-check-label">Description</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="submission"><label class="form-check-label">Submission</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="target" checked><label class="form-check-label">Annual Target</label></div>
            </div>

            <!-- KANAN -->
            <div class="col-md-6">
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="metric" checked><label class="form-check-label">Metric</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="category"><label class="form-check-label">Category</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="output"><label class="form-check-label">Output/Outcome</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="type" checked><label class="form-check-label">Indicator Type</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="type_def"><label class="form-check-label">Indicator Type Definition</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="achievement"><label class="form-check-label">Component Achievement</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="status" checked><label class="form-check-label">Status</label></div>
              <div class="form-check"><input class="form-check-input column-toggle" type="checkbox" data-column="action" checked disabled><label class="form-check-label">Action</label></div>
            </div>
          </div>

          <!-- BUTTONS KANAN -->
          <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>

          <div class="table-responsive text-nowrap">
            <table id="indicatorTable" class="table table-bordered align-middle">
              <thead class="table-light text-center">
                <tr class="text-nowrap">
                  <th style="width: 40px;"><input type="checkbox" id="checkAll"></th>
        <th style="width: 50px;" class="sortable-header" onclick="sortTable('indicatorTable', 1, 'number')">
          No <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="width: 80px;" class="sortable-header" onclick="sortTable('indicatorTable', 2, 'number')">
          Year <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 150px;" class="sortable-header" onclick="sortTable('indicatorTable', 3, 'text')">
          Division <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 150px;" class="sortable-header" onclick="sortTable('indicatorTable', 4, 'text')">
          Section <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 150px;" class="sortable-header" onclick="sortTable('indicatorTable', 5, 'text')">
          Unit/Office <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 200px;" class="sortable-header" onclick="sortTable('indicatorTable', 6, 'text')">
          Indicator <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 120px;" class="sortable-header" onclick="sortTable('indicatorTable', 7, 'number')">
          Annual Target <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 120px;" class="sortable-header" onclick="sortTable('indicatorTable', 8, 'text')">
          Metric <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 130px;" class="sortable-header" onclick="sortTable('indicatorTable', 9, 'text')">
          Indicator Type <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 100px;" class="sortable-header" onclick="sortTable('indicatorTable', 10, 'text')">
          Status <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="width: 90px;">Action</th>



                </tr>
              </thead>

              <tbody class="table-border-bottom-0">
                @foreach($kpiAchievements as $kpiAchievement)
                  <?php $kpiAchievement->no = $loop->iteration; ?>
                  @include('content.indicator-types-table.employee-kpi-achievement-table',['kpiAchievement'=>$kpiAchievement])
                @endforeach
              </tbody>
            </table>
          </div>


    <!-- Footer Table -->
    <div class="d-flex justify-content-between align-items-center mt-3 flex-wrap gap-2">
      <div>Showing 1 to 1 of 1 Entries</div>
      <nav aria-label="Page navigation">
        <ul class="pagination mb-0">
          <li class="page-item first">
            <a class="page-link" href="#"><i class="tf-icon bx bx-chevrons-left bx-sm"></i></a>
          </li>
          <li class="page-item prev">
            <a class="page-link" href="#"><i class="tf-icon bx bx-chevron-left bx-sm"></i></a>
          </li>
          <li class="page-item">
            <a class="page-link" href="#">1</a>
          </li>
          <li class="page-item">
            <a class="page-link" href="#">2</a>
          </li>
          <li class="page-item next">
            <a class="page-link" href="#"><i class="tf-icon bx bx-chevron-right bx-sm"></i></a>
          </li>
          <li class="page-item last">
            <a class="page-link" href="#"><i class="tf-icon bx bx-chevrons-right bx-sm"></i></a>
          </li>
        </ul>
      </nav>
    </div>

    <br><br>

    <div class="d-flex justify-content-end gap-2">
        <!-- Submit Button -->
        <button type="button" class="btn btn-primary" id="saveCompaniesBtn">Submit</button>

        <!-- Verify Button -->
        <button type="button" class="btn btn-primary" id="verifyCompaniesBtn">Verify</button>
    </div>


</div>

<script>
let sortDirections = {};

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 (skip first row with checkbox)
    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
        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') {
            aValue = parseFloat(aValue.replace(/,/g, '')) || 0;
            bValue = parseFloat(bValue.replace(/,/g, '')) || 0;
            return newDirection === 'asc' ? aValue - bValue : bValue - aValue;
        } else {
            aValue = aValue.toLowerCase();
            bValue = bValue.toLowerCase();
            return newDirection === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
        }
    });

    // Clear tbody and re-append sorted rows
    tbody.innerHTML = '';
    rows.forEach(row => tbody.appendChild(row));

    // Visual feedback
    header.style.backgroundColor = '#e3f2fd';
    setTimeout(() => {
        header.style.backgroundColor = '';
    }, 300);
}
</script>

<script>
let sortDirections = {};

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 (skip first row with checkbox)
    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
        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') {
            aValue = parseFloat(aValue.replace(/,/g, '')) || 0;
            bValue = parseFloat(bValue.replace(/,/g, '')) || 0;
            return newDirection === 'asc' ? aValue - bValue : bValue - aValue;
        } else {
            aValue = aValue.toLowerCase();
            bValue = bValue.toLowerCase();
            return newDirection === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
        }
    });

    // Clear tbody and re-append sorted rows
    tbody.innerHTML = '';
    rows.forEach(row => tbody.appendChild(row));

    // Visual feedback
    header.style.backgroundColor = '#e3f2fd';
    setTimeout(() => {
        header.style.backgroundColor = '';
    }, 300);
}
</script>

@endsection

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

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

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

    const modal = bootstrap.Modal.getInstance(document.getElementById('columnModal'));
    modal.hide();
  }
</script>
