<?php
$ambil = $con->query("SELECT * FROM profile_paket WHERE id = '$page[1]'");
  $data1 = $ambil->fetch_assoc();
  $harga = $data1['harga_paket'] ;
  $kodeprofile = $data1['nama_profile'];
  $vim = $data1['vi_agen'] ;
  $jumlah = $harga - $vim ;
  $saldo = $pcmem['saldo'];
  // echo "<pre>";
  // print_r($pcmem);
  // echo "</pre>";
?>
<nav class="navbar fixed-top">
    <div id="specificCard" class="card col-12" style="border-radius: 20px; background: none; border: none; margin-top: 10px;">
        <div class="row">
            <div class="col-6 icon-container">
                <a href="?<?php echo base64_encode('voucher_buat'); ?>" class="fa fa-arrow-left text-light"></a>
            </div>
            <div class="col-6 text-right">
                <h6 class="text-light mt-2 mb-2">Pembayaran</h6>
            </div>
        </div>
    </div>
</nav>
<div class="card" style="border-radius: 0px; background: none; border: none; margin-top: 100px;">
  <div class="card-body">
    <center>
      <p style="color: #fff;">Saldo Anda</p>
      <h1 style="font-size: 36px; color: #fff;"><small>Rp. </small><b><?php echo number_format($pcmem['saldo']); ?></b></h1>
    </center>
  </div>
</div>
<div class="card" id="2" style="border-top-right-radius: 40px; border-top-left-radius: 40px; min-height: 750px; border: none; z-index: 1;">
  <div class="card-body">
    <center>
      <h6><b>Pembayaran Voucher Hotspot</b></h6><br>
    </center>
    <hr>
    <div class="row">
      <div class="col-6">
        <h6>Pembelian</h6>
        <h6>Paket</h6>
      </div>
      <div class="col-6 text-right">
        <h6>Voucher</h6>
        <h6><?php echo $data1['nama']; ?></h6>
      </div>
    </div>
    <hr>
    <div class="row">
      <div class="col-6">
        <h6>Harga</h6>
        <h6>Fee Agen</h6>
      </div>
      <div class="col-6 text-right">
        <h6>Rp. <?php echo number_format($data1['harga_paket']) ; ?></h6>
        <h6>Rp. <?php echo number_format($vim ) ; ?></h6>
      </div>
    </div>
    <hr>
    <div class="row">
      <div class="col-6">
        <h6><b>TOTAL</b></h6>
      </div>
      <div class="col-6 text-right">
        <h2><b>Rp. <?php echo number_format($jumlah ) ; ?></b></h2>
      </div>
    </div>
    <?php if ($saldo < $jumlah): ?>
    <div class="alert alert-danger fixed">
        <b>Saldo Anda..!! </b>tidak mencukupi untuk melanjutkan transaksi
    </div>
    <div class="card-body">
        <h3 class="text-danger">Saldo anda Rp. <?php echo number_format($saldo); ?></h3><br>
    </div>
    <?php else: ?>
        <div class="card-body mt-4">
            <form method="post">
                <div class="card-body" id="btn001">
                    <input type="submit" style="border-radius: 20px;" name="pay" class="btn btn-warning btn-md btn-rounded btn-block" value="Generate Voucher" onclick="toggleButtons()"/>
                </div>
                <div class="card-body" id="btn002" style="display: none;">
                    <input type="submit" style="border-radius: 20px;" class="btn btn-warning btn-md btn-rounded btn-block" value="Sedang diproses..." disabled/>
                </div>
            </form>
        </div>
    <?php endif; ?>
  </div>
</div>
</div>
<?php

if (isset($_POST['pay']) && $_SESSION['pay'] == 'true') {
    $karakter = "QWERTYUIOPASDFGHJKLZXCV12345098760987612345BNMQWERTYUIOPASGHJKLZXCVBNM";
    $str = $data1['durasi'];
    $kodevoucher = $pcmem['kode_agen'] . $str . substr(str_shuffle($karakter), 0, 7);
    if($pcmem['status'] == 'Aktif') {
        // Fetch settings
        $stmt = $pdo->prepare("SELECT * FROM setting_mikrotik WHERE id = :id");
        $stmt->execute([':id' => $pcmem['id_setting_mikrotik']]);
        $pset = $stmt->fetch(PDO::FETCH_ASSOC);
    
        $m_ip = $pset['ip_address'];
        $m_user = $pset['username'];
        $m_pass = $pset['password'];
        $m_port = $pset['port_api'];
    
        require('router_api/routeros_api.class.php');
        $API = new RouterosAPI();
        $API->debug = false;
    
        if ($API->connect2($m_ip, $m_user, $m_pass, $m_port)) {
            if ($saldo >= $jumlah) {
                $ARRAY = $API->comm("/ip/hotspot/user/profile/print", array(
                    ".proplist" => ".id",
                    "?name" => $kodeprofile,
                ));
    
                if (empty($ARRAY) || $ARRAY[0]['.id'] == '') {
                  sweetAlert("Transaksi Gagal: Profile paket tidak terdaftar di server, silahkan hubungi admin", "error");
                } else {
                    $date = date('Y-m-d H:i:s');
    
                    // Insert generated voucher
                    $stmt = $pdo->prepare("INSERT INTO ganerate_voucher 
                        (id_data_server, id_agen_voucher, id_setting_mikrotik, id_profile_paket, voucher, harga, create_time)
                        VALUES (:id_data_server, :id_agen_voucher, :id_setting_mikrotik, :id_profile_paket, :voucher, :harga, :create_time)");
                    $stmt->execute([
                        ':id_data_server' => $pcmem['id_data_server'],
                        ':id_agen_voucher' => $_SESSION['agen'],
                        ':id_setting_mikrotik' => $pcmem['id_setting_mikrotik'],
                        ':id_profile_paket' => $page[1],
                        ':voucher' => $kodevoucher,
                        ':harga' => $harga,
                        ':create_time' => $date
                    ]);
                    $last_id = $pdo->lastInsertId();
    
                    // Add user in MikroTik
                    $API->comm('/ip/hotspot/user/add', array(
                        "name" => $kodevoucher,
                        "password" => $kodevoucher,
                        "profile" => $kodeprofile,
                        "server" => "all"
                    ));
    
                    $API->disconnect();
    
                    $generate_time = date('Y-m-d');
                    $ket = 'pembelian voucher ' . $data1['nama'] . ' -> ' . $kodevoucher;
                    $stmt = $pdo->prepare("INSERT INTO transaksi_agen_voucher 
                        (id_data_server, id_agen_voucher, id_ganerate_voucher, kredit, keterangan, input_time, generate_time) 
                        VALUES (:id_data_server, :id_agen_voucher, :id_ganerate_voucher, :kredit, :keterangan, :input_time, :generate_time)");
                    $stmt->execute([
                        ':id_data_server' => $pcmem['id_data_server'],
                        ':id_agen_voucher' => $_SESSION['agen'],
                        ':id_ganerate_voucher' => $last_id,
                        ':kredit' => $jumlah,
                        ':keterangan' => $ket,
                        ':input_time' => $date,
                        ':generate_time' => $generate_time
                    ]);
                    sweetAlert("Transaksi Berhasil", "success", "?" . base64_encode('voucher_detail_berhasil|' . $last_id));
                }
            } else {
                sweetAlert("Transaksi Gagal: Saldo Anda tidak Cukup", "error");
            }
        } else {
            sweetAlert("Transaksi Gagal: Server tidak terhubung, silahkan hubungi admin", "error");
        }
    } else {
        sweetAlert("Transaksi Gagal: Status agen Non Aktif, silahkan hubungi Admin", "error");
    }
}

if ($_SESSION['pay'] == 'false') {
    echo '<meta http-equiv="refresh" content="0;url=?'.base64_encode('Home').'">';
    // exit();
}
?>

<script>
function toggleButtons() {
    document.getElementById('btn001').style.display = 'none';
    document.getElementById('btn002').style.display = 'block';
}
</script>