<?php
session_start();
require("../mainconfig.php");
$datetime = new DateTime( "now", new DateTimeZone( "Asia/Jakarta" ) );
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");
	}

	include("../lib/header.php");
	$msg_type = "nothing";

	if (isset($_POST['order'])) {
		$post_service = $_POST['service'];
		$post_quantity = $_POST['quantity'];
		$post_link = trim($_POST['link']);
		$check_service = mysqli_query($db, "SELECT * FROM services WHERE sid = '$post_service' AND status = 'Active'");
		$data_service = mysqli_fetch_assoc($check_service);

        $check_orders = mysqli_query($db, "SELECT * FROM orders WHERE link = '$post_link' AND status IN ('Pending','Processing')");
        $data_orders = mysqli_fetch_assoc($check_orders);
        if (($data_service['min'] == 1) && ($data_service['max'] == 1)) {
		    $rate = $data_service['price'];
		} else {
		    $rate = $data_service['price'] / 1000;
		}
		$price = $rate*$post_quantity;
		$oid = random_number(3).random_number(4);
		$service = $data_service['service'];
		$provider = $data_service['provider'];
		$pid = $data_service['pid'];

		$check_provider = mysqli_query($db, "SELECT * FROM provider WHERE code = '$provider'");
		$data_provider = mysqli_fetch_assoc($check_provider);

		if (empty($post_service) || empty($post_link) || empty($post_quantity)) {
			$msg_type = "error";
			$msg_content = '<b>Gagal:</b> Mohon mengisi input.<script>swal("Error!", "Mohon mengisi input.", "error");</script>';
		} else if (mysqli_num_rows($check_orders) == 1) {
		    $msg_type = "error";
		    $msg_content = '<b>Gagal:</b> Terdapat orderan username yang sama dan berstatus pending/processing.<script>swal("Error!", "Terdapat orderan yang sama.", "error");</script>';
		} else if (mysqli_num_rows($check_service) == 0) {
			$msg_type = "error";
			$msg_content = '<b>Gagal:</b> Layanan tidak ditemukan.<script>swal("Error!", "Layanan tidak ditemukan.", "error");</script>';
		} else if (mysqli_num_rows($check_provider) == 0) {
			$msg_type = "error";
			$msg_content = '<b>Gagal:</b> Server Maintenance.<script>swal("Error!", "Server maintenance.", "error");</script>';
		} else if ($post_quantity < $data_service['min']) {
			$msg_type = "error";
			$msg_content = '<b>Gagal:</b> Jumlah minimal tidak sesuai.<script>swal("Error!", "Jumlah tidak sesuai.", "error");</script>';
		} else if ($post_quantity > $data_service['max']) {
			$msg_type = "error";
			$msg_content = '<b>Gagal:</b> Jumlah maksimal tidak sesuai.<script>swal("Error!", "Jumlah tidak sesuai.", "error");</script>';
		} else if ($data_user['balance'] < $price) {
			$msg_type = "error";
			$msg_content = '<b>Gagal:</b> Saldo Anda tidak mencukupi untuk melakukan pembelian ini.<script>swal("Error!", "Saldo tidak mencukupi.", "error");</script>';
		} else {

			// api data
			$api_link = $data_provider['link'];
			$api_key = $data_provider['api_key'];
			// end api data

			if ($provider == "MANUAL") {
				$api_postdata = "";
			} else if ($provider == "SMMKITA") {
                $postdata = "api_id=2068&api_key=aa9f8e-bb2b3f-61fa01-587b63-188230&service=$pid&target=$post_link&quantity=$post_quantity&custom_comments=".$_POST['comment'];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, "https://irvankedesmm.co.id/api/order");
                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);
                curl_close($ch);
                    $json_result = json_decode($chresult);
			} else {
				die("System Error!");
			}

			if ($provider == "SMMKITA" AND $json_result->status == false) {
				$msg_type = "error";
				$msg_content = "<b>Failed:</b> ".$json_result->data->msg." .";
			} else {
				if ($provider == "SMMKITA") {
					$poid = $json_result->data->id;
				} else if ($provider == "MANUAL") {
					$poid = $oid;
				}
				    $ubah_penulisan = number_format($price,0,',','.');
				    $send = mysqli_query($db, "INSERT INTO balance_history(username, action, quantity, msg, tanggal) VALUES ('$sess_username','Cut Balance','$price','Kamu telah berhasil melakukan Pembelian dengan harga Rp $ubah_penulisan','$date $time')");
                    $update_user = mysqli_query($db, "UPDATE users SET balance = balance-$price WHERE username = '$sess_username'");
					$update_user = mysqli_query($db, "INSERT INTO catatan (username, note, waktu) VALUES ('$sess_username', 'Kamu telah melakukan aktifitas Order $service', '$date $time')");
					$check_top = mysqli_query($db, "SELECT * FROM top_user WHERE username = '$sess_username'");
					$data_top = mysqli_fetch_assoc($check_top);
				if ($update_user == TRUE) {
				    if (mysqli_num_rows($check_top) == 0) {
				        $insert_order = mysqli_query($db, "INSERT INTO top_user (method, username, jumlah, total) VALUES ('Order', '$sess_username', '$price', '1')");
				    } else {
				        $insert_order = mysqli_query($db, "UPDATE top_user SET jumlah = ".$data_top['jumlah']."+$price, total = ".$data_top['total']."+1 WHERE username = '$sess_username' AND method = 'Order'");
				    }
				    $date = $datetime->format( 'Y-m-d H:i:s' );
					$insert_order = mysqli_query($db, "INSERT INTO orders (oid, poid, user, service, link, quantity, price, status, date, provider, place_from) VALUES ('$poid', '$poid', '$sess_username', '$service', '$post_link', '$post_quantity', '$price', 'Pending', '$date', '$provider', 'WEB')");
					if ($insert_order == TRUE) {
						$msg_type = "success";
						$msg_content = "<b>Pesanan telah diterima.</b><br /><b>ID Pesanan:</b> $poid<br /><b>Layanan:</b> $service<br /><b>Link:</b> $post_link<br /><b>Jumlah:</b> ".number_format($post_quantity,0,',','.')."<br /><b>Biaya:</b> Rp ".number_format($price,0,',','.');
					} else {
						$msg_type = "error";
						$msg_content =  '<b>Gagal:</b> Error system (2).<script>swal("Error!", "Error system.", "error");</script>';
					}
				} else {
					$msg_type = "error";
					$msg_content = '<b>Gagal:</b> Error system (1).<script>swal("Error!", "Error system.", "error");</script>';
				}
			}
		}
	}
	
	$check_user = mysqli_query($db, "SELECT * FROM users WHERE username = '$sess_username'");
	$data_user = mysqli_fetch_assoc($check_user);
?>
<div class="page-body"> 
<?php include('../lib/partial/breadcrumb.php') ?>
   <!-- Container-fluid starts-->
   <div class="container-fluid">
       <?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="row">
           <div class="col-xl-7 col-sm-12">
                <div class="card">
                  <form class="form theme-form dark-inputs" method='POST'>
                    <div class="card-body">
                      <div class="row">
                        <div class="col">
                          <div class="mb-3">
                            <label class="form-label">Category</label>
                        <select class="form-select btn-pill digits" id="category">
														<option value="0">Pilih salah satu...</option>
														<?php
														$check_cat = mysqli_query($db, "SELECT * FROM service_cat ORDER BY name ASC");
														while ($data_cat = mysqli_fetch_assoc($check_cat)) {
														?>
														<option value="<?php echo urlencode($data_cat['code']); ?>"><?php echo $data_cat['name']; ?></option>
														<?php
														}
														?>
													</select>
                          </div>
                        </div>
                      </div>
                      <div class="row">
                        <div class="col">
                          <div class="mb-3">
                            <label class="form-label">Service</label>
                        <select class="form-select btn-pill digits" name="service" id="service">
														<option value="0">Pilih Service...</option>
													</select>
                          </div>
                        </div>
                      </div>
                            <div id="note"></div>
                      <div class="row">
                        <div class="col">
                          <div class="mb-3">
                            <label class="form-label">Link/Username</label>
						    <input type="text" name="link" class="form-control btn-pill digits" placeholder="Link/Target">
                          </div>
                        </div>
                      </div>
                      <div class="row"> 
                        <div id="show1" style="display: none">
                    	<div class="mb-3">
                        <label class="form-label">Komentar</label>
						<textarea class="form-select btn-square" id="comments" placeholder="Pisahkan tiap baris komentar dengan enter" name="comment" rows="5"></textarea>
                            </div>
                    	</div>
                      </div>
                      <div class="row">
                        <div class="col">
                         <div class="mb-3">
                          <div>
                            <label class="form-label">Jumlah</label>
                            <input type="number" name="quantity" id="quantity" class="form-control btn-pill digits" placeholder="Jumlah" onkeyup="get_total(this.value).value;">
                          </div>
                         </div>
                        </div>
                      </div>
                      <div class="row">
                        <div class="col">
                          <div>
                            <input type="hidden" id="rate" value="0">
                          </div>
                        </div>
                      </div>
                      <div class="row">
                        <div class="col">
                          <div class="mb-3">
                            <label class="form-label">Harga</label>
						    <input type="number" class="form-control btn-pill digits" id="total" readonly>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="card-footer text-end">
                      <button class="btn btn-primary me-3" type="submit" name='order'>Order</button>
                      <input class="btn btn-light" type="reset" value="Cancel">
                    </div>
                  </form>
                </div>
              </div>
              <div class="col-xl-5 col-sm-12">
                  <div class="card">
            <div class="card-body">

                <center>
                    <h8 class="m-t-0 text-uppercase header-title"><i aria-hidden="true" class="fa fa-info-circle"></i><b> Informasi Order</h8></b><br/>
                    Gunakan koneksi internet yang stabil agar daftar layanan sinkron dengan kategori yang dipilih.
                    <hr>
                </center>

                <!--KETENTUAN-->
                <div class="table-responsive">
                    <center><i aria-hidden="true" class="fa fa-check-circle"></i><b> S&K</b></center>
                    <ol class="list-p">
                        <li>Kesalahan input & order pending / processing tidak dapat di cancel.</li>
                        <li>Order baru untuk layanan & target yang sama, tunggu status sebelumnya <span class="badge badge-success"><b>Success</b></span>.</li>
                        <li>Tidak bisa melakukan double order.</li>
                        <li>Kecepatan Rata² adalah hasil dari rata rata orderan layanan tersebut selesai, Orderan anda mungkin bisa lebih cepat ataupun lebih lama untuk selesai.</li>
                    </ol>
                </div>

                <!--CARA-->
                <div class="table-responsive">
                    <center><i aria-hidden="true" class="fa fa-check-circle"></i><b> Cara Melakukan Order</b></center>
                    <ol class="list-p">
                        <li>Pilih salah satu kategori & layanan.</li>
                        <li>Masukkan username / url pada target.</li>
                        <li>Masukkan jumlah pemesanan</li>
                        <li>Klik <span class="badge badge-primary"><b>Order</b></span> untuk memesan.</li>
                    </ol>
                </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 type="text/javascript">
  $(document).ready(function() {
    $("#category").change(function() {
      var category = $("#category").val();
      $.ajax({
        url: '<?php echo $cfg_baseurl; ?>lib/order',
        data: 'category=' + category,
        type: 'POST',
        dataType: 'html',
        success: function(msg) {
          $("#service").html(msg);
          $("#show1").hide();
          updateQuantity(); // Update quantity when category changes
        }
      });
    });

    $("#service").change(function() {
      var service = $("#service").val();
      $.ajax({
        url: '<?php echo $cfg_baseurl; ?>lib/order',
        data: 'service1=' + service,
        type: 'POST',
        dataType: 'html',
        success: function(msg) {
          $("#note").html(msg);
        }
      });
      $.ajax({
        url: '<?php echo $cfg_baseurl; ?>lib/order',
        data: 'service=' + service,
        type: 'POST',
        dataType: 'html',
        success: function(msg) {
          $("#rate").val(msg);
        }
      });

      var selectedCountry = $("#service option:selected").text();
      // Check if the selected service contains 'custom', 'comment', or 'comments'
      if ((selectedCountry.toLowerCase().indexOf('comments') !== -1 && selectedCountry.toLowerCase().indexOf('custom') !== -1) || (selectedCountry.toLowerCase().indexOf('comment') !== -1 && selectedCountry.toLowerCase().indexOf('custom') !== -1)) {
        $("#show1").show();
        $('#quantity').prop('readonly', true);
      } else {
        $("#show1").hide();
        $('#quantity').prop('readonly', false);
      }

      updateQuantity(); // Update the quantity based on comment textarea lines
    });

    // Add event listener for the textarea input to update quantity
    $("#comments").on("input", function() {
      updateQuantity();
    });
  });

  function updateQuantity() {
    var comment = $("#comments").val();
    var commentLines = comment.split('\n').length;
    var rate = $("#rate").val();
    var result = eval(commentLines) * rate;
    $('#quantity').val(commentLines);
    $('#total').val(result);
  }
  
  function get_total(quantity) {
	var rate = $("#rate").val();
	var result = eval(quantity) * rate;
	$('#total').val(result);
}
</script>
<?php
	include("../lib/footer.php");
} else {
	header("Location: ".$cfg_baseurl);
}
?>