<?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");
	}

if (isset($_POST['submit'])) {
		$post_subject =  mysqli_real_escape_string($db, $_POST['subject']);
		$post_message = mysqli_real_escape_string($db, $_POST['message']);
		if($_POST['order_id'] != 0){
		    $idnya = $_POST['order_id'];
		} else if ($_POST['deposit_id'] != 0){
		    $idnya = $_POST['deposit_id'];
		} else {
		    $idnya = 0;
		}
		if (empty($post_subject) || empty($post_message)) {
			$msg_type = "error";
			$msg_content = "<b>Gagal:</b> Mohon mengisi semua input.";
		} else if (strlen($post_subject) > 200) {
			$msg_type = "error";
			$msg_content = "<b>Gagal:</b> Maximal subject menggunakan 200 karakter.";
		} else if (strlen($post_message) > 500) {
			$msg_type = "error";
			$msg_content = "<b>Gagal:</b> Maximal message menggunakan 500 karakter.";
		} else {
			$insert_ticket = mysqli_query($db, "INSERT INTO tickets (user, subject, idnya, message, datetime, last_update, status) VALUES ('$sess_username', '$post_subject', $idnya, '$post_message', '$date $time', '$date $time', 'Pending')");
			if ($insert_ticket == TRUE) {
				$msg_type = "success";
				$msg_content = "<b>Berhasil:</b> Ticket terkirim, mohon menunggu admin untuk membalas pesan ticket dari anda, trimakasih.";
				$text1 = str_replace("<br />", "\n", nl2br($_POST['message']));
				$textnya = urlencode("*New Created Ticket*\nUsername : $sess_username\nSubject : $post_subject - $idnya\nText : $text1");
				file_get_contents('https://wassup.codinginan.com/send-message?api_key=7vjF9ac0zIuclLXboUI1GvBeNmhyJW&sender=6281292200561&number=6285246050710|6285161740004&message='.$textnya);
			} else {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> System error.";
			}
		}
		unset($_SESSION['postdata']);
	}
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>Ticket Saya</h5>
                    <p class="f-m-light mt-1">Ticket hanya diperlukan jika terdapat masalah pada orderan/deposit atau masalah lainnya.</p>
                  </div>
                  <div class="card-body">
                    <div class="row" bis_skin_checked="1">
    <div class="table-responsive col-md-8">
      <table class="table table-hover" id="ticket-table">
      </table>
    </div>
    <div class="accordion dark-accordion col-md-4" id="simpleaccordion" bis_skin_checked="1">
                      <div class="accordion-item" bis_skin_checked="1">
                        <h2 class="accordion-header" id="headingOne">
                          <button class="accordion-button collapsed accordion-light-primary txt-primary active" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">Arti Setiap Status Ticket<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-down svg-color" style="--darkreader-inline-stroke: currentColor;" data-darkreader-inline-stroke=""><polyline points="6 9 12 15 18 9"></polyline></svg></button>
                        </h2>
                        <div class="accordion-collapse collapse" id="collapseOne" aria-labelledby="headingOne" data-bs-parent="#simpleaccordion" bis_skin_checked="1">
                          <div class="accordion-body" bis_skin_checked="1">
                            Pending = Pesan Terkirim, menunggu jawaban Admin<br>
                            Responded = Admin telah merespon<br>
                            Closed = Ticket telah ditutup dengan penyelesaian sesuai pernyataan Admin
                            </div>
                        </div>
                      </div>
                      <div class="accordion-item" bis_skin_checked="1">
                        <h2 class="accordion-header" id="headingTwo">
                          <button class="accordion-button collapsed accordion-light-primary txt-primary active" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">Buat Ticket baru<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-down svg-color" style="--darkreader-inline-stroke: currentColor;" data-darkreader-inline-stroke=""><polyline points="6 9 12 15 18 9"></polyline></svg></button>
                        </h2>
                        <div class="accordion-collapse collapse" id="collapseTwo" aria-labelledby="headingTwo" data-bs-parent="#simpleaccordion" bis_skin_checked="1">
                          <div class="card-body custom-input" bis_skin_checked="1">
                    <form class="row g-3" method="POST">
                      <div class="col-12" bis_skin_checked="1"> 
                            <label class="form-label" for="validationDefault04">Subjek</label>
                            <select class="form-select" id="validationDefault04" name="subject" required="" onchange="toggleFormFields()">
                                <option selected="" disabled="" value="">Choose...</option>
                                <option value="Pesanan">Pesanan</option>
                                <option value="Deposit">Deposit</option>
                                <option value="Lain-Lain">Lain-Lain</option>
                            </select>
                        </div>
                        <div id="show1" style="display: none" class="col-12" bis_skin_checked="1"> 
                            <label class="form-label" for="exampleFormControlTextarea1">Order ID</label>
                            <input type="text" name="order_id" class="form-control btn-pill digits" placeholder="Masukkan Order ID Anda" value="">
                        </div>
                        <div id="show2" style="display: none" class="col-12" bis_skin_checked="1"> 
                            <label class="form-label" for="exampleFormControlTextarea2">Deposit ID</label>
                            <input type="text" name="deposit_id" class="form-control btn-pill digits" placeholder="Masukkan Deposit ID Anda" value="">
                        </div>
                      <div class="col-12" bis_skin_checked="1"> 
                        <label class="form-label" for="exampleFormControlTextarea1">Pesan</label>
                        <textarea class="form-control" id="exampleFormControlTextarea1" name="message" rows="3"></textarea>
                      </div>
                      <div class="col-12" bis_skin_checked="1">
                        <button class="btn btn-primary" type="submit" name="submit">Submit</button>
                      </div>
                    </form>
                  </div>
                        </div>
                      </div>
                    </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_ticket_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></tr></thead>");

        // Add table body with fetched data
        const tbody = $("<tbody></tbody>");
        $.each(data.ticket_history, function(index, item) {
          const row = $("<tr></tr>");
            const ticketLink = $("<a></a>").attr("href", "/pages/ticket_open?id=" + item.id).text("#" + item.id);
            row.append("<td>" + ticketLink.prop('outerHTML') + "</td>");
            row.append("<td><a href='/pages/ticket_open?id=" + item.id + "'>" + item.subject + "</a></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
          }

          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>
<script>
    function toggleFormFields() {
        var subjectSelect = document.getElementById("validationDefault04");
        var orderIDInputDiv = document.getElementById("show1");
        var depositIDInputDiv = document.getElementById("show2");

        // Sembunyikan semua div terlebih dahulu
        orderIDInputDiv.style.display = "none";
        depositIDInputDiv.style.display = "none";

        // Tampilkan div yang sesuai berdasarkan subjek yang dipilih
        if (subjectSelect.value === "Pesanan") {
            orderIDInputDiv.style.display = "block";
        } else if (subjectSelect.value === "Deposit") {
            depositIDInputDiv.style.display = "block";
        }
    }
</script>
<?php
	include("../lib/footer.php");
} else {
	header("Location: ".$cfg_baseurl);
}
?>