<!-- 2. Add CSS for sortable columns -->
<style>
  .sortable-header {
    cursor: pointer;
    user-select: none;
    transition: background-color 0.2s;
  }

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

  .sort-icon {
    margin-left: 5px;
    font-size: 0.8em;
    opacity: 0.6;
  }

  /* Add active state styling */
  .sortable-header[data-sort-direction="asc"] .sort-icon,
  .sortable-header[data-sort-direction="desc"] .sort-icon {
    opacity: 1;
    color: #0d6efd;
  }

  .sortable-header[data-sort-direction="asc"] {
    background-color: #f8f9fa;
  }

  .sortable-header[data-sort-direction="desc"] {
    background-color: #f8f9fa;
  }
</style>
<!-- Next Year Indicator -->
<button class="btn btn-outline-primary w-100 d-flex justify-content-between align-items-center" id="toggleTableBtn">
  <span>Next Year Indicator List</span>
  <i class="tf-icon bx bx-chevron-right bx-sm"></i>
</button><br>

<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); // default to 10
    @endphp
    @foreach ($options as $option)
    <option value="{{ $option }}" {{ (string)$selectedPerPage === (string)$option ? 'selected' : '' }}>
      {{ ucfirst($option) }}
    </option>
    @endforeach
  </select>
  <span>Entries</span>
</form>

<div class="table-responsive">
  <table id="indicatorTable" class="table table-bordered align-middle table-hover shadow-sm rounded">
    <thead class="table-light">
      <tr class="text-nowrap text-uppercase text-secondary fw-bold small text-center">
        <th class="checkbox-cell">
          <input type="checkbox" id="checkAll" class="form-check-input">
        </th>
        <th style="min-width: 40px;" class="sortable-header" onclick="sortTable('indicatorTable', 1, 'number')">
          No <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 70px;" class="sortable-header" onclick="sortTable('indicatorTable', 2, 'number')">
          Year <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 180px;" class="sortable-header" onclick="sortTable('indicatorTable', 3, 'text')">
          Division <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 180px;" 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: 280px;" class="sortable-header" onclick="sortTable('indicatorTable', 7, 'text')">
          Description <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 120px;" class="sortable-header" onclick="sortTable('indicatorTable', 8, 'text')">
          Submission <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 120px;" class="sortable-header" onclick="sortTable('indicatorTable', 9, 'number')">
          Annual Target <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 100px;" class="sortable-header" onclick="sortTable('indicatorTable', 10, 'text')">
          Metric <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 140px;" class="sortable-header" onclick="sortTable('indicatorTable', 11, 'text')">
          Category <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 120px;" class="sortable-header" onclick="sortTable('indicatorTable', 12, 'text')">
          Output/Outcome <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 140px;" class="sortable-header" onclick="sortTable('indicatorTable', 13, 'text')">
          Indicator Type <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 280px;" class="sortable-header" onclick="sortTable('indicatorTable', 14, 'text')">
          Indicator Type Definition <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 140px;" class="sortable-header" onclick="sortTable('indicatorTable', 15, 'text')">
          Component Achievement <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th style="min-width: 100px;" class="sortable-header" onclick="sortTable('indicatorTable', 16, 'text')">
          Status <i class="bi bi-arrow-down-up sort-icon"></i>
        </th>
        <th class="action-cell text-center">Action</th>
      </tr>
    </thead>
    <tbody class="text-start">
      <form id="indicatorSubmit" method="POST" action="{{ route('indicators.submit') }}">
         {!! csrf_field() !!}
        @foreach ($indicator_list_draft as $key => $field)
          <tr>
            <td class="text-center">
              {{-- <input type="hidden" name="indicator_id[]" value="{{ $field->no }}">
              <input type="hidden" name="source[]" value="{{ $field->source }}"> --}}
              <input type="checkbox" name="selected[]" value="{{$field->indicator_id.'__1'}}" class="row-checkbox">
            </td>
            <td class="text-center">{{ $key+1 }}</td>
            <td class="text-center">{{ $field->year }}</td>
            <td>{{ formatDivision($field->division) }}</td>
            <td>{{ formatDivision($field->section) }}</td>
            <td>{{ formatDivision($field->unit) }}</td>
            <td>{{ $field->indicator }}</td>
            <td>{{ $field->description }}</td>
            <td class="text-center">{{ formatSubmission($field->submission) }}</td>
            <td class="text-center">{{ $field->annual_target }}</td>
            <td class="text-center">{{ formatMetric($field->metric) }}</td>
            <td>{{ formatCategory($field->category) }}</td>
            <td>{{ formatOutputOutcome($field->output_outcome) }}</td>
            <td>
                @foreach ($indicator_type_list as $item)
                    @if ($item->kpi_indicator_type_id == $field->kpi_indicator_type_id)
                        {{ formatType($item->indicator_type) }}
                    @endif
                @endforeach
            </td>
            <td>{{ $field->indicator_type_def }}</td>
            <td class="text-center">{{ formatComponentAchv($field->component_achv) }}</td>
            <td class="text-center">{{ ucwords($field->status) }}</td>
            <td class="text-center align-middle">
              <div class="d-flex justify-content-center gap-2">
                <!-- Edit -->
                <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" 
                    data-bs-target="#editModal" title="Edit"
                    data-indicator_id="{{ $field->indicator_id }}"
                    data-year="{{ $field->year }}"
                    data-division="{{ $field->division }}"
                    data-section="{{ $field->section }}"
                    data-unit="{{ $field->unit }}"
                    data-indicator="{{ $field->indicator }}"
                    data-description="{{ $field->description }}"
                    data-annual_target="{{ $field->annual_target }}"
                    data-metric="{{ $field->metric }}"
                    data-category="{{ $field->category }}"
                    data-output_outcome="{{ $field->output_outcome }}"
                    data-kpi_indicator_type_id="{{ $field->indicator_type }}"
                    data-indicator_type_def="{{ $field->indicator_type_def }}"
                    data-component_achievement="{{ $field->component_achv }}"
                    data-status="{{ $field->status }}"
                    data-kpi_achievement_id="{{ $field->kpi_achievement_id }}"
                    >
                  <i class="bx bx-edit-alt"></i>
                </button>

                <!-- Delete -->
                <button type="button" class="btn btn-sm btn-danger" title="Delete">
                  <i class="bx bx-trash"></i>
                </button>
              </div>
            </td>
          </tr>
        @endforeach
    </tbody>
  </table>
</div>


{{-- Follwing code is not needed  --}}
      {{-- </tr> --}}
      <!-- Tambah baris lagi ikut data -->
      {{-- <tr>
        <td class="text-center">
          <input type="checkbox" name="selected[]" value="2" class="row-checkbox">
        </td>
        <td class="text-center">2</td>
        <td class="text-center">2025</td>
        <td>Management Services</td>
        <td>Finance Management</td>
        <td>Account</td>
        <td>Annual Financial Statement Report</td>
        <td>
          Certificate on the Audit of the Financial Statements <br>
          after submission of Annual Financial Statement Report <br>
          to National Audit Department by 30th June
        </td>
        <td class="text-center">Quarterly</td>
        <td class="text-center">1</td>
        <td class="text-center">Report</td>
        <td>Process</td>
        <td>Output</td>
        <td>Type 1</td>
        <td>KPI data is manually added in the achivement count field</td>
        <td class="text-center">N/A</td>
        <td class="text-center">Draft</td>
        <td class="text-center align-middle">
          <div class="d-flex justify-content-center gap-2">
            <!-- Edit -->
            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#editModal" title="Edit">
              <i class="bx bx-edit-alt"></i>
            </button>

            <!-- Delete -->
            <button type="button" class="btn btn-sm btn-danger" title="Delete">
              <i class="bx bx-trash"></i>
            </button>
          </div> --}}

          {{-- <!-- Modal -->
          <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="editModalLabel">Edit Indicator</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                </div>
                <div class="modal-body">
                  <form id="updateForm">
                    <div class="row">
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Year</label>
                        <input type="text" class="form-control" name="year" value="2025">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Division</label>
                        <input type="text" class="form-control" name="division" value="Management Services">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Section</label>
                        <input type="text" class="form-control" name="section" value="Finance Management">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Unit</label>
                        <input type="text" class="form-control" name="unit" value="Account">
                      </div>
                      <div class="col-md-12 mb-3">
                        <label class="form-label">Indicator</label>
                        <input type="text" class="form-control" name="indicator" value="Annual Financial Statement Report">
                      </div>
                      <div class="col-md-12 mb-3">
                        <label class="form-label">Indicator Description</label>
                        <textarea class="form-control" name="description" rows="3">Certificate on the Audit of the Financial Statements after submission of Annual Financial Statement Report to National Audit Department by 30th June</textarea>
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Submission</label>
                        <input type="text" class="form-control" name="submission" value="Quarterly">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Annual Target</label>
                        <input type="text" class="form-control" name="target" value="1">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Metric</label>
                        <input type="text" class="form-control" name="metric" value="Report">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Category</label>
                        <input type="text" class="form-control" name="category" value="Process">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Output/Outcome</label>
                        <input type="text" class="form-control" name="output" value="Output">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Indicator Type</label>
                        <input type="text" class="form-control" name="indicator_type" value="Type 1">
                      </div>
                      <div class="col-md-12 mb-3">
                        <label class="form-label">Indicator Type Definition</label>
                        <textarea class="form-control" name="type_definition" rows="2">KPI data is manually added in the achivement count field</textarea>
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Component Achievement</label>
                        <input type="text" class="form-control" name="component_achievement" value="N/A">
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status">
                          <option value="">-- Select Type --</option>
                          <option value="draft" selected>Draft</option>
                          <option value="endorsed">Endorsed</option>
                          <option value="pending">Pending Endorsed</option>
                          <option value="proposed">Proposed</option>
                          <option value="rejected">Rejected</option>
                        </select>
                      </div>
                    </div>
                  </form>
                </div>

                <div class="modal-footer">
                  <!-- Butang Save dengan margin kanan -->
                  <button type="submit" class="btn btn-primary me-4" form="updateForm">Save</button>
                  <button type="button" class="btn btn-secondary" id="backButton">Back</button>
                </div>

              </div>
            </div>
          </div> --}}

        {{-- </td>
      </tr> --}}
    {{-- </tbody>
  </table>

</div> --}}

<!-- Table Footer with Inline Layout -->
<div class="d-flex justify-content-between align-items-center mt-3 flex-wrap gap-2">
  <!-- Entries Info -->
  <div>Showing 1 to 1 of 1 Entries</div>

  <!-- Pagination -->
  <nav aria-label="Page navigation">
    <ul class="pagination mb-0">
      <li class="page-item first">
        <a class="page-link" href="javascript:void(0);">
          <i class="tf-icon bx bx-chevrons-left bx-sm"></i>
        </a>
      </li>
      <li class="page-item prev">
        <a class="page-link" href="javascript:void(0);">
          <i class="tf-icon bx bx-chevron-left bx-sm"></i>
        </a>
      </li>
      <li class="page-item">
        <a class="page-link" href="javascript:void(0);">1</a>
      </li>
      <li class="page-item">
        <a class="page-link" href="javascript:void(0);">2</a>
      </li>
      <li class="page-item next">
        <a class="page-link" href="javascript:void(0);">
          <i class="tf-icon bx bx-chevron-right bx-sm"></i>
        </a>
      </li>
      <li class="page-item last">
        <a class="page-link" href="javascript:void(0);">
          <i class="tf-icon bx bx-chevrons-right bx-sm"></i>
        </a>
      </li>
    </ul>
  </nav>

  <div class="container">
    <div class="row">
      <div class="col-12"><br>
        <div class="d-flex justify-content-end gap-2">
          <button type="submit" class="btn btn-primary">Submit</button>
          <button type="button" class="btn btn-primary">Save</button>
        </div>
      </form>
        @include('newIndicator.edit-indicator-modal')
        @include('newIndicator.new-indicator-modal')
        
      </div>
    </div>

    <script>
      document.addEventListener('DOMContentLoaded', function() {
        const table = document.getElementById('indicatorTable');
        const tbody = table.querySelector('tbody');
        const sortableHeaders = table.querySelectorAll('.sortable');

        let currentSort = {
          column: null,
          direction: 'asc'
        };

        sortableHeaders.forEach(header => {
          header.addEventListener('click', function() {
            const column = this.dataset.column;

            // Remove active class from all headers
            sortableHeaders.forEach(h => {
              h.classList.remove('active', 'asc', 'desc');
            });

            // Determine sort direction
            if (currentSort.column === column) {
              currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            } else {
              currentSort.direction = 'asc';
            }

            currentSort.column = column;

            // Add active class and direction to current header
            this.classList.add('active', currentSort.direction);

            // Sort the table
            sortTable(column, currentSort.direction);
          });
        });

        function sortTable(column, direction) {
          const rows = Array.from(tbody.querySelectorAll('tr'));

          // Get column index based on data-column attribute
          const columnIndex = getColumnIndex(column);

          rows.sort((a, b) => {
            let aValue = a.cells[columnIndex].textContent.trim();
            let bValue = b.cells[columnIndex].textContent.trim();

            // Handle numeric values
            if (column === 'target' || column === 'year') {
              aValue = parseFloat(aValue) || 0;
              bValue = parseFloat(bValue) || 0;
            } else {
              // Convert to lowercase for case-insensitive sorting
              aValue = aValue.toLowerCase();
              bValue = bValue.toLowerCase();
            }

            if (direction === 'asc') {
              return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
            } else {
              return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
            }
          });

          // Reorder rows in the table
          rows.forEach(row => tbody.appendChild(row));

          // Update row numbers
          updateRowNumbers();
        }

        function getColumnIndex(column) {
          const columnMap = {
            'year': 2,
            'division': 3,
            'section': 4,
            'unit': 5,
            'indicator': 6,
            'description': 7,
            'submission': 8,
            'target': 9,
            'metric': 10,
            'category': 11,
            'output': 12,
            'type': 13,
            'definition': 14,
            'achievement': 15,
            'status': 16
          };

          return columnMap[column] || 0;
        }

        function updateRowNumbers() {
          const rows = tbody.querySelectorAll('tr');
          rows.forEach((row, index) => {
            row.cells[1].textContent = index + 1; // Update the "No" column
          });
        }
      });
    </script>