<?php
global $connection, $botUrl, $mainValues, $admin, $buttonValues;
include '../baseInfo.php';
include '../config.php';
//==============================================================

$stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
$stmt->execute();
$paymentKeys = $stmt->get_result()->fetch_assoc()['value'];
if (!is_null($paymentKeys))
    $paymentKeys = json_decode($paymentKeys, true);
else
    $paymentKeys = array();
$stmt->close();

if (isset($_GET['nowpayment'])) {
    if (isset($_GET['NP_id'])) {
        $hash_id = $_GET['NP_id'];
        $base_url = 'https://api.nowpayments.io/v1/payment/' . $hash_id;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

        curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-API-KEY: ' . $paymentKeys['nowpayment']]);
        curl_setopt($ch, CURLOPT_URL, $base_url);
        $res = json_decode(curl_exec($ch));
        $hash_id = $res->invoice_id;

        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `payid` = ? AND (`state` = 'pending' OR `state` = 'send')");
        $stmt->bind_param("i", $hash_id);
        $stmt->execute();
        $payInfo = $stmt->get_result();
        $stmt->close();

        if (mysqli_num_rows($payInfo) == 0) {
            showForm("کد پرداخت یافت نشد", "خطا!");
        }
        else {
            $payParam = $payInfo->fetch_assoc();
            $rowId = $payParam['id'];
            $amount = $payParam['price'];
            $user_id = $payParam['user_id'];
            $payType = $payParam['type'];

            $plan_id = $payParam['plan_id'];
            $volume = $payParam['volume'];
            $days = $payParam['day'];
            if ($payType == "BUY_SUB")
                $payDescription = "خرید اکانت";
            elseif ($payType == "RENEW_ACCOUNT")
                $payDescription = "تمدید اکانت";
            elseif ($payType == "RENEW_SCONFIG")
                $payDescription = "تمدید اکانت";
            elseif ($payType == "INCREASE_WALLET")
                $payDescription = "شارژ کیف پول";
            elseif (preg_match('/^INCREASE_DAY_(\d+)_(\d+)/', $payType))
                $payDescription = "افزایش زمان اکانت";
            elseif (preg_match('/^INCREASE_VOLUME_(\d+)_(\d+)/', $payType))
                $payDescription = "افزایش حجم اکانت";

            //==============================================================
            if ($res->payment_status == 'finished' or $res->payment_status == 'confirmed' or $res->payment_status == 'sending') {
                doAction($rowId, "nowpayment");
            }
            else {
                if ($res->payment_status == 'partially_paid') {
                    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'low_payment' WHERE `payid` =?");
                    $stmt->bind_param("i", $hash_id);
                    $stmt->execute();
                    $stmt->close();

                    showForm("#$hash_id - شما هزینه کمتری واریز کردید، لطفا به پشتیبانی مراجعه کنید", $payDescription);
                }
                else {
                    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'canceled' WHERE `payid` =?");
                    $stmt->bind_param("i", $hash_id);
                    $stmt->execute();
                    $stmt->close();

                    showForm("پرداخت انجام نشد", $payDescription);
                }
            }
        }
    }
    else {
        showForm("پرداخت انجام نشد", "خطا!");
    }
}
elseif (isset($_GET['zarinpal'])) {
    $hash_id = $_GET['hash_id'];
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND (`state` = 'pending' OR `state` = 'send')");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    if (mysqli_num_rows($payInfo) == 0) {
        showForm("کد پرداخت یافت نشد", "خطا!");
    }
    else {
        $payParam = $payInfo->fetch_assoc();
        $rowId = $payParam['id'];
        $amount = $payParam['price'];
        $user_id = $payParam['user_id'];
        $payType = $payParam['type'];


        $Authority = $_GET['Authority'];
        //==============================================================
        $client = new SoapClient('https://www.zarinpal.com/pg/services/WebGate/wsdl', ['encoding' => 'UTF-8']);
        $result = $client->PaymentVerification([
            'MerchantID' => $paymentKeys['zarinpal'],
            'Authority' => $Authority,
            'Amount' => $amount,
        ]);
        //==============================================================
        if ($_GET['Status'] == 'OK' and $result->Status == 100) {
            doAction($rowId, "zarinpal");
        }
        else {
            $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'canceled' WHERE `hash_id` = ?");
            $stmt->bind_param("s", $hash_id);
            $stmt->execute();
            $stmt->close();

            showForm("پرداخت شما انجام نشد!", "درگاه زرین پال");
        }
    }
}
elseif (isset($_GET['nextpay'])) {
    $hash_id = $_GET['trans_id'];
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `payid` = ? AND (`state` = 'pending' OR `state` = 'send')");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    if (mysqli_num_rows($payInfo) == 0) {
        showForm("کد پرداخت یافت نشد", "خطا!");
    }
    else {
        $payParam = $payInfo->fetch_assoc();
        $rowId = $payParam['id'];
        $amount = $payParam['price'];
        $user_id = $payParam['user_id'];
        $payType = $payParam['type'];
        $payid = $payParam['payid'];


        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://nextpay.org/nx/gateway/verify',
            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 => 'api_key=' . $paymentKeys['nextpay'] . '&amount=' . $amount . '&currency=IRT&trans_id=' . $payid,
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response);

        if ($response->code == '0') {
            doAction($rowId, "nextpay");
        }
        else {
            $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'canceled' WHERE `hash_id` = ?");
            $stmt->bind_param("s", $hash_id);
            $stmt->execute();
            $stmt->close();

            showForm("پرداخت شما انجام نشد!", "درگاه نکست پی");
        }
    }
}
else {
    showForm("درگاه پرداخت شناسایی نشد", "خطا!");
    exit();
}


include_once 'do_action.php';

function showForm($msg, $type = "", $state = false)
{
?>
<html dir="rtl">

<head>
    <script>
        (function (w, d, s, l, i) {
            w[l] = w[l] || [];
            w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js', });
            var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : '';
            j.async = true; j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl + '&gtm_auth=&gtm_preview=&gtm_cookies_win=x';
            f.parentNode.insertBefore(j, f);
        })(window, document, 'script', 'dataLayer', 'GTM-MSN6P6G');</script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>
        <?php echo $type; ?>
    </title>
    <meta name="next-head-count" content="4">
    <link rel="stylesheet" href="../assets/20bb620751bbea45.css">
    <noscript data-n-css=""></noscript>
</head>

<body style="margin: 0 auto;">
    <div id="__next">
        <section class="ant-layout ant-layout-rtl PayPing-layout background--primary justify-center"
            style="min-height:100vh">
            <main class="ant-layout-content justify-center align-center flex-column">
                <div class="ant-row ant-row-center ant-row-rtl PayPing-row w-100">
                    <div
                        class="ant-col PayPing-col PayPing-error-card ant-col-xs-23 ant-col-rtl ant-col-sm-20 ant-col-md-16 ant-col-lg-12 ant-col-xl-8 ant-col-xxl-6">
                        <div class="py-2 align-center color--danger flex-column">
                            <?php if (!$state) { ?><svg fill="none" stroke="currentColor" stroke-linecap="round"
                                stroke-linejoin="round" viewBox="0 0 24 24" class="PayPing-icon" stroke-width="1"
                                width="100">
                                <circle cx="12" cy="12" r="11"></circle>
                                <path d="M15.3 8.7l-6.6 6.6M8.7 8.7l6.6 6.6"></path>
                            </svg>
                            <?php
    }?>
                            <div class="py-2">
                                <?php echo $msg; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </section>
    </div>
</body>

</html>
<?php
}
?>