<?php
require_once '../../config.php';
session_start();
load('middleware', 'user');
$date = date('Y-m-d H:i:s');
if(isset($_POST['metode']) AND isset($_POST['nominal'])){
    $metode = $_POST['metode'];
    $nominal = $_POST['nominal'];
    $query_metode = $db->query("SELECT * FROM metode_guest WHERE id='$metode'");
    $layanan ="Deposit Saldo (".$nominal.")";
    if(mysqli_num_rows($query_metode) === 1){
        $fetch_metode = $query_metode->fetch_assoc();
        $next = false;
        $order_id = 'LS'.rand(00000000,99999999);
        $layanan ="Deposit Saldo (".$nominal.")";
        $unik = rand(555,999);
        $waa = $_SESSION['user']['phone'];
        $get_saldo = $nominal * 0.005;
        $get_saldoo = $nominal - $get_saldo;
        if($fetch_metode['sistem'] == "Tripay"){
            $Trip = $db->query("SELECT * FROM payment WHERE code='Tripay'")->fetch_assoc();
            $link = 'https://tripay.co.id/api/transaction/create';
            $substr = substr($waa,3);
            $waaa = '08'.$substr;
            $result = $curl->connectTripayPost($link,['Authorization: Bearer '.$Trip['api_key']],['method' => $fetch_metode['kode'],'merchant_ref' => $order_id,'amount' => $nominal,'customer_name' => $_SESSION['user']['name'],'customer_email' => $_SESSION['user']['email'],'customer_phone' => $waaa,'order_items' => array(['sku' => 'LS','name' => $layanan,'price' => $nominal,'quantity' => 1]),'return_url' => base_url() . 'account/deposit/invoice?no=' . $order_id,'expired_time' => (time() + (60 * 60 * 3)),'signature' => hash_hmac('sha256', $Trip['merchant_id'].$order_id.$nominal, $Trip['api_id'])]);
            if ($result['success'] == true) {
                if (array_key_exists('qr_string', $result['data'])) {
                    $unik = $result['data']['total_fee'];
                    $isi = $result['data']['qr_string'];
                    $gen = md5(uniqid(random(40),true));
                    $nama = $gen.'.png';
                    $pay_url = $nama;
                    $reference = $result['data']['reference'];
                    QRcode::png($isi,'../../assets/qris/'.$nama,QR_ECLEVEL_L,4);
                }else if(isset($result['data']['pay_code'])){
                    $pay_url = $result['data']['pay_code'];
                    $unik = $result['data']['total_fee'];
                    $reference = $result['data']['reference'];
                }else{
                    $pay_url = $result['data']['pay_url'];
                    $unik = $result['data']['total_fee'];
                    $reference = $result['data']['reference'];
                }
                $next = true;
            } else{
                $_SESSION['alert'] = ['danger','Failed',$result['message']];
                exit(header('location: '.base_url('account/deposit/')));
                $next = false;
            }
        }else if($fetch_metode['metode'] == 'E-QRIS'){
                $nama = 'qrisku.jpg';
                $pay_url = 'qrisku.jpg';
                $next = true;
        }else if($fetch_metode['sistem'] == "Xendit"){
            if($fetch_metode['kode'] == "DANA" || $fetch_metode['kode'] == "OVO" || $fetch_metode['kode'] == "SHOPEEPAY" || $fetch_metode['kode'] == "LINKAJA"){
                $try = $Xendit->eWallet($order_id,$nominal+$unik,$fetch_metode['kode'],$waa);
                $pay_url = $try['payment'];
                $reference = $try['id'];
                $next = true;
            }else if($fetch_metode['metode'] == "QRIS"){
                $try = $Xendit->qris($order_id,$nominal+$unik);
                $isi = $try['payment'];
                $reference = $try['id'];
                $gen = md5(uniqid(random(40),true));
                $nama = $gen.'.png';
                $pay_url = $nama;
                QRcode::png($isi,'../../assets/qris/'.$nama,QR_ECLEVEL_L,4);
                $reference = $try['id'];
                $next = true;
            }else if($fetch_metode['tipe'] == "Convenience Store"){
                $try = $Xendit->qris($order_id,$nominal+$unik);
                $reference = $try['id'];
                $pay_url = $try['payment'];
                $next = true;
            }else if($fetch_metode['tipe'] == "Virtual Account"){
                $try = $Xendit->virtualAccount($order_id,$nominal+$unik,$fetch_metode['kode'],$_SESSION['user']['name']);
                $reference = $try['id'];
                $pay_url = $try['payment'];
                $next = true;
            }
        }else{
            $nominal = $nominal;
            $pay_url = $fetch_metode['rek'];
            $next = true;
        }
        if ($next === true) {
                if (isset($pay_url)) {
                    $rek = $pay_url;
                } else {
                    $rek = !empty($fetch_metode['rek']) ? $fetch_metode['rek'] : '-';
                }
                
                if($fetch_metode['metode'] == 'E-QRIS'){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Download QR Code pada invoice</li>
    <li>Masuk ke aplikasi dompet digital Anda yang telah mendukung QRIS</li>
    <li>Upload QR Code yang telah di download tadi</li>
    <li>Akan muncul detail transaksi. Pastikan data transaksi sudah sesuai</li>
    <li>Selesaikan proses pembayaran Anda<//li>
    <li>Transaksi selesai. Simpan bukti pembayaran Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "Indomaret"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Datang ke gerai Indomaret</li>
    <li>Sampaikan ke kasir ingin melakukan pembayaran Linkita</li>
    <li>Berikan kode bayar ke kasir</li>
    <li>Bayar sesuai jumlah yang diinfokan oleh kasir</li>
    <li>Simpan struk bukti pembayaran Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "Alfamidi"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Datang ke Alfamidi</li>
    <li>Sampaikan ke kasir ingin melakukan pembayaran Plasamall</li>
    <li>Berikan kode bayar ke kasir</li>
    <li>Bayar sesuai jumlah yang diinfokan oleh kasir</li>
    <li>Simpan struk bukti pembayaran Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "Alfamart"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Datang ke Alfamart</li>
    <li>Sampaikan ke kasir ingin melakukan pembayaran Plasamall</li>
    <li>Berikan kode bayar ke kasir</li>
    <li>Bayar sesuai jumlah yang diinfokan oleh kasir</li>
    <li>Simpan struk bukti pembayaran Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "BSI Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Masuk ke Internet Banking BSI Anda</li>
    <li>Pilih menu Pembayaran</li>
    <li>Pilih nomor rekening Anda</li>
    <li>Pilih Jenis Pembayaran > Institusi</li>
    <li>Pada opsi Nama Institusi, pilih 9042 Win Pay</li>
    <li>Masukkan kode bayar</li>
    <li>Klik tombol Verifikasi</li>
    <li>Akan ditampikan detail transaksi, pastikan sudah sesuai</li>
    <li>Masukkan TAN & PIN Anda</li>
    <li>Tekan tombol Submit</li>
    <li>Transaksi selesai, simpan bukti pembayaran Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "CIMB Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Login ke CIMB clicks</li>
    <li>Pilih menu Bayar Tagihan / Pay Bills</li>
    <li>Pilih Rekening Sumber / Source Account dan Jenis Pembayaran / Payment Type > Virtual Account</li>
    <li>Masukkan nomor Virtual Account</li>
    <li>Masukkan nominal pembayaran</li>
    <li>Masukkan 6 digit mPIN dan tekan tombol Submit</li>
    <li>Transaksi berhasil, simpan bukti transaksi Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "Muamalat Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Login ke IB Muamalat</li>
    <li>Pilih menu Payment</li>
    <li>pilih rekening Anda dan pilih Virtual Account pada bill type</li>
    <li>masukkan Nomor Va</li>
    <li>Klik Next</li>
    <li>Periksa kembali jumlah pembayaran</li>
    <li>Apabila sudah sesuai, Masukkan mPasscode lalu klik SUBMIT jika setuju dengan informasi pembayaran</li>
    <li>Transaksi Anda selesai. Silahkan cetak bukti transaksi</li>
</ol>';
                }else if($fetch_metode['metode'] == "Sinarmas Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Login ke internet banking Bank Sinarmas Anda</li>
    <li>Pilih menu Transfer Dana lalu pilih menu Rekening Bank Sinarmas</li>
    <li>Masukkan Nomor VA</li>
    <li>Lakukan konfirmasi transaksi seperti memasukkan nomor token atau SMS token untuk melakukan pembayaran</li>
    <li>Simpan bukti transaksi Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "Maybank Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Login ke internet banking Maybank Anda</li>
    <li>Pilih menu Transfer lalu pilih Maybank Virtual Account</li>
    <li>Pilih Rekening Sumber</li>
    <li>Masukkan Nomor VA dan jumlah pembayaran lalu klik Lanjutkan</li>
    <li>Detail transaksi akan ditampilkan, pastikan data sudah sesuai lalu klik Lanjutkan</li>
    <li>Masukkan SMS Token lalu klik Lanjutkan</li>
    <li>Transaksi sukses, simpan bukti transaksi Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "Permata Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Login ke internet banking Bank Permata Anda</li>
    <li>Pilih menu Pembayaran lalu klik menu Pembayaran Tagihan</li>
    <li>Pilih menu Virtual Account</li>
    <li>Pilih Rekening Asal lalu centang Masukkan Daftar Tagihan Baru</li>
    <li>Masukkan Nomor VA lalu klik Lanjutkan</li>
    <li>Detail transaksi akan ditampilkan, pastikan data sudah sesuai lalu klik Lanjutkan</li>
    <li>Masukkan SMS Token Permata, lalu klik Lanjutkan</li>
    <li>Transaksi sukses, simpan bukti transaksi Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "BNI Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Login ke internet banking Bank BNI Anda</li>
    <li>Pilih menu Transaksi lalu klik menu Virtual Account Billing</li>
    <li>Masukkan Nomor VA lalu pilih Rekening Debit</li>
    <li>Detail transaksi akan ditampilkan, pastikan data sudah sesuai</li>
    <li>Masukkan respon key BNI appli 2v
    <li>Transaksi sukses, simpan bukti transaksi Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "BRI Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Login ke internet banking Bank BRI Anda</li>
    <li>Pilih menu Pembayaran lalu klik menu BRIVA</li>
    <li>Pilih rekening sumber dan masukkan Kode Bayar lalu klik Kirim</li>
    <li>Detail transaksi akan ditampilkan, pastikan data sudah sesuai</li>
    <li>Klik Lanjutkan</li>
    <li>Masukkan kata sandi ibanking lalu klik Request untuk mengirim m-PIN ke nomor HP Anda</li>
    <li>Periksa HP Anda dan masukkan m-PIN yang diterima lalu klik Kirim</li>
    <li>Transaksi sukses, simpan bukti transaksi Anda</li>
</ol>';
                }else if($fetch_metode['metode'] == "Mandiri Virtual Account"){
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
    <li>Login ke internet banking Anda</li>
    <li>Pilih menu Pembayaran lalu klik menu Multipayment</li>
    <li>Pilih Penyedia Jasa: Bimasakti</li>
    <li>Masukkan Nomor VA</li>
    <li>Masukkan Nominal</li>
    <li>Detail transaksi akan ditampilkan, pastikan data sudah sesuai</li>
    <li>Klik tombol Konfirmasi</li>
    <li>Periksa aplikasi Mandiri Online di ponsel Anda untuk menyelesaikan persetujuan transaksi</li>
    <li>Transaksi sukses, simpan bukti transaksi Anda</li>
</ol>';
                }else{
                    $intruksi = '<p><b>Cara Pembayaran</b></p>
<ol>
	<li>Salin Rekening dan Harga Total</li>
	<li>Buka Aplikasi M-banking/E-Wallet Anda.</li>
	<li>Masukkan nomor rekening</li>
	<li>Masukkan Harga Total yang ada di invoice (tidak boleh ditambah/dikurangi)</li>
	<li>Lalu Transfer</li>
</ol>';
                }
                $total_harga = $nominal + $unik;
                $suc = $db->query("INSERT INTO `deposit` VALUES ('','{$_SESSION['user']['username']}','{$_SESSION['user']['phone']}','$order_id','$reference','$layanan','{$fetch_metode['metode']}','{$fetch_metode['id']}','$rek','$nominal','$unik','$total_harga','$get_saldoo','Pending','$intruksi','$date','$date')");
                if ($suc == TRUE) {
                    if(filter_var($pay_url,FILTER_VALIDATE_URL)){
                        header('location: '.$pay_url);
                    }else{
                    exit(header('location: /account/deposit/invoice?no=' . $order_id));
                    }
                } else {
                    $_SESSION['alert'] = ['danger','Failed!','Deposit Gagal Dilakukan'];
                    exit(header('location: '.base_url('account/deposit/')));
                }
        } else {
        $_SESSION['alert'] = ['danger','Failed!','Deposit Gagal Dilakukan'];
        exit(header('location: '.base_url('account/deposit/')));
        }
    }else{
        $_SESSION['alert'] = ['danger','Failed!','Metode Tidak Ditemukan!'];
        exit(header('location: /account/deposit/'));
    }
}
require '../../layouts/header.php';
?>
<div class="row justify-content-center">
    <div class="col-lg-8 mx-auto mb-5">
        <div class="card bg-dark shadow">
            <div class="card-header">
                <span class="card-title">Deposit saldo</span>
                <a href="<?=base_url('account/deposit/riwayat');?>" class="btn btn-info text-white">Riwayat Deposit</a>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-12">
                        <span class="h4">Saldo Sekarang : <span class="badge bg-success badge-pill" id="saldoSekarang">Rp <?= number_format($_SESSION['user']['saldo'],0,',','.');?></span></span>
                    </div>
                    <div class="col-12 mt-3">
                        <div class="row justify-content-center">
                            <div class="input-group mb-3">
                                <span class="input-group-text">Rp.</span>
                                <input type="number" class="form-control" id="inputSaldo" placeholder="Masukkan nominal saldo">
                            </div>
                        </div>
                    </div>
                    <div class="col-12 mt-3">
                        <span class="h3">Pilih metode pembayaran</span>
                        <hr>
                        <div class="area-list-payment-method">
                            <?php $i = 1; $query_tipe_metode = mysqli_query($db, "SELECT DISTINCT tipe FROM metode_guest"); while($fetch_tipe_metode = mysqli_fetch_assoc($query_tipe_metode)): $query_metode = mysqli_query($db, "SELECT * FROM metode_guest WHERE tipe = '".$fetch_tipe_metode['tipe']."'");?>
                            <?php if (mysqli_num_rows($query_metode) !== 0 && $fetch_tipe_metode['tipe'] !== "Saldo Akun" && $fetch_tipe_metode['tipe'] !== "Convenience Store" && $fetch_tipe_metode['tipe'] !== "Virtual Account"): ?>
                            <div class="child-box payment-drawwer shadow">
                                <div class="header short-payment-support-info-head" onclick="openPayment(this)">
                                    <div class="left">
                                        <b><?= $fetch_tipe_metode['tipe']; ?></b>
                                    </div>
                                </div>
                                <?php while($fetch_metode = mysqli_fetch_assoc($query_metode)): ?>
                                <div class="button-action-payment" style="display:none;">
                                    <ul>
                                        <li><input type="radio" name="metode" id="metode-<?= $fetch_metode['id']; ?>" onclick="pilih_metode('<?= $fetch_metode['id']; ?>');">
                                            <label for="metode-<?= $fetch_metode['id']; ?>" class="payment-item">
                                            <div class="info-top">
                                                <div><img alt="" height="20px" src="/assets/metode/<?= $fetch_metode['img']; ?>"></div>
                                                <b class="d-block" id="payment" data-harga="" style="font-size: 11px;"></b>
                                            </div>
                                            <div class="info-bottom text-sm-left"><?= $fetch_metode['ket']; ?></br><b id="payment"><?= $fetch_metode['sub_ket']; ?></b></div>
                                            </label>
                                        </li>
                                    </ul>
                                </div>
                                <?php endwhile?>
                                <div class="short-payment-support-info" onclick="openPayment(this)">
                                    <?php $query_metode_logo = mysqli_query($db, "SELECT * FROM metode_guest WHERE tipe = '".$fetch_tipe_metode['tipe']."'"); while($fetch_metode_logo = mysqli_fetch_assoc($query_metode_logo)):?>
                                    <img class="m-1" id="IMG-<?= $fetch_metode['ket']; ?>" style="background-color:white;border-radius: 3px;height:20px;padding:3px;" src="/assets/metode/<?= $fetch_metode_logo['img']; ?>">
                                    <?php endwhile;?>
                                    <a class="open-button-action-payment"><i class="fas fa-chevron-down"></i></a>
                                </div>
                            </div>
                            <?php endif;?>
                            <?php endwhile;?>
                        </div>
                    </div>
                    <div class="col-12 mt-3">
                        <form id="form-deposit" method="POST" action="?">
                            <input type="hidden" name="metode" id="input-metode">
                            <input type="hidden" name="name_metode" id="name_metode">
                            <input type="hidden" name="nominal">
                            <button class="btn btn-success float-end" type="button" onclick="submit_deposit();">Topup Sekarang</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade text-left" id="modal-detail-user-detail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true" data-backdrop="static">
        <div class="modal-dialog modal-dialog-centered" id="SModal-size" role="document">
            <div class="modal-content bg-dark">
                <div class="modal-header">
                    <h5 class="modal-title" id="SModal-title">Konfirmasi</h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true" style="text-shadow: none; color:white;">&times;</span></button>
                </div>
                <div class="modal-body" id="SModal-body">
                    <p>Silahkan Konfirmasi Untuk Deposit Saldo Berikut:</p>
                    <table class="table" style="border:none;">
                        <tr>
                            <th>Nominal</th>
                            <td id="mdu-nominal">-</td>
                        </tr>
                        <tr>
                            <th>Metode</th>
                            <td id="mdu-metode">-</td>
                        </tr>
                    </table>
                    <hr>
                    <button class="btn btn-primary w-100" type="button" onclick="order();">Topup Sekarang</button>
                </div>
            </div>
        </div>
    </div>
<?php include_once '../../layouts/footer.php'; ?>
<script>
function order(){
    $("#form-deposit").submit();
}
function submit_deposit(){
    price = $("#inputSaldo").val();
    metode = $("#input-metode").val();
    name_metode = $("#name_metode").val();
    if(price < 10000){
        toastr.warning(`Minimal Deposit 10000`,"Warning");
    }else if(price == ""){
        toastr.error(`Harap Menginput Nominal Saldo Deposit`,"Error");
    }else if(metode == ""){
        toastr.error(`Harap Memilih Metode Deposit`,"Error");
    }else{
        $("#mdu-nominal").text(formatNumber(price));
        $("#mdu-metode").text(name_metode);
        $('#modal-detail-user-detail').modal('show');
    }
}
function formatNumber(num) {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
}
$(document).ready(function(){
    $("#inputSaldo").on('keyup', function(e) {
            $("input[name='nominal']").val($(this).val());
            $(".info-top #payment").text(formatNumber($(this).val()));
    });
});
function pilih_metode(id) {
    $(".button-action-payment>ul").map(function(){if($(this).children().length == 0){$(this).parent().parent().remove();}});
    $("input[type='radio'][name='metode']").change(function() {
        if ($(this).is(":checked")) {
            $("li.active").removeClass("active");
            $(this).parent('li').addClass("active");
            $("#input-metode").val(id);
            $.ajax({
                url: "<?= base_url('ajax/metode.php');?>",
                type: 'POST',
                dataType: 'JSON',
                data: 'metode_id='+ id,
                success: function(result) {
                    for(var i = 0; i < result.length; i++) {
                        $("#name_metode").val(result[i].metode);
                    }
                }
            });
                
        }
    })
}
    function openPayment(elem) {
            var $this = $(elem);
            $('.payment-drawwer').not(this).each(function() {
                var $parents = $(this);
                $parents.find('.button-action-payment').slideUp(function() {
                    $parents.removeClass('active');
                });

                $parents.find('.short-payment-support-info').find('img').slideDown();
                $parents.find('.short-payment-support-info').find('.fa-chevron-up').removeClass('fa-chevron-up').addClass(
                    'fa-chevron-down');
            });

            var $parents = $this.parents('.child-box');
            if (!$parents.find('.button-action-payment').is(":hidden")) {
                $parents.find('.button-action-payment').slideUp(function() {
                    $parents.removeClass('active');
                });

                $parents.find('.short-payment-support-info').find('img').slideDown();
                $parents.find('.short-payment-support-info').find('.fa-chevron-up').removeClass('fa-chevron-up').addClass(
                    'fa-chevron-down');

            } else {
                $parents.find('.button-action-payment').slideDown(function() {
                    $parents.addClass('active');
                });
                $parents.find('.short-payment-support-info').find('img').slideUp();
                $parents.find('.short-payment-support-info').find('.fa-chevron-down').addClass('fa-chevron-up').removeClass(
                    'fa-chevron-down');

            }
        }
</script>