<?php
    $auto_depozit = true;
    //session_start();
    include_once(__DIR__."/../../conf.php");

    $id = (int)post('ok_invoice');
    $ip = check_ip();

    $system = "OkPay";
    //достаем заявку
    $sql = "SELECT * FROM `invest` WHERE `id` = ".escape_db($id)." AND `summa` = ".escape_db($m_amount)." AND `status` = ".escape_db(0).condition_delete()." LIMIT 1;";
    //$sql = "SELECT * FROM `invest` WHERE `id` = ".escape_db($id)." AND `status` = ".escape_db(0)." LIMIT 1;";
    $result = $mysqli->query($sql);
    if ($result->num_rows !== 1) {
        die($_POST['ok_invoice'].'|error');
    }
    $row = $result->fetch_assoc();
    if (!$row) {
        die($_POST['ok_invoice'].'|error');
    }
    $invest_id = $row["id"];//id пополнения

    if ($invest_id) {
        // Read the post from OKPAY and add 'ok_verify'
        $request = 'ok_verify=true';

        foreach ($_POST as $key => $value) {
            $value = urlencode(stripslashes($value));
            $request .= "&$key=$value";
        }

        $fsocket = false;
        $result = false;

        // Try to connect via SSL due sucurity reason
        if ( $fp = @fsockopen('ssl://checkout.okpay.com', 443, $errno, $errstr, 30) ) {
            // Connected via HTTPS
            $fsocket = true;
        } elseif ($fp = @fsockopen('checkout.okpay.com', 80, $errno, $errstr, 30)) {
            // Connected via HTTP
            $fsocket = true;
        }

        // If connected to OKPAY
        if ($fsocket == true) {
            $header = 'POST /ipn-verify HTTP/1.1' . "\r\n" .
                      'Host: checkout.okpay.com'."\r\n" .
                      'Content-Type: application/x-www-form-urlencoded' . "\r\n" .
                      'Content-Length: ' . strlen($request) . "\r\n" .
                      'Connection: close' . "\r\n\r\n";

            @fputs($fp, $header . $request);
            $string = '';
            while (!@feof($fp)) {
                $res = @fgets($fp, 1024);
                $string .= $res;
                // Find verification result in response
                if ( $res == 'VERIFIED' || $res == 'INVALID' || $res == 'TEST') {
                    $result = $res;
                    break;
                }
            }
            @fclose($fp);
        }

        if ($result === "VERIFIED" && post('ok_txn_status') == 'completed') {
            //выполняем действия - после успешной оплаты
            $transaction = escape(post("ok_txn_id"));
            $m_amount = format_money(post("ok_txn_gross"));
            $currency = escape(post("ok_txn_currency"));

            $sql = "SELECT * FROM `invest` WHERE `id` = ".escape_db($id)." AND `summa` = ".escape_db($m_amount)." AND `status` = ".escape_db(0)." LIMIT 1;";
            $result = $mysqli->query($sql);
            if ($result->num_rows !== 1) {
                die($_POST['ok_invoice'].'|error');
            }
            $row = $result->fetch_assoc();
            if (!$row) {
                die($_POST['ok_invoice'].'|error');
            }
            if ($row["status"]) {
                die($_POST['ok_invoice'].'|error');
            }
            //исправление безопасности
			if ($row["system"] !== $system) {
               log_write(['Подмена системы', $_POST, $_GET, $_SESSION, $_SERVER]);
               die('Подмена системы');
            }
            $login = $row['login'];//получаем логин
            $invest_id = $id;//получаем id пополнения
            $summa = $row['summa'];//сумма пополнения
            $exch_rate = $row['exch_rate'];
            $currency = $val;//валюта пополнения

            $summa_check = $summa;
            //если USD тогда высчитываем сумму пополнения в рублях и сравниваем.
            $summa_check = $summa_check * $exch_rate;

            if (format_money($m_amount) !== format_money($summa_check)) {
                die($_POST['ok_invoice'].'|error');
            }

            $sql = "UPDATE `invest` SET `status`= '1', `transaction` = ".escape_db($transaction)." WHERE `id` = ".escape_db($id)." LIMIT 1;";
            if (!$mysqli->query($sql)) {
                die($_POST['ok_invoice'].'|error');
            }

            $res = active_invest($invest_id);
            if ($res['error']) {
                log_write("ERROR: Пополнение на {$system}; MESSAGE: {$res['message']}", $res['data']);
            }
            $mysqli->query("UPDATE `cache` SET balans_invest = balans_invest + '$summa'");

            echo $_POST['ok_invoice'].'|success';
            exit(0);
        } else {
            header('HTTP/1.0 404 Not Found');
            die();
        }

        //curl_close($ch);
        die();
    } else {
        header('HTTP/1.0 404 Not Found');
        echo 'ERROR: Order not found!';
        return 0;
        die();
    }
