<?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['add'])) {
			$post_username = trim($_POST['username']);
			$post_password = $_POST['password'];
			$post_balance = $_POST['balance'];
			$post_level = $_POST['level'];

			$checkdb_user = mysqli_query($db, "SELECT * FROM users WHERE username = '$post_username'");
			$datadb_user = mysqli_fetch_assoc($checkdb_user);
			if (empty($post_username) || empty($post_password)) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Mohon mengisi semua input.";
			} else if ($post_level != "Member" AND $post_level != "Reseller" AND $post_level != "Admin" AND $post_level != "Agen") {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Input tidak sesuai.";
			} else if (mysqli_num_rows($checkdb_user) > 0) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Username $post_username sudah terdaftar dalam database.";
			} else {
				$post_api = random(20);
				$insert_user = mysqli_query($db, "INSERT INTO users (username, password, balance, level, registered, status, api_key, uplink) VALUES ('$post_username', '$post_password', '$post_balance', '$post_level', '$date', 'Active', '$post_api', '$sess_username')");
				if ($insert_user == TRUE) {
					$msg_type = "success";
					$msg_content = "<b>Berhasil:</b> Pengguna berhasil ditambahkan.<br /><b>Username:</b> $post_username<br /><b>Password:</b> $post_password<br /><b>Level:</b> $post_level<br /><b>Saldo:</b> Rp ".number_format($post_balance,0,',','.');
				} else {
					$msg_type = "error";
					$msg_content = "<b>Gagal:</b> Error system.";
				}
			}
		} else if (isset($_POST['delete'])) {
			$post_username = $_POST['username'];
			$checkdb_user = mysqli_query($db, "SELECT * FROM users WHERE username = '$post_username'");
			if (mysqli_num_rows($checkdb_user) == 0) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Pengguna tidak ditemukan.";
			} else {
				$delete_user = mysqli_query($db, "DELETE FROM users WHERE username = '$post_username'");
				if ($delete_user == TRUE) {
					$msg_type = "success";
					$msg_content = "<b>Berhasil:</b> Pengguna <b>$post_username</b> dihapus.";
				}
			}
		} else if (isset($_POST['edit'])) {
// memulai proses edit user

$add_username = $_POST['username'];
$add_password = $_POST['password'];
$add_balance = $_POST['balance'];
$add_email = $_POST['email'];
$add_level = $_POST['level'];
$add_status = $_POST['status'];
$add_nohp = $_POST['nohp'];

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

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

	$send = mysqli_query($db, "UPDATE users SET password = '$add_password' WHERE username = '$add_id'");
	$send = mysqli_query($db, "UPDATE users SET balance = '$add_balance' WHERE username = '$add_id'");
    $send = mysqli_query($db, "UPDATE users SET email = '$add_email' WHERE username = '$add_id'");
    $send = mysqli_query($db, "UPDATE users SET level = '$add_level' WHERE username = '$add_id'");
    $send = mysqli_query($db, "UPDATE users SET status = '$add_status' WHERE username = '$add_id'");
    $send = mysqli_query($db, "UPDATE users SET nohp = '$add_nohp' WHERE username = '$add_id'");
    
                if ($send == TRUE) {
					$msg_type = "success";
					$msg_content = "Pengguna berhasil diubah.<br /><b>Username:</b> $add_username<br /><b>Password:</b> $add_password<br /><b>Level:</b> $add_level<br /><b>Status:</b> $add_status<br /><b>Saldo:</b> Rp ".number_format($add_balance,0,',','.');
					//$msg_content = "<b>Berhasil:</b> Pengguna berhasil diubah.<br /><b>Username:</b> $add_username<br /><b>Password:</b> $add_password<br /><b>Level:</b> $add_level<br /><b>Status:</b> $add_status<br /><b>Saldo:</b> Rp ".number_format($add_balance,0,',','.');
				}  
}

    $url = "https://irvankedesmm.co.id/api/profile";
    
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    
    $headers = array(
       "Content-Type: application/x-www-form-urlencoded",
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    
    $data = "api_id=2068&api_key=aa9f8e-bb2b3f-61fa01-587b63-188230";
    
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    
    //for debug only!
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    
    $resp = curl_exec($curl);
    $saldo = json_decode($resp, true)['data']['balance'];
    
	include("../../lib/header.php");
	$check_wuser = mysqli_query($db, "SELECT SUM(balance) AS total FROM users");
	$data_wuser = mysqli_fetch_assoc($check_wuser);
	$check_wuser = mysqli_query($db, "SELECT * FROM users");
	$count_wuser = mysqli_num_rows($check_wuser);
?>
<div class="page-body"> 
<?php include('../../lib/partial/breadcrumb.php') ?>
   <!-- Container-fluid starts-->
   <div class="container-fluid">
            <div class="row">
              <div class="col-sm-12 col-xl-6">
                <div class="card o-hidden">
                  <div class="card-body balance-widget">
                    <span class="f-w-500 f-light">Total Balance</span>
                    <h4 class="mb-3 mt-1 f-w-500 mb-0 f-22">Rp <? echo number_format($data_wuser['total'],0,',','.'); ?> <span class="f-light f-14 f-w-400 ms-1"></span>
                    </h4>
                    <span class="f-w-500 f-light">Total User</span>
                    <h4 class="mb-3 mt-1 f-w-500 mb-0 f-22"><?= $count_wuser?> Users <span class="f-light f-14 f-w-400 ms-1"></span>
                    </h4>
                    <div class="mobile-right-img">
                      <img class="left-mobile-img" src="../../assets/images/dashboard-2/widget-img.png" alt="">
                      <img class="mobile-img" src="../../assets/images/dashboard-2/mobile.gif" alt="mobile with coin">
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-sm-12 col-xl-6">
                <div class="card o-hidden">
                  <div class="card-body balance-widget">
                    <span class="f-w-500 f-light">Irvankede Balance</span>
                    <h4 class="mb-3 mt-1 f-w-500 mb-0 f-22">Rp <? echo number_format($saldo,0,',','.'); ?> <span class="f-light f-14 f-w-400 ms-1"></span>
                    </h4>
                    <span class="f-w-500 f-light">Selisih</span>
                    <h4 class="mb-3 mt-1 f-w-500 mb-0 f-22">Rp <? echo number_format($saldo-$data_wuser['total'],0,',','.'); ?> <span class="f-light f-14 f-w-400 ms-1"></span>
                    </h4>
                    <div class="mobile-right-img">
                      <img class="left-mobile-img" src="../../assets/images/dashboard-2/widget-img.png" alt="">
                      <img class="mobile-img" src="../../assets/images/gif/online-shopping.gif" alt="mobile with coin">
                    </div>
                  </div>
                </div>
              </div>
              <div class='row g-3 justify-content-center'>
                <div class="col-xxl-3">
                    <div class="card">
                        <?php 
											if ($msg_type == "success") {
											?>
											<script> Swal.fire( 'Good Job!', '<?= $msg_content ?>', 'success' ) </script>
											<?php
											} else if ($msg_type == "error") {
											?>
											<script> Swal.fire( 'Failure!', '<?= $msg_content ?>', 'error' ) </script>
											<?php
											}
											?>
                <button type="submit" class="btn btn-success" data-bs-toggle='modal' data-bs-target='#add_user'><i class="fa fa-plus"></i>Add User</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'>Add User</h3>
                        <div class='modal-body'>
                          <form class='row g-3' method='POST'>
                            <div class='col-md-12'>
                              <label class='form-label' for='exampleFormControlInput1'>Username</label>
                              <input class='form-control' id='exampleFormControlInput1' type='text' name="username" placeholder='Username'>
                            </div>
                            <div class='col-md-12'>
                              <label class='form-label' for='exampleFormControlInput1'>Password</label>
                              <input class='form-control' id='exampleFormControlInput1' type='text' name="password" placeholder='Password'>
                            </div>
                            <div class='col-md-12'>
                              <label class='form-label' for='exampleFormControlInput1'>Saldo</label>
                              <input class='form-control' id='exampleFormControlInput1' type='text' name="saldo" placeholder='Saldo'>
                            </div>
                            <div class='col-md-12'>
                              <label class='form-label' for='exampleFormControlInput1'>Level</label>
                              <select class="form-control" name="level">
														<option value="Member">Member</option>
														<option value="Admin">Admin</option>
													</select>
                            </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>
              <div class="col-xxl-12">
            <div class="card">
  <div class="card-body">
    <div class="input-group mb-3">
                           <input type="text" id="search-users" class="form-control" placeholder="Search User">
                        </div>
    <div class="table-responsive">
      <table class="table table-hover" id="user-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-user">
        <!-- 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 = $("#user-table");
  const pagination = $("#pagination-user");
  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_users_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>Status</th><th>Username</th><th>Password</th><th>Level</th><th>Saldo</th><th>Terdaftar</th><th>Uplink</th><th>API Key</th><th>Aksi</th></tr></thead>");

        // Add table body with fetched data
        const tbody = $("<tbody></tbody>");
        $.each(data.users, function(index, item) {
          const row = $("<tr class='border-bottom-success'></tr>");
          row.append("<td align='center'>" + (item.status === "Active" ? "<i class='fa fa-check'></i>" : "<i class='fa fa-times'></i>") + "</td>");
          row.append("<td>" + item.username + "</td>");
          row.append("<td>" + item.password + "</td>");
          row.append("<td>" + item.level + "</td>");
          row.append("<td>" + formatCurrency(item.balance) + "</td>"); // Format the balance as currency
          row.append("<td>" + item.registered + "</td>");
          row.append("<td>" + item.uplink + "</td>");
          row.append("<td>" + item.api_key + "</td>");
          row.append("<td align='center'>" +
            "<a class='btn btn-xs btn-warning' data-bs-toggle='modal' data-bs-target='#editusernya"+item.username+"'><i class='fa fa-edit'></i></a> " +
            "<div class='modal fade' id='editusernya"+item.username+"' 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'>Username</label> <input type='text' class='form-control' value='"+item.username+"' name='username' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Password</label> <input type='text' class='form-control' name='password' placeholder='Password' value='"+item.password+"' required> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Email address</label> <input class='form-control' id='exampleFormControlInput1' type='email' name='email' value='"+item.email+"'> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>No. Wangsaff</label> <input class='form-control' id='exampleFormControlInput1' type='number' name='nohp' value='"+item.nohp+"'> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Balance</label> <input type='text' class='form-control' name='balance' placeholder='Password' value='"+item.balance+"' required> </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='Member'>Member</option><option value='Admin'>Admin</option></select> </div><div class='col-md-12'> <label class='form-label' for='validationCustom02'>Status</label> <select class='form-control' name='status'> <option value='"+item.status+"'>"+item.status+"</option> <option value='Active'>Active</option><option value='Suspended'>Suspended</option></select> </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='#deleteusernya"+item.username+"'><i class='fa fa-trash-o'></i></a> " +
            "<div class='modal fade' id='deleteusernya"+item.username+"' 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 User</h3> <div class='modal-body'> <form class='row g-3' method='POST'> <div class='col-md-6'> <label class='form-label' for='validationCustom01'>Username</label> <input type='text' class='form-control' value='"+item.username+"' name='username' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Password</label> <input type='text' class='form-control' name='password' placeholder='Password' value='"+item.password+"' readonly> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Email address</label> <input class='form-control' id='exampleFormControlInput1' type='email' name='email' value='"+item.email+"' readonly> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>No. Wangsaff</label> <input class='form-control' id='exampleFormControlInput1' type='number' name='nohp' value='"+item.nohp+"' readonly> </div> <div class='col-md-12'> <button class='btn btn-danger' type='submit' name='delete'>Hapus 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-users").val().trim());
    }
  }

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