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

    $ip = check_ip();
    $system = "NixMoney";

    if ($nixmoney_alt_phrase === '*****************') {
        die('ERROR');
    }

    $string = $_REQUEST['PAYMENT_ID'].':'.$_REQUEST['PAYEE_ACCOUNT'].':'.$_REQUEST['PAYMENT_AMOUNT'].':'.$_REQUEST['PAYMENT_UNITS'].':'.$_REQUEST['PAYMENT_BATCH_NUM'].':'.$_REQUEST['PAYER_ACCOUNT'].':'.strtoupper(md5($nixmoney_alt_phrase)).':'.$_REQUEST['TIMESTAMPGMT'];

    $hash = strtoupper(md5($string));
    if($hash === $_REQUEST['V2_HASH']) {
        $id = (int)(isset($_REQUEST['PAYMENT_ID']) ? $_REQUEST['PAYMENT_ID'] : 0);
        $m_amount = isset($_REQUEST['PAYMENT_AMOUNT']) ? $_REQUEST['PAYMENT_AMOUNT'] : 0;
        $m_amount = format_money($m_amount);
        $transaction = $_REQUEST['PAYMENT_BATCH_NUM'];
        //$currency = $_REQUEST['PAYMENT_UNITS'];
        //log_write(["Входные параметры", $id, $m_amount, $transaction, $currency]);

        $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` = '0' LIMIT 1;";
        $result = $mysqli->query($sql);
        if ($result->num_rows !== 1) {
            die('ERROR');
        }
        $row = $result->fetch_assoc();
        if (!$row) {
            die('ERROR');
        }
        if ($row["status"]) {
            die('ERROR');
        }
        //исправление безопасности
        if ($row["system"] !== $system) {
           log_write(['Подмена системы', $_POST, $_GET, $_SESSION, $_SERVER]);
           die('Подмена системы');
        }
        //получаем данные из платежа
        $summa = $row['summa'];		//сумма
        $exch_rate = $row['exch_rate'];	//курс валюты
        $login = $row['login'];			//логин
        $invest_id = $id;
        $currency = $val;//валюта пополнения

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

        if (format_money($m_amount) !== format_money($summa_check)) {
            die('|error');
        }

        //если суммы совпали, обновляем статус платежа.
        $sql = "UPDATE `invest` SET `status`= '1', `transaction` = ".escape_db($transaction)." WHERE `id` = ".escape_db($id)." LIMIT 1;";
        if (!$mysqli->query($sql)) {
            die('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'");

        exit(0);
    } else {
        log_write([
            "Ошибка соли",
            $hash, $_REQUEST['V2_HASH'],
            $_REQUEST,
        ]);
        die('ERROR');
    }
