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

<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;
}
</style>
<div>
<!-- Previous Year Indicator -->
<button class="btn btn-outline-primary w-100 d-flex justify-content-between align-items-center" id="toggleTableBtn">
        <span>Previous Year Indicator List</span>
        <i class="tf-icon bx bx-chevron-right bx-sm"></i>
      </button>
    </div>

    <!-- Responsive Table -->
    <div id="tableContainer" style="display: none;">
      Year:
      <div class="btn-group">
        <button type="button" class="btn btn-outline-primary" id="selectedYear">
          {{ request('year_select', now()->year - 1) }}
        </button>
        <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
          <span class="visually-hidden">Toggle Dropdown</span>
        </button>
        <ul class="dropdown-menu">
          @php
            $currentYear = now()->year;
            $years = range(2018, $currentYear - 1);
            $selectedYear = request('year_select', $currentYear - 1);
          @endphp
          @foreach($years as $year)
            <li>
              <a class="dropdown-item year-option {{ $selectedYear == $year ? 'active' : '' }}" href="javascript:void(0);" data-year="{{ $year }}">
                {{ $year }}
              </a>
            </li>
          @endforeach
        </ul>
        <form method="GET" action="{{ url()->current() }}" id="previousIndicatorListForm">
          <input type="hidden" name="year_select" id="year_select" value="{{ $selectedYear }}">
        </form>
      </div>
      <br><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-uppercase text-secondary fw-bold small text-center">
                <th style="width: 40px;">
                  <input type="checkbox" id="checkAll">
                </th>
                <th style="min-width: 180px;" class="sortable-header" onclick="sortTable('indicatorTable', 1, 'text')">
                                Division
                                <i class="bi bi-arrow-down-up sort-icon"></i>
                            </th>
                            <th style="min-width: 180px;" class="sortable-header" onclick="sortTable('indicatorTable', 2, 'text')">
                                Section
                                <i class="bi bi-arrow-down-up sort-icon"></i>
                            </th>
                            <th style="min-width: 150px;" class="sortable-header" onclick="sortTable('indicatorTable', 3, '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', 4, 'text')">
                                Indicator
                                <i class="bi bi-arrow-down-up sort-icon"></i>
                            </th>
                            <th style="min-width: 280px;" class="sortable-header" onclick="sortTable('indicatorTable', 5, 'text')">
                                Description
                                <i class="bi bi-arrow-down-up sort-icon"></i>
                            </th>
                            <th style="min-width: 120px;" class="sortable-header" onclick="sortTable('indicatorTable', 6, 'text')">
                                Submission
                                <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: 100px;" class="sortable-header" onclick="sortTable('indicatorTable', 8, 'text')">
                                Metric
                                <i class="bi bi-arrow-down-up sort-icon"></i>
                            </th>
                            <th style="min-width: 140px;" class="sortable-header" onclick="sortTable('indicatorTable', 9, 'text')">
                                Category
                                <i class="bi bi-arrow-down-up sort-icon"></i>
                            </th>
                            <th style="min-width: 120px;" class="sortable-header" onclick="sortTable('indicatorTable', 10, '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', 11, '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', 12, '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', 13, 'text')">
                                Component Achievement
                                <i class="bi bi-arrow-down-up sort-icon"></i>
                            </th>
              </tr>
            </thead>
            <tbody class="text-start">
              <form id="indicatorCopy" method="POST" action="{{ route('indicators.copy') }}">
                {!! csrf_field() !!}
              @foreach ($indicator_list_previous as $key => $field)
              <tr>
                <td class="text-center">
                  <input type="checkbox" name="selected[]" value="{{$field->indicator_id.'__1'}}" class="row-checkbox">
                </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>{{ formatSubmission($field->submission) }}</td>
                <td>{{ $field->annual_target }}</td>
                <td>{{ 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>
              </tr>
            @endforeach
                @if($indicator_list_previous->isEmpty())
                  <tr>
                    <td colspan="15" class="text-center">No records found.</td>
                  </tr>
                @endif
            </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>

      <!-- Trigger Modal -->
      <div class="mt-3">
        <button type="button" class="btn btn-primary me-3" data-bs-toggle="modal" data-bs-target="#copyConfirmModal">
          Copy
        </button>
      </div>

      <!-- Modal -->
      <div class="modal fade" id="copyConfirmModal" tabindex="-1" aria-labelledby="copyConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content text-center">
            <div class="modal-header">
              <h5 class="modal-title" id="copyConfirmModalLabel">Confirm Copy</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <!-- Icon di atas -->
              <div class="mb-3">
                <i class="bx bx-error-circle text-warning" style="font-size: 3rem;"></i>
              </div>
              <p class="fs-5 mb-0">Are you sure you want to copy?</p>
            </div>
            <div class="modal-footer justify-content-center border-0">
              <button type="submit" class="btn btn-primary" id="confirmCopyBtn">Yes</button>
              <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button> <p></p>
            </div>
          </div>
        </div>
      </div>
    </form>

      <!-- Success Modal -->
      <div class="modal fade" id="copySuccessModal" tabindex="-1" aria-labelledby="copySuccessModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content text-center">
            <div class="modal-body py-5">
              <div class="mb-3">
                <i class="bx bx-check-circle text-success" style="font-size: 3rem;"></i>
              </div>
              <h5 class="mb-3">Message Copied!</h5>
              <button type="button" class="btn btn-primary" id="successOkBtn">OK</button>
            </div>
          </div>
        </div>
      </div>

      <!-- Error Modal -->
      <div class="modal fade" id="copyErrorModal" tabindex="-1" aria-labelledby="copyErrorModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content text-center">
            <div class="modal-body py-5">
              <div class="mb-3">
                <i class="bx bx-x-circle text-danger" style="font-size: 3rem;"></i>
              </div>
              <h5 class="mb-2 text-danger">Error</h5>
              <p class="mb-3">Indicator <strong>Disposal of Assets and Stocks</strong> already existed!</p>
              <button type="button" class="btn btn-primary" id="errorOkBtn">OK</button>
            </div>
          </div>
        </div>
      </div>



      <!-- Account Deactivation Form -->
      <form id="formAccountDeactivation" onsubmit="return false">
        <div class="form-check my-4 ms-2">
          <!-- Optional deactivation checkbox (currently hidden) -->
        </div>
      </form>
    </div>
    
    <script>
    function sortTable(tableId, columnIndex, dataType) {
    const table = document.getElementById(tableId);
    const tbody = table.getElementsByTagName('tbody')[0];
    const rows = Array.from(tbody.getElementsByTagName('tr'));
    
    // Get current sort direction from the header
    const header = table.getElementsByTagName('th')[columnIndex];
    const currentDirection = header.getAttribute('data-sort-direction') || 'none';
    const newDirection = currentDirection === 'asc' ? 'desc' : 'asc';
    
    // Sort rows
    rows.sort((a, b) => {
        let aValue = a.cells[columnIndex].textContent.trim();
        let bValue = b.cells[columnIndex].textContent.trim();
        
        if (dataType === 'number') {
            aValue = parseFloat(aValue) || 0;
            bValue = parseFloat(bValue) || 0;
        } else {
            aValue = aValue.toLowerCase();
            bValue = bValue.toLowerCase();
        }
        
        if (newDirection === 'asc') {
            return aValue > bValue ? 1 : aValue < bValue ? -1 : 0;
        } else {
            return aValue < bValue ? 1 : aValue > bValue ? -1 : 0;
        }
    });
    
    // Clear tbody and append sorted rows
    tbody.innerHTML = '';
    rows.forEach(row => tbody.appendChild(row));
    
    // Update sort direction and icons
    updateSortIcons(table, columnIndex, newDirection);
}

function updateSortIcons(table, activeColumnIndex, direction) {
    const headers = table.querySelectorAll('.sortable-header');
    
    headers.forEach((header, index) => {
        const icon = header.querySelector('.sort-icon');
        header.removeAttribute('data-sort-direction');
        
        // Fix: account for the checkbox column - add 1 to index
        if (index + 1 === activeColumnIndex) {
            header.setAttribute('data-sort-direction', direction);
            icon.className = direction === 'asc' ? 'bi bi-arrow-up sort-icon' : 'bi bi-arrow-down sort-icon';
        } else {
            icon.className = 'bi bi-arrow-down-up sort-icon';
        }
    });
}
    </script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const toggleBtn = document.getElementById("toggleTableBtn");
    const tableContainer = document.getElementById("tableContainer");
    const icon = toggleBtn.querySelector("i");

    const yearOptions = document.querySelectorAll(".year-option");
    const selectedYearBtn = document.getElementById("selectedYear");
    const yearInput = document.getElementById("year_select");
    const yearForm = document.getElementById("previousIndicatorListForm");

    // Auto-open if year_select exists
    @if(request()->has('year_select'))
        tableContainer.style.display = "block";
        icon.classList.remove("bx-chevron-right");
        icon.classList.add("bx-chevron-down");
    @endif

    // Toggle table
    toggleBtn.addEventListener("click", function () {
        if (tableContainer.style.display === "none" || tableContainer.style.display === "") {
            tableContainer.style.display = "block";
            icon.classList.remove("bx-chevron-right");
            icon.classList.add("bx-chevron-down");
        } else {
            tableContainer.style.display = "none";
            icon.classList.remove("bx-chevron-down");
            icon.classList.add("bx-chevron-right");
        }
    });

    // Year selection
    yearOptions.forEach(option => {
        option.addEventListener("click", function () {
            const year = this.dataset.year;
            selectedYearBtn.textContent = year;
            yearInput.value = year;
            yearForm.submit();
        });
    });
});
</script>