<?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['delete'])) {
			$post_sid = $_POST['sid'];
			$checkdb_service = mysqli_query($db, "SELECT * FROM services WHERE sid = '$post_sid'");
			if (mysqli_num_rows($checkdb_service) == 0) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Layanan tidak ditemukan.";
			} else {
				$delete_user = mysqli_query($db, "DELETE FROM services WHERE sid = '$post_sid'");
				if ($delete_user == TRUE) {
					$msg_type = "success";
					$msg_content = "<b>Berhasil:</b> Layanan <b>$post_sid</b> dihapus.";
				}
			}
		} else if (isset($_POST['delete_service'])) {
				$delete_service = mysqli_query($db, "DELETE FROM services");
				$delete_service1 = mysqli_query($db, "DELETE FROM service_cat");
				if ($delete_service == TRUE) {
					$msg_type = "success";
					$msg_content = "<b>Berhasil:</b> Layanan dihapus.";
				} else {
					$msg_type = "error";
					$msg_content = "<b>Gagal:</b> Error system.";
			}
		} else if (isset($_POST['editsepis'])) {
// memulai proses edit user

$add_username = $_POST['idnya'];
$add_password = $_POST['categorynya'];
$add_balance = $_POST['servicenya'];
$add_email = $_POST['harganya'];
$add_level = $_POST['statusnya'];

// mencari data di database
$cekdata = mysqli_query($db,"SELECT * FROM services WHERE sid = '$add_username'");
$sdata = mysqli_fetch_array($cekdata);
$scount = mysqli_num_rows($cekdata);

$show_username = $sdata['sid'];
$add_id = $sdata['sid'];

	$send = mysqli_query($db, "UPDATE services SET sid = '$add_username' WHERE sid = '$add_id'");
	$send = mysqli_query($db, "UPDATE services SET category = '$add_password' WHERE sid = '$add_id'");
    $send = mysqli_query($db, "UPDATE services SET service = '$add_balance' WHERE sid = '$add_id'");
    $send = mysqli_query($db, "UPDATE services SET price = '$add_email' WHERE sid = '$add_id'");
    $send = mysqli_query($db, "UPDATE services SET status = '$add_level' WHERE sid = '$add_id'");
		} else if (isset($_POST['get_irv'])) {
        $key = "aa9f8e-bb2b3f-61fa01-587b63-188230"; // your api key
$postdata = "api_key=$key&api_id=2068";
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://irvankedesmm.co.id/api/services");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$chresult = curl_exec($ch);
//echo $chresult;
curl_close($ch);
$json_result = json_decode($chresult, true);
$indeks=0;
$i = 1;
// get data service
while($indeks < count($json_result['data'])){
   
$category=$json_result['data'][$indeks]['category'];
$id =$json_result['data'][$indeks]['id'];
$service = $json_result['data'][$indeks]['name'];
$min_order =$json_result['data'][$indeks]['min'];
$max_order = $json_result['data'][$indeks]['max'];
$price = $json_result['data'][$indeks]['price'];
$note = $json_result['data'][$indeks]['note'];
$average = $json_result['data'][$indeks]['average'];
$status = $json_result['data'][$indeks]['status'];
if ($status == '0') {
    $finalnya = 'Not active';
} else {
    $finalnya = 'Active';
};
$indeks++;
$i++;
// end get data service
// setting price
$k = 1.25;
$rate = $price;
$rate_asli = $rate * $k; //setting penambahan harga
// setting price
 $check_services = mysqli_query($db, "SELECT * FROM services WHERE pid = '$id' AND provider='SMMKITA'");
 //           $check_services = mysqli_query($db, "SELECT * FROM service_cat WHERE name = '$category' AND code = '$category'");
            $data_services = mysqli_fetch_assoc($check_orders);
        if(mysqli_num_rows($check_services) > 0) {
            echo "Service Sudah Ada Di database => $service | $id \n <br />";
        } else {
           $layanan2 = strtr($service, array(
			' IRVANKEDE' => ' BMED',
			' IRVAN KEDE' => ' BMED',
			' Irvankede' => ' BMED',
			' IRV' => ' BMED',
			' IKP' => ' BMED',
			' IK' => ' BMED',
		));	
		$category2 = strtr($category, array(
			' IRVANKEDE' => ' BMED',
			' IRVAN KEDE' => ' BMED',
			' Irvankede' => ' BMED',
			' IRV' => ' BMED',
			' IKP' => ' BMED',
			' IK' => ' BMED',
			'TikTok  Views, Komentar , Like Komentar &Share ' => 'TikTok Service',
			'TikTok  Views, Komentar , Like Komentar &Share ' => 'TikTok Service'
		));	
		$note2 = strtr($note, array(
			' IRVANKEDE' => ' BMED',
			' IRVAN KEDE' => ' BMED',
			' irvankede' => ' BMED',
			' irvankedepanel' => ' BMED',
			' IRV' => ' BMED',
			' IKP' => ' BMED',
			' IK' => ' BMED',
		));	
		$note = str_replace(['irvankede', 'irvankede', 'irvankedepanel', '081282471791'], ['BMED', 'BMED', 'BMED', '085161740004'], $note2);
		$category2 = str_replace(['(', ')'], ['[', ']'], $category2);
$insert=mysqli_query($db, "INSERT INTO services (sid, category, service, note, average, min, max, price, status, pid, provider) VALUES ('$id','$category2','$layanan2','$note', '$average', '$min_order','$max_order','$rate_asli','$finalnya','$id','SMMKITA')");//Memasukan Kepada Database (OPTIONAL)
//$insert=mysqli_query($db, "INSERT INTO service_cat (name, code) VALUES ('$category','$category')");//Memasukan Kepada Database (OPTIONAL)
if ($insert == TRUE){
					$msg_type = "success";
					$msg_content = "<b>Berhasil:</b> Layanan ditambahkan.";
            $no++;
            }else{
					$msg_type = "error";
					$msg_content = "<b>Gagal:</b> Error system.";
            }
$check_category = mysqli_query($db, "SELECT * FROM service_cat WHERE name = '$category2' AND code = '$category2'");
    if(mysqli_num_rows($check_category) > 0) {
        } else {
$insert2=mysqli_query($db, "INSERT INTO service_cat (name, code) VALUES ('$category2','$category2')");//Memasukan Kepada Database (OPTIONAL)
            }
}
}

        }

	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
											}
											?>
                <form class='row g-3 justify-content-center' method='POST'>
        <div class="col-xxl-3">
                    <div class="card">
                <button type="submit" class="btn btn-success" name="get_irv"><i class="fa fa-plus"></i> Get Service IRV</button>
                </div>
            </div>
            <div class="col-xxl-3">
                    <div class="card">
                <button type="submit" class="btn btn-danger" name="delete_service"><i class="fa fa-trash-o"></i> Delete All Service</button>
                </div>
            </div></form>
              <div class="col-xxl-12">
            <div class="card">
  <div class="card-body">
    <div class="input-group mb-3">
                           <input type="text" id="search-services" class="form-control" placeholder="Search Service">
                        </div>
    <div class="table-responsive">
      <table class="table table-hover" id="service-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-service">
        <!-- 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 = $("#service-table");
    const pagination = $("#pagination-service");
    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_services_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>ID</th><th>Category</th><th>Name</th><th>Price</th><th>Min</th><th>Max</th><th>Action</th></tr></thead>");

          // Add table body with fetched data
          const tbody = $("<tbody></tbody>");
          $.each(data.services, function(index, item) {
            const row = $("<tr class='border-bottom-success'></tr>");
            row.append("<td>" + item.sid + "</td>");
            row.append("<td>" + item.category + "</td>");
            row.append("<td>" + item.service + "</td>");
            row.append("<td>" + formatCurrency(item.price) + "</td>"); // Format the price as currency
            row.append("<td>" + item.min + "</td>");
            row.append("<td>" + item.max + "</td>");
            row.append("<td align='center'>" +
              "<a class='btn btn-xs btn-warning' data-bs-toggle='modal' data-bs-target='#editservicenya" + item.sid + "'><i class='fa fa-edit'></i></a> " +
              "<div class='modal fade' id='editservicenya"+item.sid+"' 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'>User 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.sid+"' name='idnya' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Category</label> <input type='text' class='form-control' name='categorynya' value='"+item.category+"' > </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Service Name</label> <input class='form-control' id='exampleFormControlInput1' type='text' name='servicenya' value='"+item.service+"'> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Price</label> <input type='text' class='form-control' name='harganya' placeholder='Password' value='"+item.price+"' > </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Status</label> <select class='form-control' name='statusnya'> <option value='Active'>Active</option> <option value='Not Active'>Not Active</option> </select> </div> <div class='col-md-12'> <button class='btn btn-primary' type='submit' name='editsepis'>Submit Gan</button> </div> </form> </div> </div> </div> </div> </div>"+
            //   "<a class='btn btn-xs btn-danger' data-bs-toggle='modal' data-bs-target='#deleteservicenya" + item.sid + "'><i class='fa fa-trash-o'></i></a> " +
            //   "<div class='modal fade' id='deleteservicenya"+item.sid+"' 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'>Delete Service</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.sid+"' name='idnya' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Category</label> <input type='text' class='form-control' name='categorynya' value='"+item.category+"' readonly> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Service Name</label> <input class='form-control' id='exampleFormControlInput1' type='text' name='servicenya' value='"+item.service+"' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Price</label> <input type='text' class='form-control' name='harganya' placeholder='Password' value='"+item.price+"' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Status</label> <select class='form-control' name='statusnya' readonly> <option value='Active'>Active</option> <option value='Not Active'>Not Active</option> </select> </div> <div class='col-md-12'> <button class='btn btn-danger' 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-services").val().trim());
      }
    }

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