<?php
$datetime = new DateTime( "now", new DateTimeZone( "Asia/Jakarta" ) );
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['delete'])) {
			$post_id = $_POST['id'];
			$checkdb_news = mysqli_query($db, "SELECT * FROM topup WHERE id = '$post_id'");
			if (mysqli_num_rows($checkdb_news) == 0) {
				$msg_type = "error";
				$msg_content = "Topup tidak ditemukan.";
			} else {
				$delete_news = mysqli_query($db, "DELETE FROM topup WHERE id = '$post_id'");
				if ($delete_news == TRUE) {
					$msg_type = "success";
					$msg_content = "Topup deleted.";
				}
			}
		} else if (isset($_POST['ubah_rate'])) {
			$post_rate = $_POST['ratenya'];
			$checkdb_news = mysqli_query($db, "SELECT * FROM akun_qris WHERE id = '1'");
			if (mysqli_num_rows($checkdb_news) == 0) {
				$msg_type = "error";
				$msg_content = "Data tidak ditemukan.";
			} else {
				$delete_news = mysqli_query($db, "UPDATE akun_qris SET rate = '$post_rate' WHERE id = '1'");
				if ($delete_news == TRUE) {
					$msg_type = "success";
					$msg_content = "Rate berhasil diubah.";
				}
			}
		}

	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">
                <?php 
											if ($msg_type == "success") {
											    echo "<script>
            Swal.fire(
  'Good Job!',
  '$msg_content',
  '$msg_type'
)
          </script>";
											
											} else if ($msg_type == "error") {
											echo "<script>
            Swal.fire(
  'Failure!',
  '$msg_content',
  '$msg_type'
)
          </script>";
											}
											?>
        <div class="col-xxl-3">
                    <div class="card">
                <button type="submit" class="btn btn-primary" data-bs-toggle='modal' data-bs-target='#add_user'>Rate Option</button>
                <div class='modal fade' id='add_user' tabindex='-1' role='dialog' aria-labelledby='exampleModalgetbootstrap' aria-hidden='true'>
                  <div class='modal-dialog' role='document'>
                    <div class='modal-content'>
                      <div class='modal-toggle-wrapper social-profile text-start dark-sign-up'>
                        <h3 class='modal-header justify-content-center border-0'>Rate Option</h3>
                        <div class='modal-body'>
                          <form class='row g-3' method='POST'>
                            <div class='col-md-12'>
                              <label class='form-label' for='exampleFormControlInput1'>Rate Option (Default 1)</label>
                              <input class='form-control' id='exampleFormControlInput1' type='text' name="ratenya" value='<? $ambil_data = mysqli_query($db, "SELECT * FROM akun_qris ORDER BY id ASC"); 
while($datanya = mysqli_fetch_assoc($ambil_data)){
echo $datanya['rate']; } ?>'>
                            </div>
                            <div class='col-md-12'>
                              <button class='btn btn-primary' type='submit' name="ubah_rate">Submit Gan</button>
                            </div>
                          </form>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                </div>
            </div>
              <div class="col-xxl-12">
    <div class="card">
        <div class="card-body">
            <div class="input-group mb-3">
                <input type="text" id="search-topups" class="form-control" placeholder="Search Top-ups">
            </div>
            <div class="table-responsive">
                <table class="table table-hover" id="topupgan-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-topupgan">
                    <!-- 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 = $("#topupgan-table");
    const pagination = $("#pagination-topupgan");
    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_topup_datas.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>ID</th><th>Username</th><th>Jumlah</th><th>Kode Unik</th><th>Status</th><th>Tanggal</th><th>#</th></tr></thead>");

          // Add table body with fetched data
          const tbody = $("<tbody></tbody>");
          $.each(data.topups, function(index, item) {
                    const row = $("<tr class='border-bottom-success'></tr>");
                    row.append("<td>" + item.id + "</td>");
                    row.append("<td>" + item.username + "</td>");
                    row.append("<td>" + item.jumlah + "</td>");
                    row.append("<td>" + item.kode_unik + "</td>");
                    if (item.status == 'Waiting') {
            row.append("<td><span class='badge badge-warning'>"+item.status+"</span></td>");
          }  else if (item.status == 'Canceled') {
            row.append("<td><span class='badge badge-danger'>"+item.status+"</span></td>");
          }  else if (item.status == 'Completed') {
            row.append("<td><span class='badge badge-success'>"+item.status+"</span></td>");
          } else {
            row.append("<td></td>"); // Handle other cases, if needed
          }
                    row.append("<td>" + item.tanggal + "</td>");
                    row.append("<td>" +
              "<a class='btn btn-xs btn-danger' data-bs-toggle='modal' data-bs-target='#deletetopup" + item.id + "'><i class='fa fa-trash-o'></i></a> " +
              "<div class='modal fade' id='deletetopup" + item.id + "' tabindex='-1' role='dialog' aria-labelledby='exampleModalgetbootstrap' aria-hidden='true'> <div class='modal-dialog' role='document'> <div class='modal-content'> <div class='modal-toggle-wrapper social-profile text-start dark-sign-up'> <h3 class='modal-header justify-content-center border-0'>Order Edit</h3> <div class='modal-body'> <form class='row g-3' method='POST'> <div class='col-md-6'> <label class='form-label' for='validationCustom01'>ID</label> <input type='text' class='form-control' value='" + item.id + "' name='id' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Jumlah</label> <input type='text' class='form-control' name='date' placeholder='User' value='" + item.jumlah + "' readonly> </div> <div class='col-md-12'> <label class='form-label' for='validationCustom02'>Username</label> <input type='text' class='form-control' name='date' placeholder='User' value='" + item.username + "' readonly> </div>  <div class='col-md-12'> <button class='btn btn-primary' type='submit' name='delete'>Submit Gan</button> </div> </form> </div> </div> </div> </div> </div>" +
              "</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;
      updateTableData(currentPage, $("#search-topups").val().trim());
    }
  }

  // Function to handle search input
  $("#search-topups").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-topups").val().trim());
    }
  });

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

  // Function to format the number as currency (Rp)
  function formatCurrency(num) {
    return "Rp " + num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
</script>
<?php
	include("../../lib/footer.php");
	}
} else {
	header("Location: ".$cfg_baseurl);
}
?>