<?php
session_start();
require '../config.php';
require '../lib/session_user.php';
$post_idtarget = $conn->real_escape_string($_GET['id_services']);
$order_single = $conn->query("SELECT * FROM layanan_sosmed WHERE id = '$post_idtarget' AND status = 'Aktif'");
$data_order_single = $order_single->fetch_assoc();
if (mysqli_num_rows($order_single) == 1) {
    $lanjut = "364hgdI34JBD78kdsg89yenGH78bhas78gBq2iI";
    $cek_diskon = $conn->query("SELECT * FROM users WHERE username = '" . $_SESSION['user']['username'] . "'");
    $data_diskon = mysqli_fetch_assoc($cek_diskon);
    if ($data_diskon['diskon_user'] == "0") {
        $price = $data_order_single['harga'];
    } else {
        $ST = (($data_order_single['harga'] * $data_diskon['diskon_user']) / 100);
        $price = $data_order_single['harga'] - $ST;
    }
} else {
    $lanjut = "NOT";
}
if (isset($_POST['pesan'])) {
    require '../lib/session_login.php';
    $post_kategori = $conn->real_escape_string(trim(filter($_POST['kategori'])));
    $post_layanan = $conn->real_escape_string(trim(filter($_POST['layanan'])));
    $post_jumlah = $conn->real_escape_string(trim(filter($_POST['jumlah'])));
    $post_target = $conn->real_escape_string(trim(filter($_POST['target'])));
    $post_comments = $_POST['comments'];

    $cek_kate = $conn->query("SELECT * FROM kategori_layanan  WHERE id = '$post_kategori'");
    $data_kate = mysqli_fetch_assoc($cek_kate);

    $cek_layanan = $conn->query("SELECT * FROM layanan_sosmed  WHERE service_id = '$post_layanan' AND status = 'Aktif'");
    $data_layanan = mysqli_fetch_assoc($cek_layanan);

    if ($data_layanan['refill'] == "1") {
        $refill_button = "YA";
    } else {
        $refill_button = "TIDAK";
    }

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


    $cek_harga = $data_layanan['harga'] / 1000;
    $cek_profit = $data_layanan['profit'] / 1000;
    $hitung = count(explode(PHP_EOL, $post_comments));
    $replace = str_replace("\r\n", '\r\n', $post_comments);
    if (!empty($post_comments)) {
        $post_jumlah = $hitung;
    } else {
        $post_jumlah = $post_jumlah;
    }
    // $price = $rate*$post_quantity;
    if (!empty($post_comments)) {
        $harga_asli = $cek_harga * $hitung;
        $DS = $data_user['diskon_user'];
        $SET = (($harga_asli * $DS) / 100);
        $harga = $harga_asli - $SET;

        $profit = $cek_profit * $hitung;
    } else {
        $harga_asli = $cek_harga * $post_jumlah;
        $DS = $data_user['diskon_user'];
        $SET = (($harga_asli * $DS) / 100);
        $harga = $harga_asli - $SET;

        $profit = $cek_profit * $post_jumlah;
    }
    $order_id = acak_nomor(3) . acak_nomor(4);
    $provider = $data_layanan['provider'];

    $cek_provider = $conn->query("SELECT * FROM provider WHERE code = 'ZAYNFLAZZ'");
    $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();

    //Get Start Count
    if ($data_layanan['kategori'] == "Instagram Likes" and "Instagram Likes Indonesia" and "Instagram Likes [Targeted Negara]" and "Instagram Likes/Followers Per Minute") {
        $start_count = likes_count($post_target);
    } else if ($data_layanan['kategori'] == "Instagram Followers No Refill/Not Guaranteed" and "Instagram Followers Indonesia" and "Instagram Followers [Negara]" and "Instagram Followers [Refill] [Guaranteed] [NonDrop]") {
        $start_count = followers_count($post_target);
    } else if ($data_layanan['kategori'] == "Instagram Views") {
        $start_count = views_count($post_target);
    } else {
        $start_count = 0;
    }

    if (!$post_target || !$post_layanan || !$post_kategori) {
        $_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Gagal!', 'pesan' => 'Harap Mengisi Semua Form Input');
    } else if (mysqli_num_rows($cek_layanan) == 0) {
        $_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Gagal!', 'pesan' => 'Layanan Tidak Tersedia.');
    } else if (mysqli_num_rows($cek_provider) == 0) {
        $_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Gagal!', 'pesan' => 'Server Sedang Maintance.');
    } else if ($post_jumlah < $data_layanan['min']) {
        $_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Gagal!', 'pesan' => 'Jumlah Minimal Pemesanan Adalah ' . number_format($data_layanan['min'], 0, ',', '.') . '.');
    } else if ($post_jumlah > $data_layanan['max']) {
        $_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Gagal!', 'pesan' => 'Jumlah Maksimal Pemesanan Adalah ' . number_format($data_layanan['max'], 0, ',', '.') . '.');
    } else if ($data_user['saldo'] < $harga) {
        $_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Gagal!', 'pesan' => 'Saldo Anda Tidak Mencukupi Untuk Melakukan Pemesanan Ini.');
    } else {

        if ($provider == "MANUAL") {
            $api_postdata = "";
        } else if ($provider == "ZAYNFLAZZ") {
            if ($post_comments == false) {
                $postdata = "api_key=" . $data_provider['api_key'] . "&action=pemesanan&layanan=" . $data_layanan['provider_id'] . "&target=$post_target&jumlah=$post_jumlah";
            } else if ($post_comments == true) {
                $postdata = "api_key=" . $data_provider['api_key'] . "&action=pemesanan&layanan=" . $data_layanan['provider_id'] . "&target=$post_target&custom_comments=$post_comments";
            }

            $endpoint = $data_provider['link'];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $endpoint);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $chresult = curl_exec($ch);
            curl_close($ch);
            $json_result = json_decode($chresult, true);
        } else {
            die("System Error!");
        }
        if ($provider == "ZAYNFLAZZ" and $json_result['status'] == false) {
            $_SESSION['hasil'] = array('alert' => 'danger', 'judul' => 'Gagal!', 'pesan' => '' . $json_result['data']['pesan'] . '.');
        } else {
            if ($provider == "ZAYNFLAZZ") {
                $provider_oid = $json_result['data']['id'];
            }

            if ($conn->query("INSERT INTO pembelian_sosmed VALUES ('','$order_id', '$provider_oid', '$sess_username', '" . $data_layanan['layanan'] . "', '$post_target', '$post_jumlah', '0', '$start_count', '$harga', '$profit', 'Pending', '$date', '$time', '$provider', 'Website', '0', '$refill_button')") == true) {
                $conn->query("UPDATE users SET saldo = saldo-$harga, pemakaian_saldo = pemakaian_saldo+$harga WHERE username = '$sess_username'");
                $conn->query("INSERT INTO history_saldo VALUES ('', '$sess_username', 'Pengurangan Saldo', '$harga', 'Pemesanan Sosial Media Dengan Order ID $order_id', '$date', '$time')");
                $conn->query("INSERT INTO monitoring_sosmed VALUES ('', '" . $data_layanan['id_kategori'] . "', '" . $data_layanan['service_id'] . "', '$order_id', '" . $data_kate['nama'] . "', '" . $data_layanan['layanan'] . "', '$date', '$time','')");

                $jumlah = number_format($post_jumlah, 0, ',', '.');
                $harga2 = number_format($harga, 0, ',', '.');
                $_SESSION['hasil'] = array(
                    'alert' => 'success',
                    'judul' => 'Pesanan Berhasil.<br />',
                    'pesan' => '<b>Order ID : </b> ' . $order_id . '<br />
    				 <b>Layanan : </b> ' . $data_layanan['layanan'] . '<br />
    				 <b>Target : </b> ' . $post_target . '<br />
    				 <b>Start Count : </b> ' . $start_count . '<br />
    				 <b>Jumlah Pesan : </b> ' . $jumlah . '<br />
    				 <b>Total Harga : </b> Rp ' . $harga2 . ''
                );
                // PESAN WA
                $target = $data_user['nomer'];
                $nama_user = $data_user['nama'];
                $token_whatsapp =  $data_wa_bot['token_wa'];
                $waktu_order = (tanggal_indo($date));
                $webstes = $config['web']['url'];
                $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 SOSIAL MEDIA\n\n𝙄𝘿 : $order_id\nTanggal & Waktu : $waktu_order - $time WIB\nLayanan : " . $data_layanan['layanan'] . "\nHarga : $harga\nTarget : $post_target\nStatus : Pending\n\nby : $webstes",
                    ),
                    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' => 'Gagal!', 'pesan' => 'Error System (2)');
            }
        }
    }
    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 Baru</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="kategori" id="kategori" style="width:100%">
                                <?php
                                if ($lanjut == "364hgdI34JBD78kdsg89yenGH78bhas78gBq2iI") {
                                ?>
                                    <option value="<?php echo $data_order_single['id_kategori']; ?>"><?php echo $data_order_single['kategori']; ?></option>
                                <?php
                                } else {
                                ?>
                                    <option value="">Pilih Kategori...</option>
                                <?php } ?>
                                <?php
                                $cek_kategori = $conn->query("SELECT * FROM kategori_layanan WHERE tipe = 'Sosial Media' ORDER BY nama ASC");
                                while ($data_kategori = $cek_kategori->fetch_assoc()) {
                                ?>
                                    <option value="<?php echo $data_kategori['id']; ?>"><?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%">
                                <?php
                                if ($lanjut == "364hgdI34JBD78kdsg89yenGH78bhas78gBq2iI") {
                                ?>
                                    <option value="0">👇👇 Pilih Disini 👇👇</option>
                                    <option value="<?php echo $data_order_single['service_id']; ?>"> <?php echo $data_order_single['layanan']; ?> Rp <?php echo number_format($price, 0, ',', '.'); ?></option>
                                <?php
                                } else {
                                ?>
                                    <option value="0">Pilih Layanan...</option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <div id="catatan"></div>
                        </div>
                        <div class="form-group">
                            <label for="target">Target</label>
                            <input type="text" class="form-control" id="target" name="target">
                        </div>
                        <div id="show1">
                            <div class="form-group">
                                <label for="target">Jumlah</label>
                                <input type="number" class="form-control" id="jumlah" name="jumlah" onkeyup="get_total(this.value).value;">
                            </div>
                            <input type="hidden" id="rate" value="0">
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Total Harga</span>
                                    </div>
                                    <input type="number" class="form-control" id="total" readonly style="background: #000;">
                                    <div class="input-group-append">
                                        <span class="input-group-text">IDR</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div id="show2" style="display: none;">
                            <div class="form-group">
                                <label for="comments">Comments</label>
                                <textarea class="form-control" name="comments" id="comments" placeholder="Pisahkan Tiap Baris komentar dengan enter" rows="4"></textarea>
                            </div>
                            <input type="hidden" id="rate" value="0">
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Total Harga</span>
                                    </div>
                                    <input type="number" class="form-control" id="totalxx" readonly style="background: #000;">
                                    <div class="input-group-append">
                                        <span class="input-group-text">IDR</span>
                                    </div>
                                </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>Pastikan Anda memenginput link yang benar sesuai format yang ada di keterangan, karena kami tidak bisa membatalkan pesanan.</li>
                        <li>Jangan menggunakan lebih dari satu layanan sekaligus untuk username/link yang sama. Harap tunggu status completed pada orderan sebelumnya baru melakukan orderan kepada username/ link yang sama. Hal ini tidak akan membantu mempercepat orderan Anda karena kedua orderan bisa jadi berstatus completed tetapi hanya tercapai target dari salah satu orderan dan tidak ada pengembalian dana.</li>
                        <li>Setelah order dimasukan, jika username/link yang diinput tidak ditemukan (diganti, menjadi pribadi), orderan akan otomatis menjadi completed dan tidak ada pengembalian dana.</li>
                        <li>Kesalahan jumlah order dll oleh member, bukan tanggung jawab akmi, karena panel ini serba automatis, jadi hati-hati dan perhatikan sebelum order dan tidak ada pengembalian dana!</li>
                        <li>Jika Orderan status partial & canceled, saldo otomatis di refund dan bisa order ulang!</li>
                        <li>Jumlah MAX menunjukkan kapasitas layanan tersebut untuk satu target (akun/link) bukan menunjukkan kapasitas maks sekali order. Apabila Anda telah menggunakan semua kapasitas MAX layanan, Anda tidak bisa menggunakan layanan itu lagi dan harus menggunakan layanan yang lain. Oleh karenannya kami menyediakan banyak layanan dengan kapasitas maks yang lebih besar.</li>
                        <li>Informasi yang terdapat pada kolom keterangan (speed, drop rate, bersifat estimasi untuk membedakan layanan yang satu dan lainnya.Informasi bisa jadi tidak akurat tergantung dari performa server dan jumlah orderan yang masuk pada server tersebut. Anda dapat report setelah 24 jam orderan disubmit.</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>
<?php
require '../lib/footer.php';
?>