<?php
session_start();
require '../config.php';
require '../lib/session_user.php';
if (isset($_POST['pesan'])) {
	require '../lib/session_login.php';
	$post_operator = $conn->real_escape_string(trim(filter($_POST['operator'])));
	$post_layanan = $conn->real_escape_string(trim(filter($_POST['layanan'])));
	$post_target = $conn->real_escape_string(trim(filter($_POST['target'])));
	$post_nometer = $conn->real_escape_string(trim(filter($_POST['nometer'])));

	$cek_layanan = $conn->query("SELECT * FROM layanan_ppob WHERE provider_id = '$post_layanan' AND status = 'Normal'");
	$data_layanan = mysqli_fetch_assoc($cek_layanan);

	$order_id = acak_nomor(3).acak_nomor(4);
	$provider = $data_layanan['provider'];

	$cek_provider = $conn->query("SELECT * FROM provider WHERE code = '$provider'");
	$data_provider = mysqli_fetch_assoc($cek_provider);
	
	$cek_wa = $conn->query("SELECT * FROM bot_whatsapp WHERE status = 'Aktif'");
    $data_wa_bot = $cek_wa->fetch_assoc();
    
    $nilai_coin = $conn->query("SELECT * FROM penukaran_coin WHERE tipe = 'Deposit' ");
    $data_coin = $nilai_coin->fetch_assoc();
    $set_coin = $data_coin['coin_pemesanan'];

	$cek_pesanan = $conn->query("SELECT * FROM pembelian_ppob WHERE user = '$sess_username' AND target = '$post_target' AND status = 'Pending' AND provider = '$provider'");
	$data_pesanan = mysqli_fetch_assoc($cek_pesanan);

	if (!$post_target || !$post_layanan || !$post_operator) {
		$_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Order Gagal', 'pesan' => 'Masih Ada Form Kosong');

	} else if (mysqli_num_rows($cek_layanan) == 0) {
		$_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Order Gagal', 'pesan' => 'Produk Tidak Tersedia');

	} else if (mysqli_num_rows($cek_provider) == 0) {
		$_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Order Gagal', 'pesan' => 'Server Sedang Maintenance');

	} else if ($data_user['saldo'] < $data_layanan['harga']) {
		$_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Order Gagal', 'pesan' => 'Saldo Tidak Mencukupi');

	} else if (mysqli_num_rows($cek_pesanan) == 1) {
		$_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Order Gagal', 'pesan' => 'Orderan Sebelumnya di Produk & Target yang Sama Masih Pending');

	} else {

		$api_link = $data_provider['link'];
		    $api_key = $data_provider['api_key'];
		    $api_id = $data_provider['api_id'];

		    if ($provider == "MANUAL") {
			    $api_postdata = "";
		    } else if ($provider == "DIGIFLAZZ") {
		    $sign = md5($api_id.$api_key.$order_id);
            $api_postdata = array( 
            	'username' => $api_id,
            	'buyer_sku_code' => $data_layanan['provider_id'],
            	'customer_no' => "$post_target",
            	'ref_id' => $order_id,
            	'sign' => $sign
            );
            $header = array(
                'Content-Type: application/json',
            );
			} else {
				die("System Error!");
			}

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($api_postdata));
                $chresult = curl_exec($ch);
                curl_close($ch);
                $json_result = json_decode($chresult, true);
                $result = json_decode($chresult);
                // print_r($result);

			    if ($provider == "DIGIFLAZZ" && $json_result['data']['status'] == "Gagal") {
		            $_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Order Gagal', 'pesan' => 'Gagal, '.$json_result['data']['message']);
			    } else {

			        if ($provider == "DIGIFLAZZ") {
		                $provider_oid = $order_id;
			        }
				if ($conn->query("INSERT INTO pembelian_ppob VALUES ('','$order_id', '$provider_oid', '$sess_username', '".$data_layanan['layanan']."', '".$data_layanan['harga']."', '".$data_layanan['profit']."', '$post_target', '$post_nometer', '$pesan', 'Pending', '$date', '$time', 'Website', '$provider', '0')") == true) {

					$conn->query("UPDATE users SET saldo = saldo-".$data_layanan['harga'].", pemakaian_saldo = pemakaian_saldo+".$data_layanan['harga']." WHERE username = '$sess_username'");
					$conn->query("INSERT INTO history_saldo VALUES ('', '$sess_username', 'Pengurangan Saldo', '".$data_layanan['harga']."', 'Order ID $order_id Pulsa Reguler', '$date', '$time')");
					$conn->query("UPDATE referral_kode SET coin = coin+$set_coin WHERE username = '".$sess_username."'");

					$harga = number_format($data_layanan['harga'],0,',','.');
					$_SESSION['hasil'] = array(
						'alert' => 'success',
						'judul' => 'Order Berhasil', 
						'pesan' => 'Terimakasih </b>'.$sess_username.'<br /> 
						<b>Order ID : </b> '.$order_id.'<br />
						<b>Layanan : </b> '.$data_layanan['layanan'].'<br />
						<b>Target : </b> '.$post_target.'<br />
						<b>Harga : </b> Rp. '.$harga.'');
						// PESAN WA
                 $target = $data_user['nomer'] ;
                 $waktu_order = (tanggal_indo($date));
                 $token_whatsapp =  $data_wa_bot ['token_wa'] ;
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                    CURLOPT_URL => 'https://api.fonnte.com/send',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => array(
                    'target' => $target,
                    'message' => "INVOICE ORDER PERTAGAS\n\n𝙄𝘿 : $order_id\nTanggal : $waktu_order - $time WIB\nLayanan : ".$data_layanan['layanan']."\nHarga : $harga\nTujuan : $post_target",
                    ),
                    CURLOPT_HTTPHEADER => array(
                    "Authorization: $token_whatsapp " //change TOKEN to your actual token
                    ),
                    ));
                    
                    $response = curl_exec($curl);
                    curl_close($curl);
				} else {
					$_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Order Gagal', 'pesan' => 'Pemesanan gagal');
				}
			}
		}
 header("Location: " . $_SERVER['REQUEST_URI'] . "");
    exit();
}

require("../lib/header.php");
?>
<div class="content-wrapper">

    <?php
    //$date = date("Y-m-d");
    $cek_berita = $conn->query("SELECT * FROM berita ORDER BY id DESC");
    if (mysqli_num_rows($cek_berita) != "0") {
    ?>
        <div class="row">
            <div class="col-lg-12">
                <div class="alert alert-dark alert-dismissible" role="alert">
                    <button type="button" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                    <strong><i class="mdi mdi-bell-ring"></i> Informasi Terbaru!</strong>
                    <marquee style="max-height:25px" behavior="scroll" onmouseover="this.stop();" onmouseout="this.start();">
                        <p style="font-size: 12pt">
                            <?php
                            while ($data_berita = $cek_berita->fetch_assoc()) {
                            ?>
                                <b><?php echo $data_berita['subjek']; ?> - </b> <?php echo $data_berita['konten']; ?>
                            <?php } ?>
                        </p>
                    </marquee>
                </div>
            </div>
        </div>
    <?php } else { ?>
    <?php } ?>

    <div class="row">
        <div class="col-lg-12">
            <div class="alert alert-dark">-Baca <b>Informasi</b> yang terletak dikanan (PC/Tablet) / dibawah (Smartphone) form sebelum melakukan pemesanan.</div>
        </div>
    </div>
    <?php
    if (isset($_SESSION['hasil'])) {
    ?>
        <div class="alert alert-<?php echo $_SESSION['hasil']['alert'] ?>">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <b><?php echo $_SESSION['hasil']['judul'] ?></b> <?php echo $_SESSION['hasil']['pesan'] ?>
        </div>
    <?php
        unset($_SESSION['hasil']);
    }
    ?>
    <div class="row">
        <div class="col-md-6 grid-margin">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">- Pemesanan PERTAGAS</h4>
                    <form class="forms-sample" method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo $config['csrf_token'] ?>">
                        <div class="form-group">
                            <label>Pilih Kategori</label>
                            <select class="js-example-basic-single" name="operator" id="operator" style="width:100%">
                                <option value="">Pilih Kategori Produk...</option>
                                <?php
								$cek_kategori = $conn->query("SELECT * FROM kategori_ppob WHERE tipe IN ('Pertagas') ORDER BY nama ASC");
								while ($data_kategori = $cek_kategori->fetch_assoc()) {
									?>
									<option value="<?php echo $data_kategori['kode']; ?>"><?php echo $data_kategori['nama']; ?></option>
								<?php } ?>	
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Pilih Layanan</label>
                            <select class="js-example-basic-single" name="layanan" id="layanan" style="width:100%">
                                <option value="0">Pilih Layanan...</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <div id="catatan"></div>
                        </div>
                        <div class="form-group">
                            <label for="target">ID Pelanggan</label>
                            <input type="number" class="form-control" id="target" name="target" placeholder="ID / No.Tujuan">
                        </div>
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Total Harga</span>
                                    </div>
                                    <input type="text" class="form-control" id="harga" readonly style="background: #000;">
                                    <div class="input-group-append">
                                        <span class="input-group-text">IDR</span>
                                    </div>
                                </div>
                            </div>
                        <button type="reset" class="btn btn-dark mr-2">Cancel</button>
                        <button type="submit" name="pesan" class="btn btn-info float-right">Order Sekarang</button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-md-6 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">- RULES ORDER</h4>
                    <ul>
                        <li>Pilih salah satu Kategori Layanan.</li>
						<li>Pilih salah satu Layanan yang ingin dipesan.</li>
						<li>Masukkan Target pesanan Contoh Pulsa: 083191910986 / Token Pln: 252738138 dll. Untuk Mengecek No Token PLN Cek Di Riwayat Pemesanan PPOB</li>
						<li>Untuk Pembelian Voucer Games Masukan Id Akun Langsung, Misal Mobile Legends Gabungkan Id Dan Zone-Id Contoh ID: 2600 ID-Zone:334 Masukan Ke Target Pesanan : 2600334</li>
						<li>Klik Submit untuk membuat pesanan baru</li>
                        <li>Dengan melakukan orderan Anda dianggap sudah memahami dan setuju <a href="/halaman/syarat-ketentuan">Syarat dan Ketentuan</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

</div>
<style>
    .menubottom {
        display: none
    }

    @media screen and (max-width:800px) {
        .menubottom {
            position: relative
                /*fixed*/
            ;
            right: 0;
            left: 0;
            z-index: 500;
            bottom: 0
        }

        .menubottom nav ul {
            display: flex !important;
            width: 100% !important;
            padding-left: 0;
            justify-content: space-between !important;
            margin-bottom: 0;
            flex-direction: row !important;
            list-style: none
        }

        .menubottom nav ul li {
            width: 100% !important;
            list-style: none;
        }

        .menubottom nav ul li a {
            display: block;
            text-decoration: none;
            padding: .4rem 1rem
        }

        .menubottom nav ul li a svg {
            width: 25px;
            height: 25px;
            fill: #9aa3a9;
        }

        .menubottom nav ul li a span {
            color: #4b4f56;
            position: relative;
            font-size: 8px;
            display: block;
            top: -5px padding-top: 5px;
        }
    }

    @media screen and (max-width:768px) {
        .menubottom {
            left: 0;
            text-align: center;
            width: 100%;
            position: fixed;
            display: block
        }

        .menubottom nav {
            background-color: #191c24;
            background-image: linear-gradient(110deg, rgba(33, 150, 243, 0.1) 16%, rgba(33, 150, 243, 0.1) 17%, rgba(33, 150, 243, 0.05) 17%, rgba(33, 150, 243, 0.05) 23%, transparent 8.5%, transparent 78%, rgba(33, 150, 243, 0.05) 78%, rgba(33, 150, 243, 0.05) 84%, rgba(33, 150, 243, 0.1) 84%, rgba(33, 150, 243, 0.1));
            display: block;
            position: relative;
            box-shadow: 0 -1px 3px rgba(0, 0, 0, .3);
            border-radius: 20px 20px 0 0
        }

        .menubottom ul li {
            float: left;
            width: 100px;
            height: 100%;
            transition: background-color 0.2s linear .5s;
            transition: all .5s linear;
            background-position: center;
            display: block
        }
</style>
<div class='menubottom '>
    <nav>
        <ul>
            <li class='ripple'>
                <a href='/' itemprop='url' title='Home'><i class="mdi mdi-home" style='font-size:20px'></i><span itemprop='name'><b>Home</b></span></a>
            </li>
            <li class='ripple'>
                <a href='/deposit/' itemprop='url' title='Deposit'><i class="mdi mdi-cash-usd" style='font-size:20px'></i><span itemprop='name'><b>Deposit</b></span></a>
            </li>
            <li class='ripple'>
                <a href='/user/mutasi' itemprop='url' title='Mutasi'><i class="mdi mdi-code-not-equal" style='font-size:20px'></i><span itemprop='name'><b>Mutasi</b></span></a>
            </li>
            <li class='ripple'>
                <a href='/tiket/' itemprop='url' title='Bantuan'><i class="mdi mdi-comment-account-outline" style='font-size:20px'></i><span itemprop='name'><b>Bantuan</b></span></a>
            </li>
            <li class='ripple'>
                <a href='/user/setting' itemprop='url' title='Profil'><i class="mdi mdi-account-circle" style='font-size:20px'></i><span itemprop='name'><b>Profil</b></span></a>
            </li>
        </ul>
    </nav>
</div>
<footer class="footer">
    <div class="d-sm-flex justify-content-center justify-content-sm-between">
        <span class="text-muted d-block text-center text-sm-left d-sm-inline-block">© Copyright <?php echo $data['short_title']; ?>.</span>
    </div>
</footer>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!--WA BUTTON-->
<!--<div class="integration-fixed integration-fixed__bottom-left">
    <div class="whatsapp-container">
        <a href="https://api.whatsapp.com/send?phone=<?php echo $data['wa_number']; ?>" target="_blank" class="whatsapp-button">
            <i class="mdi mdi-whatsapp"></i>
        </a>
    </div>
</div>-->
<!-- container-scroller -->
<link rel="stylesheet" href="/assets/vendors/mdi/css/materialdesignicons.min.css">
<!-- plugins:js -->
<script src="/assets/vendors/js/vendor.bundle.base.js"></script>
<!-- endinject -->
<script src="/assets/vendors/select2/select2.min.js"></script>
<script src="/assets/vendors/typeahead.js/typeahead.bundle.min.js"></script>
<!-- Custom js for this page -->
<script src="/assets/js/file-upload.js"></script>
<script src="/assets/js/typeahead.js"></script>
<script src="/assets/js/select2.js"></script>
<!-- Plugin js for this page -->
<script src="/assets/vendors/chart.js/Chart.min.js"></script>
<script src="/assets/vendors/progressbar.js/progressbar.min.js"></script>
<script src="/assets/vendors/jvectormap/jquery-jvectormap.min.js"></script>
<script src="/assets/vendors/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<script src="/assets/vendors/owl-carousel-2/owl.carousel.min.js"></script>
<!-- End plugin js for this page -->
<!-- inject:js -->
<script src="/assets/js/off-canvas.js"></script>
<script src="/assets/js/hoverable-collapse.js"></script>
<script src="/assets/js/misc.js"></script>
<script src="/assets/js/settings.js"></script>
<script src="/assets/js/todolist.js"></script>
<!-- endinject -->
<!-- Custom js for this page -->
<script src="/assets/js/chart.js"></script>
<!-- Custom js for this page -->
<script src="/assets/js/dashboard.js"></script>
<!-- End custom js for this page -->
<script src="/PWA/register.js"></script>
    <script>
      var btnAdd = document.getElementById("addtohome");
      var defferedPrompt;
      window.addEventListener("beforeinstallprompt", function (event) {
        event.preventDefault();
        defferedPrompt = event;
    
        btnAdd.addEventListener("click", function (event) {
          defferedPrompt.prompt();
    
          defferedPrompt.userChoice.then((choiceResult) => {
            if (choiceResult.outcome === "accepted") {
              console.log("User accepted the A2HS prompt");
            } else {
              console.log("User dismissed the A2HS prompt");
            }
            defferedPrompt = null;
          });
        });
      });
    </script>
<script type="text/javascript">
	$(document).ready(function() {
		$("#operator").change(function() {
			var operator = $("#operator").val();
			$.ajax({
				url: '/ajax/layanan_pulsa.php',
				data: 'operator=' + operator,
				type: 'POST',
				dataType: 'html',
				success: function(msg) {
					$("#layanan").html(msg);
				}
			});
		});
		$("#layanan").change(function() {
			var layanan = $("#layanan").val();
			$.ajax({
				url: '/ajax/harga_pulsa.php',
				data: 'layanan=' + layanan,
				type: 'POST',
				dataType: 'html',
				success: function(msg) {
					$("#harga").val(msg);
				}
			});
		});
		$("#layanan").change(function() {
			var layanan = $("#layanan").val();
			$.ajax({
				url: '/ajax/catatan_pulsa.php',
				data: 'layanan=' + layanan,
				type: 'POST',
				dataType: 'html',
				success: function(msg) {
					$("#catatan").html(msg);
				}
			});
		});
	});
</script>
</body>

</html>