<?php
// Recoded by Gh0Code
// Hargailah orang lain jika Anda ingin dihargai
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 justify-content-center">
              <div class="col-xxl-12">
  <div class="card">
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-hover" id="catatan-table">
          <!-- Table data will be loaded dynamically using JavaScript -->
        </table>
      </div>
      <br>
      <div class="d-flex justify-content-center">
        <ul class="pagination justify-content-end mb-0" id="pagination-catatan">
          <!-- Pagination links will be loaded dynamically using JavaScript -->
        </ul>
      </div>
    </div>
  </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 = $("#catatan-table");
  const pagination = $("#pagination-catatan");
  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 catatan data based on the current page and search input
  function updateCatatanData(page, searchQuery = '') {
    $.ajax({
      url: "get_catatan_data.php",
      method: "GET",
      data: { page: page, recordsPerPage: recordsPerPage, search: searchQuery },
      dataType: "json",
      success: function(data) {
        // Clear existing table rows
        table.empty();

        // Add table header
        table.append("<thead><tr><th>Note</th><th>Waktu</th></tr></thead>");

        // Add table body with fetched data
        const tbody = $("<tbody></tbody>");
        $.each(data.catatan, function(index, item) {
          const row = $("<tr></tr>");
          row.append("<td>" + item.note + "</td>");
          row.append("<td>" + item.waktu + "</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 to handle page navigation click
  function handlePaginationClick(event) {
    event.preventDefault();
    const newPage = parseInt($(this).data("page"));
    if (newPage !== currentPage) {
      currentPage = newPage;
      updateCatatanData(currentPage, $("#search-catatan").val().trim());
    }
  }

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

  // 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;
      updateCatatanData(currentPage, $("#search-catatan").val().trim());
    }
  });

  // Initial catatan data fetch for the first page
  updateCatatanData(currentPage);
});

</script>
<?php
	include("../lib/footer.php");
} else {
	header("Location: ".$cfg_baseurl);
}
?>