<?php
session_start();
require("../../mainconfig.php");
$msg_type = "nothing";

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");
	} else if ($data_user['level'] != "Developers") {
		header("Location: ".$cfg_baseurl);
	} else {
	    if (isset($_POST['closed'])) {
		    $post_target = $_POST['id'];
					if ($data_ticket['status'] == "Closed") {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Ticket already closed.";
					} else {
						$update_ticket = mysqli_query($db, "UPDATE tickets SET status = 'Closed' WHERE id = '$post_target'");
						if ($update_ticket == TRUE) {
							$msg_type = "success";
							$msg_content = "<b>Berhasil:</b> Ticket closed.";
						} else {
							$msg_type = "error";
							$msg_content = "<b>Gagal:</b> System error.";
						}
					}
				}

	include("../../lib/header.php");
?>
<div class="page-body checkout">
    <?php include('../../lib/partial/breadcrumb.php') ?>
          <!-- Container-fluid starts-->
          <div class="container-fluid" bis_skin_checked="1">
            <div class="row" bis_skin_checked="1">
              <div class="col-sm-12" bis_skin_checked="1">
                  <?php 
											if ($msg_type == "success") {
											?>
											<div class="alert alert-success dark" role="alert">
                      <p><?php echo $msg_content; ?></p>
                    </div>
											<?php
											} else if ($msg_type == "error") {
											?>
											<div class="alert alert-secondary dark" role="alert">
                          <p><?php echo $msg_content; ?></p>
                        </div>
											<?php
											}
											?>
                <div class="card" bis_skin_checked="1">
                  <div class="card-header" bis_skin_checked="1">
                    <h5>Kelola Ticket</h5>
                    <p class="f-m-light mt-1">Harap dikelola dengan baik</p>
                  </div>
                  <div class="card-body">
                    <div class="row" bis_skin_checked="1">
                        <div class="table-responsive">
                          <table class="table table-hover" id="ticket--table">
                          </table>
                        </div>
                    </div>
    <br>
    <div class="d-flex justify-content-center">
      <ul class="pagination justify-content-end mb-0" id="pagination--tickets">
        <!-- 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 = $("#ticket--table");
    const pagination = $("#pagination--tickets");
    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 = 8; // Number of records to show per page

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

          // Add table header
          table.append("<thead><tr><th>ID</th><th>Subjek</th><th>Date/Time</th><th>Update Terakhir</th><th>Status</th><th>Options</th></tr></thead>");

        // Add table body with fetched data
        const tbody = $("<tbody></tbody>");
        $.each(data.ticket_history, function(index, item) {
          const row = $("<tr></tr>");
          row.append("<td>#" + item.id + "</a></td>");
          row.append("<td>" + item.subject + "</td>");
          row.append("<td>" + item.datetime + "</td>");
          row.append("<td>" + item.last_update + "</td>");
          // Check the value of "status" and display the appropriate badge
          if (item.status == 'Pending') {
            row.append("<td><span class='badge badge-warning'>"+item.status+"</span></td>");
          } else if (item.status == 'Responded') {
            row.append("<td><span class='badge badge-primary'>"+item.status+"</span></td>");
          } else if (item.status == 'Waiting') {
            row.append("<td><span class='badge badge-warning'>"+item.status+"</span></td>");
          } else if (item.status == 'Opened') {
            row.append("<td><span class='badge badge-primary'>"+item.status+"</span></td>");
          } else if (item.status == 'Closed') {
            row.append("<td><span class='badge badge-success'>"+item.status+"</span></td>");
          } else {
            row.append("<td></td>"); // Handle other cases, if needed
          } if (item.status != 'Closed'){
          row.append("<td>" +
              "<a href='ticket_reply.php?id="+item.id+"' class='btn btn-xs btn-success'><i class='fa fa-reply'></i></a> " +
              "<a class='btn btn-xs btn-danger' data-bs-toggle='modal' data-bs-target='#deleteticket" + item.id + "'><i class='fa fa-times'></i></a> " +
              "<div class='modal fade' id='deleteticket" + item.id + "' tabindex='-1' role='dialog' aria-labelledby='exampleModalgetbootstrap' aria-hidden='true'><div class='modal-dialog modal-dialog-centered' role='document'> <div class='modal-content'> <div class='modal-body'> <div class='modal-toggle-wrapper'> <ul class='modal-img'> <li> <img src='https://borneo-media.com/assets/images/gif/danger.gif' alt='error'></li> </ul> <h4 class='text-center pb-2'>Anda akan menutup ticket dengan status Closed!</h4> <p class='text-center'>Yakin ingin melakukannya?</p><form method='POST'><input type='text' name='id' value='" + item.id + "' style='display: none'><button class='btn btn-secondary d-flex m-auto' type='submit' name='closed'>Close Ticket</button></form></div> </div> </div> </div></div>" +
              "</td>");
          } else {
              row.append("<td></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);
            }
          }

          // Add "First Page" link
          //pagination.append('<li class="page-item' + (1 === currentPage ? ' disabled' : '') + '"><a class="page-link" href="#" data-page="1">First</a></li>');

          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 "Last Page" link
          //pagination.append('<li class="page-item' + (totalPages === currentPage ? ' disabled' : '') + '"><a class="page-link" href="#" data-page="' + totalPages + '">Last</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 convert newlines to <br> tags
    function nl2br(str) {
      return str.replace(/(?:\r\n|\r|\n)/g, "<br>");
    }

    // Function to handle page navigation click
    function handlePaginationClick(event) {
      event.preventDefault();
      const newPage = parseInt($(this).data("page"));
      if (newPage !== currentPage) {
        currentPage = newPage;
        updateTableData(currentPage);
      }
    }

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

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