<?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 justify-content-center">
              <div class="col-xxl-12">
            <div class="card">
  <div class="card-body"><div class="input-group mb-3">
                           <input type="text" id="search-orders-historys" class="form-control" placeholder="Search Order ID">
                        </div>
    <div class="table-responsive">
      <table class="table table-hover" id="order-history-table">
      </table>
    </div>
    <br>
    <div class="d-flex justify-content-center">
      <ul class="pagination justify-content-end mb-0" id="pagination-orders-history">
        <!-- 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 = $("#order-history-table");
  const pagination = $("#pagination-orders-history");
  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 and search input
  function updateTableData(page, searchQuery = '') {
    $.ajax({
      url: "get_order_history.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>Tanggal</th><th>Order ID</th><th>Service</th><th>Link</th><th>Quantity</th><th>Start Count</th><th>Remains</th><th>Price</th><th>Status</th><th>Refund</th></tr></thead>");

        // Add table body with fetched data
        const tbody = $("<tbody></tbody>");
        $.each(data.order_history, function(index, item) {
          const row = $("<tr></tr>");
          row.append("<td>" + item.date + "</td>");
          row.append("<td>" + item.oid + " <button class='btn btn-primary btn-xs copy-btn' data-clipboard-text='" + item.oid + "'><i class='fa fa-copy'></i></button></td>");
          row.append("<td>" + item.service + "</td>");
          row.append("<td>" + item.link + " <button class='btn btn-primary btn-xs copy-btn' data-clipboard-text='" + item.link + "'><i class='fa fa-copy'></i></button></td>");
          row.append("<td>" + item.quantity + "</td>");
          row.append("<td>" + item.start_count + "</td>");
          row.append("<td>" + item.remains + "</td>");
          row.append("<td>" + item.price + "</td>");
          // Check the value of "status" and display the appropriate badge
          if (item.status == 'Pending') {
            row.append("<td align='center'><span class='badge badge-warning'>"+item.status+"</span></td>");
          } else if (item.status == 'Processing') {
            row.append("<td align='center'><span class='badge badge-primary'>"+item.status+"</span></td>");
          } else if (item.status == 'Error') {
            row.append("<td align='center'><span class='badge badge-danger'>"+item.status+"</span></td>");
          } else if (item.status == 'Partial') {
            row.append("<td align='center'><span class='badge badge-danger'>"+item.status+"</span></td>");
          } else if (item.status == 'Success') {
            row.append("<td align='center'><span class='badge badge-success'>"+item.status+"</span></td>");
          } else {
            row.append("<td></td>"); // Handle other cases, if needed
          }

          // Check the value of "refund" and display the appropriate badge
          if (item.refund === '0') {
            row.append("<td align='center'><span class='badge badge-danger'><i class='fa fa-times'></i></span></td>");
          } else if (item.refund === '1') {
            row.append("<td align='center'><span class='badge badge-success'><i class='fa fa-check'></i></span></td>");
          } else {
            row.append("<td></td>"); // Handle other cases, if needed
          }

          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>'
            );
          }

        // Initialize Clipboard.js for copy buttons
        new ClipboardJS('.copy-btn');
      },
      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;
      updateTableData(currentPage, $("#search-orders-historys").val().trim());
    }
  }

  // Function to handle search input
  $("#search-orders-historys").on("input", function() {
    const searchQuery = $(this).val().trim();
    currentPage = 1; // Reset to the first page when performing a new search
    updateTableData(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;
      updateTableData(currentPage, $("#search-orders-historys").val().trim());
    }
  });

  // Initial table data fetch for the first page
  updateTableData(currentPage);
});
</script>
<?php
	include("../lib/footer.php");
} else {
	header("Location: ".$cfg_baseurl);
}
?>