<?php
session_start();
require("../mainconfig.php");
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);
	
	$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'])) {
	    $apa = $yang_dibayar - ($yang_dibayar * 0.3 / 100);
	    $no=1;
        $tokennya = $cek_token['token'];
        $hari_ini = date('Y-m-d');
        $kmaren_kmaren = date('Y-m-d', strtotime('-4 days'));
        do {
        $url = "https://pos.indibizpay.id/api/v1/transaction/history?start_date=$kmaren_kmaren&end_date=$hari_ini&category_transaction=QRIS&page=$no";
        
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        
        $headers = array(
           "Authorization: Bearer $tokennya",
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        //for debug only!
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        
        $resp = curl_exec($curl);
        curl_close($curl);
        $tes = json_decode($resp, true)['data']['data'];
        $acuan = json_decode($resp, true)['data']['to'];
        foreach ($tes as $key) {
            $pisah_titik = explode('.',$key['total_price'])[0];
            if ($pisah_titik == ceil($apa)) {
                $outputnya = "ketemu";
                    } 
                } $no++;
            } while ($acuan != NULL);
            
            if ($outputnya == "ketemu"){
              $ubah_penulisan = number_format($apa,0,',','.');
              $tambah_saldo = $data_user['balance'] + $cek_status['jumlah'];
              $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','$hadehh','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 $apa', '$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 $apa', '$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; ?>/assets/qris_borneo.png" 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>TOKO SABLON BORNEO MEDIA</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>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 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>
<? }
	include("../lib/footer.php");
} else {
	header("Location: ".$cfg_baseurl);
}
?>