<?php
// Recoded by Gh0Code
// Hargailah orang lain jika Anda ingin dihargai
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['add'])) {
					$post_name = $_POST['name'];
					$post_level = $_POST['level'];
					$post_contact = $_POST['contact'];

			$checkdb_staff = mysqli_query($db, "SELECT * FROM staff WHERE name = '$post_name'");
			$datadb_staff = mysqli_fetch_assoc($checkdb_staff);
			if (empty($post_name) || empty($post_level) || empty($post_contact)) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Mohon mengisi semua input.";
			} else if ($post_level != "Developer" AND $post_level != "Admin" AND $post_level != "Reseller") {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Input tidak sesuai.";
			} else if (mysqli_num_rows($checkdb_staff) > 0) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Staff $post_name sudah terdaftar dalam database.";
			} else {
				$insert_staff = mysqli_query($db, "INSERT INTO staff (name, level, contact) VALUES ('$post_name', '$post_level', '$post_contact')");
				if ($insert_staff == TRUE) {
					$msg_type = "success";
					$msg_content = "<b>Success:</b> Staff berhasil ditambahkan.<br /><b>Nama:</b> $post_name<br /><b>Level:</b> $post_level<br /><b>Kontak:</b>". nl2br($post_contact);
				} else {
					$msg_type = "error";
					$msg_content = "<b>Gagal:</b> Error system.";
				}
			}
		} else if (isset($_POST['edit'])) {
		            $post_id = $_POST['id'];
					$post_name = $_POST['name'];
					$post_level = $_POST['level'];
					$post_contact = $_POST['contact'];
					if (empty($post_id) || empty($post_name) || empty($post_contact)) {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Mohon mengisi semua input.";
					} else if ($post_level != "Admin" AND $post_level != "Reseller") {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Input tidak sesuai.";
					} else {
						$update_staff = mysqli_query($db, "UPDATE staff SET name = '$post_name', contact = '$post_contact', level = '$post_level' WHERE id = '$post_id'");
						if ($update_staff == TRUE) {
							$msg_type = "success";
							$msg_content = "<b>Berhasil:</b> Staff berhasil diubah.<br /><b>Nama:</b> $post_name<br /><b>Level:</b> $post_level<br /><b>Kontak:</b> ".nl2br($post_contact);
						} else {
							$msg_type = "error";
							$msg_content = "<b>Gagal:</b> Error system.";
						}
					}
				} else if (isset($_POST['delete'])) {
			$post_id = $_POST['id'];
			$post_name = $_POST['name'];
			$checkdb_staff = mysqli_query($db, "SELECT * FROM staff WHERE id = '$post_id'");
			if (mysqli_num_rows($checkdb_staff) == 0) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Staff tidak ditemukan.";
			} else {
				$delete_staff = mysqli_query($db, "DELETE FROM staff WHERE id = '$post_id'");
				if ($delete_staff == TRUE) {
					$msg_type = "success";
					$msg_content = "<b>Berhasil:</b> Staff <b>$post_name</b> dihapus.";
				}
			}
		}

	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") {
											?>
											<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="col-xxl-3">
                    <div class="card">
                <button type="submit" class="btn btn-primary" data-bs-toggle='modal' data-bs-target='#tambahingfo'><i class="fa fa-plus"></i> Add Staff </button>
                <div class='modal fade' id='tambahingfo' 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'>Add Staff</h3>
        <div class='modal-body'>
          <form class='row g-3' method='POST'>
            <div class='col-md-6'>
              <label class='form-label' for='exampleFormControlInput1'>Name</label>
              <input class='form-control' id='exampleFormControlInput1' type='text' name="name" placeholder='namanya siapa'></input>
            </div>
            <div class='col-md-6'>
              <label class='form-label' for='exampleFormControlInput1'>Level</label>
              <select class='form-control' name='level'> 
              <option value='Admin'>Admin</option> 
              <option value='Reseller'>Reseller</option></select>
            </div>
            <div class='col-md-12'>
              <label class='form-label' for='exampleFormControlInput1'>Kontak</label>
              <textarea class='form-control' id='exampleFormControlInput1' type='text' name="contact" placeholder='namanya siapa'></textarea>
            </div>
            <div class='col-md-12'>
              <button class='btn btn-primary' type='submit' name="add">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="table-responsive">
      <table class="table table-hover" id="staff-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-staff">
        <!-- 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 = $("#staff-table");
  const pagination = $("#pagination-staff");
  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_staff_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>No.</th><th>Name</th><th>Contact</th><th>Level</th></tr></thead>");

        // Add table body with fetched data
        const tbody = $("<tbody></tbody>");
        $.each(data.staff, function(index, item) {
          const row = $("<tr></tr>");
          row.append("<td>" + item.id + "</td>");
          row.append("<td>" + item.name + "</td>");
          row.append("<td>" + nl2br(item.contact) + "</td>");
          row.append("<td>" + item.level + "</td>");
          row.append("<td align='center'>" +
              "<a class='btn btn-xs btn-warning' data-bs-toggle='modal' data-bs-target='#editstaff" + item.id + "'><i class='fa fa-edit'></i></a> " +
              "<div class='modal fade' id='editstaff" + 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'>Level</label> <select class='form-control' name='level'> <option value='"+item.level+"'>"+item.level+"</option><option value='Admin'>Admin</option> <option value='Reseller'>Reseller</option></select> </div> <div class='col-md-12'> <label class='form-label' for='validationCustom01'>Name</label> <input type='text' class='form-control' value='" + item.name + "' name='name' > </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Kontak</label> <textarea class='form-control' id='exampleFormControlInput1' type='text' name='contact'>" + item.contact + "</textarea> </div>  <div class='col-md-12'> <button class='btn btn-primary' type='submit' name='edit'>Submit Gan</button> </div> </form> </div> </div> </div> </div> </div>" +
              "<a class='btn btn-xs btn-danger' data-bs-toggle='modal' data-bs-target='#deletestaff" + item.id + "'><i class='fa fa-trash-o'></i></a> " +
              "<div class='modal fade' id='deletestaff" + 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'>Level</label> <input type='text' class='form-control' name='date' placeholder='User' value='" + item.level + "' readonly> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Kontak</label> <textarea class='form-control' id='exampleFormControlInput1' type='text' name='contact' readonly>" + item.contact + "</textarea> </div>  <div class='col-md-12'> <button class='btn btn-danger' type='submit' name='delete'>Delete 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-staff").val().trim());
    }
  }

  // Function to handle search input
  $("#search-staff").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-staff").val().trim());
    }
  });
    
    function nl2br(str) {
    return str.replace(/(?:\r\n|\r|\n)/g, "<br>");
  }
  
  // Initial table data fetch for the first page
  updateTableData(currentPage);
});

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