<?php
session_start();
require("../mainconfig.php");

if (isset($_SESSION['user'])) {
	$sess_username = $_SESSION['user']['username'];
	$check_user = mysqli_query($db, "SELECT * FROM users WHERE username = '$sess_username'");
	$data_user = mysqli_fetch_assoc($check_user);
	if (mysqli_num_rows($check_user) == 0) {
		header("Location: ".$cfg_baseurl."logout.php");
	} else if ($data_user['status'] == "Suspended") {
		header("Location: ".$cfg_baseurl."logout.php");
	}
}

include("../lib/header.php");
?>
<div class="page-body"> 
<?php include('../lib/partial/breadcrumb.php') ?>
   <!-- Container-fluid starts-->
   <div class="container-fluid">
      <div class="row size-column">
         <div class="col-xxl-10 col-md-12 box-col-8 grid-ed-12">
            <div class="row">
               <div class="col-xxl-12">
  <div class="card">
    <div class="card-body">
      <h4 class="card-title">Services</h4>
      <!-- Add the search input element -->
      <div class="input-group mb-3">
          <div class="col-12">
        <select id="category-filter" class="form-control">
          <option value="">All</option> <!-- This option is for showing all categories -->
          <?php
														$check_cat = mysqli_query($db, "SELECT * FROM service_cat ORDER BY name ASC");
														while ($data_cat = mysqli_fetch_assoc($check_cat)) {
														?>
														<option value="<?php echo $data_cat['code']; ?>"><?php echo $data_cat['name']; ?></option>
														<?php
														}
														?>
          <!-- Add more options for other categories -->
        </select>
        </div>
        <div class="col-12">
            <br>
          </div>
          <div class="col-12">
          <input type="text" id="search-input" class="form-control" placeholder="Search Layanan">
          </div>
      </div>
      <div class="dt-ext table-responsive">
        <table class="table table-hover" id="harga-table">
          <!-- Table data will be loaded dynamically using JavaScript -->
        </table>
      </div>
      <br>
      <div class="d-flex justify-content-center">
        <ul class="pagination" id="pagination-harga">
          <!-- Pagination links will be loaded dynamically using JavaScript -->
        </ul>
      </div>
    </div>
  </div>
</div>
               <!-- Add the JavaScript code for DataTables and pagination -->
            </div>
         </div>
      </div>
   </div>
   <!-- Container-fluid Ends-->
</div> 
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
  $(document).ready(function () {
    const table = $("#harga-table");
    const pagination = $("#pagination-harga");
    const maxVisiblePages = 5; // Maximum number of visible pagination links

    // Constants to keep track of current page and records per page
    let currentPage = 1;
    const recordsPerPage = 10; // Number of records to show per page

    // Function to fetch and update table data based on the current page, category, and search input
    function updateTableData(page, category = '', searchQuery = '') {
      $.ajax({
        url: "get_services_data.php",
        method: "GET",
        data: { page: page, recordsPerPage: recordsPerPage, category: category, search: searchQuery },
        dataType: "json",
        success: function (data) {
          // Clear existing table rows
          table.empty();

          // Add table header
          table.append("<thead><tr><th>ID</th><th>Kategori</th><th>Layanan</th><th>Harga /1000</th><th>Kecepatan Rata²</th><th>Minimal</th><th>Maximal</th></tr></thead>");

          // ... (rest of the existing code)

          // Add table body with fetched data
          const tbody = $("<tbody></tbody>");
          $.each(data.services, function (index, item) {
            // Check if the category filter is set and matches the current item's category
            if (category === '' || category === item.category) {
              const row = $("<tr class='border-bottom-success'></tr>");
              row.append("<td>" + item.sid + "</td>");
              row.append("<td>" + item.category + "</td>");
              row.append("<td>" + item.service + "</td>");
              row.append("<td>" + formatCurrency(item.price) + "</td>");
              row.append("<td>" + item.average + "</td>");
              row.append("<td>" + item.min + "</td>");
              row.append("<td>" + item.max + "</td>");
              tbody.append(row);
            }
          });
          table.append(tbody);

          // Update pagination links
          pagination.empty();
          const totalPages = data.totalPages;
          let startPage = 1;
          let endPage = totalPages;

          if (totalPages > maxVisiblePages) {
            const halfMaxVisiblePages = Math.floor(maxVisiblePages / 2);
            startPage = Math.max(currentPage - halfMaxVisiblePages, 1);
            endPage = startPage + maxVisiblePages - 1;

            if (endPage > totalPages) {
              endPage = totalPages;
              startPage = Math.max(endPage - maxVisiblePages + 1, 1);
            }
          }

          for (let i = startPage; i <= endPage; i++) {
            pagination.append(
              '<li class="page-item' + (i === currentPage ? ' active' : '') + '"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>'
            );
          }

          // Add navigation arrows for previous and next
          if (currentPage > 1) {
            pagination.prepend(
              '<li class="page-item' + (1 === currentPage ? ' disabled' : '') + '"><a class="page-link" href="#" data-page="1">First</a></li>'+
              '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage - 1) + '">&#171;</a></li>'
            );
          }

          if (currentPage < totalPages) {
            pagination.append(
              '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage + 1) + '">&#187;</a></li>'+
              '<li class="page-item' + (totalPages === currentPage ? ' disabled' : '') + '"><a class="page-link" href="#" data-page="' + totalPages + '">Last</a></li>'
            );
          }
        },
        error: function (xhr, status, error) {
          console.error("Error fetching data:", error);
        }
      });
    }

    function handlePaginationClick(event) {
      event.preventDefault();
      const newPage = parseInt($(this).data("page"));
      if (newPage !== currentPage) {
        currentPage = newPage;
        updateTableData(currentPage, $("#category-filter").val(), $("#search-input").val().trim());
      }
    }

    // Function to handle search input
    $("#search-input").on("input", function() {
      const searchQuery = $(this).val().trim();
      currentPage = 1; // Reset to the first page when performing a new search
      updateTableData(currentPage, $("#category-filter").val(), searchQuery);
    });

    // Function to handle category filter
    $("#category-filter").on("change", function () {
      const selectedCategory = $(this).val();
      currentPage = 1; // Reset to the first page when changing the category filter
      updateTableData(currentPage, selectedCategory, $("#search-input").val().trim());
    });

    // Attach pagination click event for individual page numbers
    pagination.on("click", "li.page-item:not(.active) a.page-link", handlePaginationClick);

    // Attach click event for previous and next arrows
    pagination.on("click", "li.page-item a.page-link[data-page]", function(event) {
      event.preventDefault();
      const newPage = parseInt($(this).data("page"));
      if (newPage !== currentPage) {
        currentPage = newPage;
        updateTableData(currentPage, $("#category-filter").val(), $("#search-input").val().trim());
      }
    });

    // Initial table data fetch for the first page and all categories
    updateTableData(currentPage);
  });

  // Function to format the number with periods instead of commas
  function formatCurrency(num) {
    return "Rp " + num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
</script>
<?php
include("../lib/footer.php");
?>