<?php
require('db_connection.php');
include('routeros_api.class.php');

setcookie("message", "delete", time() - 1);
$API = new routeros_api();
$API->debug = false;

// Fetch packages
$packages = [];
if ($API->connect($ip_mikrotik, $user_mikrotik, $password_mikrotik, $mikrotik_port)) {
    try {
        $profiles = $API->comm('/ppp/profile/print');
        foreach ($profiles as $profile) {
            $excludePackages = ['default', 'P10', 'vpn-mikhmon', 'isolir', 'default-encryption']; 
             if (!in_array($profile['name'], $excludePackages)) {
                $packages[] = [
                    'name' => $profile['name'],
                    'price' => $profile['comment']
                ];
            }
        }
        $API->disconnect();
    } catch (Exception $ex) {
        echo json_encode(['error' => $ex->getMessage()]);
    }
} else {
    echo json_encode(['error' => 'VPN Offline atau router tidak konek']);
}

if (isset($_POST['kirim'])) {
    if ($API->connect($ip_mikrotik, $user_mikrotik, $password_mikrotik, $mikrotik_port)) {
        $merchantRef = $_POST['username'];
        $profile = $_POST['paket'];
        $method = $_POST['rek'];
        $email = $_POST['email'];
        $nama = $_POST['nama'];
        $phone = $_POST['phone'];
        
        try {
            $ceksecret = $API->comm('/ppp/secret/print', array(
                "?name" => $merchantRef,
                "?profile" => "isolir",
            ));
            $cekprofile = $API->comm('/ppp/profile/print', array(
                "?name" => $profile,
            ));
            
            if (count($ceksecret) > 0) {
                // $method = "DANA";
                $amount = $cekprofile[0]['comment'];
                // $email = "acm2lp21@gmail.com";
                // $nama = "Acil";
                // $phone = "08123456789";
                $query = "SELECT * FROM transaction WHERE merchant_ref = '{$merchantRef}' AND profile = '$profile' AND status = 'UNPAID'";
                $result = $db->query($query);
                
                if ($result === false) {
                    // Handle query error
                    die("Database query failed: " . $db->error);
                }
                
                $row = $result->fetch_assoc();
                $ceklink = isset($row['checkout_url']) ? $row['checkout_url'] : null;
                $cekdata = $result->num_rows;

                if ($cekdata == 0) {
                    $data = [
                        'method' => $method,
                        'merchant_ref' => $merchantRef,
                        'amount' => $amount,
                        'customer_name' => $nama,
                        'customer_email' => $email,
                        'customer_phone' => $phone,
                        'order_items' => [
                            [
                                'sku' => $merchantRef,
                                'name' => "$profile-$merchantRef",
                                'price' => $amount,
                                'quantity' => 1,
                            ],
                        ],
                        // 'return_url'    => 'http://wifikonut.bang-al.my.id/get_expired.php',
                        'return_url'     => 'https://wifikonut.bang-al.my.id/get_expsucces.php?merchant_ref=' . $merchantRef, //link ke detail voucher
                        'expired_time'  => (time() + (24 * 60 * 60)), // 24 jam
                        'signature'     => hash_hmac('sha256', $merchantCode . $merchantRef . $amount, $privateKey)
                    ];

                    $curl = curl_init();
                    curl_setopt_array($curl, [
                        CURLOPT_FRESH_CONNECT => true,
                        CURLOPT_URL => $Endpoint,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_HEADER => false,
                        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $apiKey],
                        CURLOPT_FAILONERROR => false,
                        CURLOPT_POST => true,
                        CURLOPT_POSTFIELDS => http_build_query($data),
                        CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
                        CURLOPT_SSL_VERIFYHOST => 0,
                        CURLOPT_SSL_VERIFYPEER => 0
                    ]);

                    $response = curl_exec($curl);
                    $invoiceData = json_decode($response, true);
                    curl_close($curl);

                    if (!isset($invoiceData['error'])) {
                        $type = 'secret';
                        $payment_url = $invoiceData['data']['checkout_url'];
                        $reference = $invoiceData['data']['reference'];
                        $status = $invoiceData['data']['status'];
                        $customer_name = $invoiceData['data']['customer_name'];
                        $customer_email = $invoiceData['data']['customer_email'];
                        $customer_phone = $invoiceData['data']['customer_phone'];

                        if ($invoiceData['success']) {
                            // Pembayaran berhasil
                            $db->query("INSERT INTO transaction (reference, merchant_ref, profile, payment_method, amount, checkout_url, status, customer_name, customer_email, customer_phone, type) VALUES ('$reference', '$merchantRef', '$profile', '$method', '$amount', '$payment_url', '$status', '$customer_name', '$customer_email', '$customer_phone', '$type')");
                            header('Location: ' . $payment_url);
                            exit;
                        } else {
                            // Pembayaran gagal
                            $error_message = $invoiceData['message'];
                            setcookie("message", "Pembayaran gagal. Pesan error: $error_message", time() + 5);
                            header('Location: ' . $base_url);
                        }
                    } else {
                        // Terjadi kesalahan koneksi
                        $error_message = $invoiceData['error_message'];
                        setcookie("message", "Pembayaran gagal. Pesan error: $error_message", time() + 5);
                        header('Location: ' . $base_url);
                    }
                } else {
                    header('Location: ' . $ceklink);
                }
            } else {
                setcookie("message", "ID Pelanggan tidak ditemukan", time() + 5);
                header('Location: ' . $base_url);
            }

            $API->disconnect();
        } catch (Exception $ex) {
            setcookie("message", "Caught exception from router: " . $ex->getMessage(), time() + 5);
            header('Location: ' . $base_url);
        }
    } else {
        setcookie("message", "VPN Offline atau router tidak konek", time() + 5);
        header('Location: ' . $base_url);
    }
}
?>

<!DOCTYPE html>
<html lang="id-ID">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="author" content="Acil">
    <meta name="theme-color" content="#16ac91">
    <meta name="msapplication-navbutton-color" content="#16ac91">
    <meta name="apple-mobile-web-app-status-bar-style" content="#16ac91">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="icon" href="img/favicon.png">
    <title>IsOlir</title>
    <link rel="stylesheet" media="screen, projection" href="css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <style>
        .hidden {
            display: none;
        }
        .alert {
            padding: 1rem;
            background-color: #f44336; /* Red */
            color: white;
            margin-top: 10px;
            text-align:center;
            border-radius:1rem;
        }
    </style>
</head>
<body onload="showMessage()">
<div class="app-container">
    <div class="page page-home page-with-subnavbar">
        <header class="background-main">

        </header>
        <!-- end header -->

        <!-- slider -->
        <div class="border-radius-style background-main">
            <div class="container">
                <div class="padding-box-middle box-shadow background-white border-radius text-center">
                    <h6 class="page-content aket-habis">
                        <h4 class="paket-habis">
                        <i class="fa fa-info-circle"></i><b> Form Pembayaran</b>
                        </h4>
                    <!--    <br>-->
                    <!--    <h4 class="paket-habis"><i>PELANGGAN YANG TERHORMAT</i></h4>-->
                        <!--<h4 class="txt-red"><i>$(username)</i> </h4>-->
                    <!--    <p class="main-content__body">-->
                    <!--        Kami informasikan <b><i>bahwa layanan internet Anda</i></b> saat ini <i><b>ter isolir secara otomatis</i></b> oleh sistem billing kami.-->
                    <!--    </p>-->
                    <!--    <p class="main-content__body">-->
                    <!--        <i><b>Silahkan melakukan Pembayaran Agar dapat digunakan kembali,</i></b>-->
                    <!--    </p>-->
                    <!--    <p class="main-content__body">-->
                    <!--       <i><b class="paket-habis">Untuk melakukan perpanjangan secara otomatis bisa menggunakan fitur dibawah ini</i></b>-->
                    <!--    </p>-->
                    <!--    <i><b>Terimakasih!</i></b>-->
                    <!--    <br>-->
                    <!--</h6>-->
                </div>
            </div>
        </div>
        <!-- end slider -->
    </div>
</div><!-- end App Container -->

<div class="separator-small"></div>
<div class="login">
    <div class="container">
        <div class="margin-bottom-small">
            <div class="background-white border-box-login box-shadow padding-box-middle text-center">
                <div class="container">
                    <form method="POST">
                        <!--<div class="container">-->
                        <!--    <div class="row-no-margin-bottom">-->
                        <!--        <img class="isolir" src="img/isolir.jpg" alt="img"/>-->
                        <!--    </div>-->
                        <!--</div>-->
                        <p class="text-center">&nbsp;Form Pembayaran&nbsp; </p>
                         <div class="modal-container-body">
                          <label><b>ID Pelanggan</b></label>
                        <input class="form-control" type="text" placeholder="ID/Username" required="" name="username">
                        <label><b>Paket</b></label>
                        <select id="paket" name="paket" style="width: 100%;" required>
                            <?php foreach ($packages as $package): ?>
                                <option value="<?= $package['name'] ?>" data-price="<?= $package['price'] ?>"><?= $package['name']?> | <?= $package['price'] ?></option>
                            <?php endforeach; ?>
                        </select>
                        <!--<input type="text" id="price" name="price" readonly>-->
                        <label><b>Nama</b></label>
                        <input class="form-control" type="text" placeholder="Nama Anda" required="" name="nama">
                        <label><b>Email</b></label>
                        <input class="form-control" type="text" placeholder="Email Anda" required="" name="email">
                        <label><b>No Whatsapp</b></label>
                        <input class="form-control" type="number" placeholder="No Whatsapp" required="" name="phone">
                        <label><b>Metode Pembayaran</b></label>
                        <select name="rek" style="width: 100%;">
                            <option value="QRIS" selected>QRIS by ShopeePay</option>    
                            <option value="BNIVA">BNI Virtual</option>
                            <option value="BRIVA">BRI Virtual Account</option>
                            <option value="BCAVA">BCA Virtual Account</option>
                            <option value="MYBVA">Maybank Virtual Account</option>
                            <option value="DANA">DANA</option>
                            <option value="OVO">OVO</option>
                            <option value="ALFAMART">ALFAMART</option>
                            <option value="INDOMARET">INDOMARET</option>
                        </select>
                        </div>
                        <div class="container">
                            <button id="paymentButton" type="submit" name="kirim" class="button border-radius button-login mr-t-10 box-shadow">Bayar Sekarang</button>
                        </div>
                        <div id="message" class="alert hidden"></div>
                    </form>
                    
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modal -->
<div class="separator-small"></div>

<!-- Social Media -->
<div class="container margin-bottom-big socmed">
    <div class="background-white border-radius box-shadow padding-box-middle text-center">
        <h4 class="margin-bottom-small">Ikuti Kami di :</h4>
        <ul>
            <li id="sosmedList"></li>
        </ul>
    </div>
</div>
<!-- end Social Media -->

<div class="separator"></div>
<div class="separator"></div>
<div class="separator-bottom"></div>

<footer class="copyright">
    <small> Copyright &copy; 2022 $(identity)</small>
</footer>

<script src="js/jquery.js"></script>
<script src="js/owl.min.js"></script>
<script src="config.js"></script>

<script>
    const api_url = 'https://wifikonut.bang-al.my.id';
        
    function getCookie(name) {
        let match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
        if (match) return decodeURIComponent(match[2].replace(/\+/g, ' '));
        return null;
    }
    
    function showMessage() {
        const message = getCookie("message");
        if (message) {
            document.getElementById("message").innerText = message;
            document.getElementById("message").style.display = "block";
            document.cookie = "message=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        }
    }
    
    // JavaScript for updating price based on selected package
    document.getElementById('paket').addEventListener('change', function() {
        var selectedOption = this.options[this.selectedIndex];
        var price = selectedOption.getAttribute('data-price');
        document.getElementById('price').value = price;
    });
</script>

</body>
</html>
