@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" onsubmit="return false">
      <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>
                <option value="unit1">Account</option>
                <option value="unit2">Administration</option>
                <option value="unit3">Application System Management Unit</option>
                <option value="unit4">Asset Management</option>
                <option value="unit5">Business Information Centre (BIC)</option>
                <option value="unit6">Competency & Talent Development</option>
                <option value="unit7">Corporate Communication</option>
                <option value="unit8">Digital Services</option>
                <option value="unit9">eCommerce Ecosystem</option>
                <option value="unit10">Exporters Advisory & Training (EATU)</option>
                <option value="unit11">Facility Management</option>
                <option value="unit12">Finance</option>
                <option value="unit13">Human Resource Management</option>
                <option value="unit14">ICT Operation & Support</option>
                <option value="unit15">Integrity</option>
                <option value="unit16">Internal Audit</option>
                <option value="unit19">International Collaboration</option>
                <option value="unit20">Johor</option>
                <option value="unit21">Market Development</option>
                <option value="unit22">Micro, Small and Medium Enterprises (MSME)</option>
                <option value="unit23">Mid Tier</option>
                <option value="unit24">MO - BUDAPEST</option>
                <option value="unit25">MO - BUENOS AIRES</option>
                <option value="unit26">MO - DOHA</option>
                <option value="unit27">MO - HANOI</option>
                <option value="unit28">MO - KARACHI</option>
                <option value="unit29">MO - KIEV</option>
                <option value="unit30">MO - MEDAN</option>
                <option value="unit31">MO - NAIROBI</option>
                <option value="unit32">MO - OSAKA</option>
                <option value="unit33">MO - PHNOM PENH</option>
                <option value="unit34">MO - TASHKENT</option>
                <option value="unit35">MyTRADE Digital</option>
                <option value="unit36">N/A</option>
                <option value="unit37">Network & ICT Security Unit</option>
                <option value="unit38">Organisational Planning & Transformation</option>
                <option value="unit39">Penang</option>
                <option value="unit40">Perfomance Monitoring</option>
                <option value="unit41">Procurement</option>
                <option value="unit42">Revenue Generation</option>
                <option value="unit43">Sabah</option>
                <option value="unit44">Sarawak</option>
                <option value="unit45">Strategic Coordination</option>
                <option value="unit46">Strategic Development</option>
                <option value="unit47">TC - ALMATY</option>
                <option value="unit48">TC - BANGKOK</option>
                <option value="unit49">TC - BEIJING</option>
                <option value="unit50">TC - CAIRO</option>
                <option value="unit51">TC - CHENGDU</option>
                <option value="unit52">TC - CHENNAI</option>
                <option value="unit53">TC - DUBAI</option>
                <option value="unit54">TC - FRANKFURT</option>
                <option value="unit55">TC - GUANGZHOU</option>
                <option value="unit56">TC - HO CHI MINH CITY</option>
                <option value="unit57">TC - HONG KONG</option>
                <option value="unit58">TC - ISTANBUL</option>
                <option value="unit59">TC - JAKARTA</option>
                <option value="unit60">TC - JEDDAH</option>
                <option value="unit61">TC - JOHANNESBURG</option>
                <option value="unit62">TC - LAGOS</option>
                <option value="unit63">TC - LONDON</option>
                <option value="unit64">TC - LOS ANGELES</option>
                <option value="unit65">TC - MANILA</option>
                <option value="unit66">TC - MELBOURNE</option>
                <option value="unit67">TC - MEXICO CITY</option>
                <option value="unit68">TC - MIAMI</option>
                <option value="unit69">TC - MILAN</option>
                <option value="unit70">TC - MOSCOW</option>
                <option value="unit71">TC - MUMBAI</option>
                <option value="unit72">TC - NEW YORK</option>
                <option value="unit73">TC - PARIS</option>
                <option value="unit74">TC - ROTTERDAM</option>
                <option value="unit75">TC - SANTIAGO</option>
                <option value="unit76">TC - SAO PAULO</option>
                <option value="unit77">TC - SEOUL</option>
                <option value="unit78">TC - SHANGHAI</option>
                <option value="unit79">TC - SINGAPORE</option>
                <option value="unit80">TC - TAIPEI</option>
                <option value="unit81">TC - TOKYO</option>
                <option value="unit82">TC - WARSAW</option>
                <option value="unit83">TC - YANGON</option>
                <option value="unit84">Terengganu</option>
                <option value="unit85">Trade Ananlysis</option>
                <option value="unit86">Trade Publication</option>
                <option value="unit87">Trade Statistic</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>
                <option value="type1">Type 1</option>
                <option value="type2">Type 2</option>
                <option value="type3">Type 3</option>
                <option value="type4">Type 4</option>
                <option value="type5">Type 5</option>
                <option value="type6">Type 6</option>
              </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="Australia">Draft</option>
                <option value="Bangladesh">Endorsed</option>
                <option value="Belarus">Pending Endorsed</option>
                <option value="Australia">Proposed</option>
                <option value="Australia">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>
              </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>
            </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">
                @include('content.indicator-types-table.type-1')
                @include('content.indicator-types-table.type-2')
                @include('content.indicator-types-table.type-3')
                @include('content.indicator-types-table.type-4')
                @include('content.indicator-types-table.type-5')
                @include('content.indicator-types-table.type-6')
              </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>
