<?php
session_start();
require("../mainconfig.php");
require("../lib/phpqrcode/custom_qris.php");
function cek_status($nominal){
$url = 'https://app.orderkuota.com/api/v2/get';
$postdata = http_build_query(
    array(
        "auth_username" => "anugrahkim28",
        "requests[qris_history][keterangan]" => "",
        "requests[0]" => "account",
        "app_version_name" => "23.02.01",
        "requests[qris_history][ke_tanggal]" => "",
        "requests[qris_history][jenis]" => "kredit",
        "app_version_code" => "230201",
        "requests[qris_history][page]" => "1",
        "auth_token" => "1531673:TP7tr5S8QIM3bRBezswNnX1KlWuOvgDF",
        "requests[qris_history][jumlah]" => "$nominal",
        "requests[qris_history][dari_tanggal]" => "",
        "app_reg_id" => "f-AvO7cUSnSvRPF3RFgb6B:APA91bFspd07dCqCv9yyhMUy9D7l24X0fmoc6Trl1fYLLd5DiK4ocakjigpa6hqriQ0E3o6QcpHVymXz6WTmKQI7ZilOXS4hBVytZo4DlZ-tahYZy1sP68YatGuzIUMosU7oXRuZ16G9"
    )
);
$headers = array(
    'Content-type: application/x-www-form-urlencoded',
    "User-Agent:okhttp/4.10.0"
);
$options = array(
    'http' => array(
        'header' => implode("\r\n", $headers),
        'method' => 'POST',
        'content' => $postdata
    )
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$hasil = json_decode($response)->qris_history->results[0]->kredit;
if(!$hasil){
    $cek_status = "tidak ketemu";
} else if ($hasil = $nominal){
    $cek_status = "ketemu";
} else {
    $cek_status = "error";
    } return $cek_status;
}

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");
	$check_status = mysqli_query($db, "SELECT * FROM topup WHERE username = '$sess_username' AND status = 'Waiting'");
	$cek_status = mysqli_fetch_assoc($check_status);
	
	//WAKTU
    $detikWaktuDiberikan = strtotime($cek_status['tanggal']);
    $detikWaktuSaatIni = strtotime(date("Y-m-d H:i:s"));
    $batasWaktu = $detikWaktuSaatIni - (20 * 60); // Mengurangkan detik untuk membuat waktu mundur
    $selisihDetik = $detikWaktuDiberikan - $batasWaktu;
	//WAKTU
	
	$check_token = mysqli_query($db, "SELECT * FROM akun_qris");
	$cek_token = mysqli_fetch_assoc($check_token);
	
	$msg_type = "nothing";
	$rate = $cek_token['rate'];
	$bonusnya = ((($cek_status['jumlah'] - $cek_status['kode_unik']) / $rate) * $rate) - (($cek_status['jumlah'] - $cek_status['kode_unik']) / $rate);
	$yang_dibayar = (($cek_status['jumlah'] - $cek_status['kode_unik']) / $rate) + $cek_status['kode_unik'];

	if (isset($_POST['deposit'])) {
	    if(is_numeric($_POST['quantity']) == FALSE){
	        $msg_type = "error";
	        $msg_content = "Error, Hanya dapat memasukkan angka";
	    } else if ($_POST['quantity'] < 1000){
	        $msg_type = "error";
	        $msg_content = "Error, Minimal Topup saldo adalah Rp. 5000";
	    } else if (mysqli_num_rows($check_status) == 1){
	        ?> <meta http-equiv="refresh" content="0;URL=<?= $cfg_baseurl ?>pages/deposit" /> <?
	    } else {
	    $kode_uniknya = rand(1, 999);
		$post_quantity = ($_POST['quantity'] * $rate) + $kode_uniknya;
		$insert_deposit = mysqli_query($db, "INSERT INTO topup (username, jumlah, kode_unik, status, tanggal) VALUES ('$sess_username', '$post_quantity', '$kode_uniknya', 'Waiting', '$date $time')");
		?> <meta http-equiv="refresh" content="0;URL=<?= $cfg_baseurl ?>pages/deposit" /> <?
	    }
	} else if (isset($_POST['cek_pembayaran'])) {
        $outputnya = cek_status($yang_dibayar); 
            
            if ($outputnya == "ketemu"){
              $tambah_saldo = ($data_user['balance'] + $cek_status['jumlah']) - $cek_status['kode_unik'] + ($cek_status['kode_unik'] * $rate);
              $untuk_quantity = $cek_status['jumlah'] - $cek_status['kode_unik'] + ($cek_status['kode_unik'] * $rate);
              $ubah_penulisan = number_format($cek_status['jumlah'] - $cek_status['kode_unik'] + ($cek_status['kode_unik'] * $rate),0,',','.');
              $hadehh = $cek_status['jumlah'];
              $updateSaldo = mysqli_query($db,"UPDATE users SET balance = '$tambah_saldo' WHERE username = '$sess_username'");
              $updatedbnya = mysqli_query($db,"UPDATE topup SET status = 'Completed' WHERE username = '$sess_username' AND status = 'Waiting'");
              $send = mysqli_query($db, "INSERT INTO balance_history(username, action, quantity, msg, tanggal) VALUES ('$sess_username','Add Balance','$untuk_quantity','Kamu telah berhasil melakukan Topup saldo sebesar Rp $ubah_penulisan','$date $time')");
              $insert_tf = mysqli_query($db, "INSERT INTO catatan (username, note, waktu) VALUES ('$sess_username', 'Kamu telah berhasil melakukan Topup saldo sebesar $ubah_penulisan', '$date $time')");
              $msg_type = "success";
              $msg_content = "Data Topup ditemukan, Topup Berhasil";
            } else {
              $msg_type = "error";
              $msg_content = "Error, Data Topup tidak ketemu, mohon segera transfer sesuai nominal, jika terkendala, hubungi Admin";
            }

	} else if (isset($_POST['batalkan_pembayaran'])) {
	          $updatedbnya = mysqli_query($db,"UPDATE topup SET status = 'Canceled' WHERE username = '$sess_username' AND status = 'Waiting'");
              $insert_tf = mysqli_query($db, "INSERT INTO catatan (username, note, waktu) VALUES ('$sess_username', 'Kamu membatalkan Topup saldo sebesar $ubah_penulisan', '$date $time')");
              $msg_type = "success";
              $msg_content = "Pembatalan Transaksi Berhasil";
              ?> <meta http-equiv="refresh" content="2"> <?
	}
	
	if (mysqli_num_rows($check_status) == 0){ 
?>
<div class="page-body"> 
<?php include('../lib/partial/breadcrumb.php') ?>
   <!-- Container-fluid starts-->
   <div class="container-fluid">
            <div class="row justify-content-center">
              <div class="col-xl-12">
                  <?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="card height-equal">
                  <div class="card-body custom-input">
                    <form class="row g-3" method='POST'>
                        <div class="alert alert-info">
                                                <!----<b>EVENT DADAKAN | BONUS DEPOSIT 10%</b>--->
                                                
                                               <b>KHUSUS TOP UP SALDO MINIMAL RP. 500.000 BONUS 8% <br/>
                                               KHUSUS TOP UP SALDO MINIMAL RP. 2.500.000 BONUS 13% <br/>
                                               SILAHKAN HUBUNGI ADMIN</b>
                                               
                                               <br/>
												- TopUp Saldo tidak masuk? Hubungi Admin.<br />
												- Minimal Isi saldo Rp <?php echo number_format($cfg_min_transfer,0,',','.'); ?>.<br />
												- Pembayaran VIA QRIS, Mohon Masukkan Jumlah Dengan Benar
											</div>
                      <div class="col-12">
    <label class="form-label">Jumlah</label>
    <input type="number" name="quantity" id="quantity" class="form-control" placeholder="Jumlah" onkeyup="get_total(this.value).value;" required>
  </div>
  <input type="hidden" id="rate" value="0">
                      <div class="col-12"> 
                        <label class="form-label">Saldo Didapat</label>
						<input type="number" class="form-control" id="total" readonly>
                      </div>
                      <div class="col-12">
                        <button class="btn btn-primary" type="submit" name='deposit'>Submit</button>
                      </div>
                    </form>
                  </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">
  function get_total(quantity) {
	var result = eval(quantity) * <?= $rate?>;
	$('#total').val(result);
}
</script>

<?php
} else { ?>
<div class="page-body checkout"> 
<?php include('../lib/partial/breadcrumb.php') ?>
   <!-- Container-fluid starts-->
   <div class="container-fluid">
            <div class="card">
              <div class="card-header">
                <h5>Billing Details</h5>
              </div>
              <div class="card-body">
                  <?php 
											if ($msg_type == "success") {
											?>
											<div class="alert alert-success dark" role="alert">
                      <p><?php echo $msg_content; ?></p>
                    </div>
                    <meta http-equiv="refresh" content="3;URL=<?= $cfg_baseurl ?>pages/deposit" />
											<?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-6 col-sm-12">
                            <img src="<?= $cfg_baseurl; ?>/lib/qrcode.php?s=qr&d=<?= generate_qrisnya($yang_dibayar) ?>&w=540&h=540" width="100%" height="100%">
                        </div>
                  <div class="col-xl-6 col-sm-12">
                    <div class="checkout-details">
                      <div class="order-box">
                      <div class="alert alert-info">
                      - Pastikan QRIS a/n <b>ANUGRAH STORE</b>, selain itu bisa dipastikan <b>ANDA SALAH TRANSFER</b>.<br />
					  - Mohon bayar sesuai <b>Total yang harus dibayar.</b><br />
					  - Nominal tersebut 100% akan menjadi saldo kamu
					  </div>
                        <div class="title-box">
                          <div class="checkbox-title">
                            <h4>Payment </h4><span>Total</span>
                          </div>
                        </div>
                        <ul class="qty">
                          <li><p id="carasingkat" data-count="<?= $selisihDetik; ?>" class="text-danger"><?= $selisihDetik; ?></p></li>
                          <li>TopUp Balance <span><?= ($cek_status['jumlah'] - $cek_status['kode_unik']) / $rate; ?></span></li>
                          <li>Kode Unik <span><?= $cek_status['kode_unik']; ?></span></li>
                          <li>Bonus <span><?= $bonusnya; ?></span></li>
                        </ul>
                        <ul class="sub-total">
                          <li>Total yang harus dibayar<span class="count"><?= $yang_dibayar; ?></span></li>
                        </ul>
                        <!---
                        <ul class="sub-total total">
                          <li>Saldo Didapat(+ Bonus jika ada) <span class="count"><?= $cek_status['jumlah']; ?></span></li>
                        </ul>
                        --->
                        <form method="POST"><div class="order-place"><button class="btn btn-success" type="submit" name="cek_pembayaran">Cek Pembayaran Sekarang!  </button></div></form>
                        <form method="POST"><div class="order-place"><button id="batalkanBtn" class="btn btn-danger" type="submit" name="batalkan_pembayaran">Batalkan Sekarang!  </button></div></form>
                      </div>
                    </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>
    var count = parseInt($('#carasingkat').data('count')); // ambil nilai count dari data attribute

    function countDown() {
        if (count > 0) {
            var menit = Math.floor(count / 60);
            var detik = count % 60;

            var waktu = menit + ":" + (detik < 10 ? "0" : "") + detik;
            $('#carasingkat').html('<b>BATAS WAKTU PEMBAYARAN '+waktu+' MENIT </b> ');
            count--;

            setTimeout(countDown, 1000);
        } else {
            document.getElementById('batalkanBtn').click();
        }
    }

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