<?php
	require_once(__DIR__."/../../conf.php");

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

	if (is_post()) {
	    if ($advcash_sci_secret === '*****************') {
            die($_POST['ac_order_id'].'|error');
        }

		$ar_hash = array(
			post('ac_transfer'),
			post('ac_start_date'),
			post('ac_sci_name'),
			post('ac_src_wallet'),
			post('ac_dest_wallet'),
			post('ac_order_id'),
			post('ac_amount'),
			post('ac_merchant_currency'),
			$advcash_sci_secret
		);

		$sign_hash = hash('sha256', implode(':', $ar_hash));
		if (post('ac_hash') === $sign_hash) {
			$id = (int)post("ac_order_id");
			$m_amount = post("ac_amount");
			$m_amount = format_money($m_amount);
			$transaction = post('ac_transfer');//Транзакция

            $set = get_row_by_field('payment_system', 'name', $system);
            if (!$set) {
                log_write("Ошибка оплаты {$system}. Настройки по системе не получены.", $_POST);
                die($_POST['ac_order_id'].'|error');
            }

            if ($set['access'] !== 'advcash') {
                die($_POST['ac_order_id'].'|error');
            }

            $merchant_currency = post('ac_merchant_currency');
            if (strtolower(post('ac_merchant_currency')) === "rur") {
                $merchant_currency = 'rub';
            }

            if (strtolower($merchant_currency) !== strtolower($set['currency'])) {
                log_write(
                    "Ошибка оплаты {$system}. Подмена валюты.",
                    "Ответ от {$system}: ", $_POST, "Настройки системы: ",
                    $set, "Валюта платежа: ".strtolower($merchant_currency),
                    "Валюта в настройках: ".strtolower($set['currency'])
                );
                die($_POST['ac_order_id'].'|error');
            }

            $sql = "SELECT * FROM `invest` WHERE `id` = ".escape_db($id)." AND `status` = ".escape_db(0).condition_delete()." LIMIT 1;";
            $result = $mysqli->query($sql);
            if ($result->num_rows !== 1) {
                die($_POST['ac_order_id'].'|error');
            }
            $row = $result->fetch_assoc();
            if (!$row) {
                die($_POST['ac_order_id'].'|error');
            }

            if ($row["status"]) {
                die($_POST['ac_order_id'].'|error');
            }
            if ($row["delete"] == 0) {
                die($_POST['ac_order_id'].'|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($_POST['ac_order_id'].'|error');
            }

            $sql = "UPDATE `invest` SET `status`= '1', `transaction` = ".escape_db($transaction)." WHERE `id` = ".escape_db($id)." LIMIT 1;";
            if (!$mysqli->query($sql)) {
                die($_POST['ac_order_id'].'|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['ac_order_id'].'|success';
            exit(0);
        } else {
            die($_POST['ac_order_id'].'|error');
        }
	} else {
		die($_POST['ac_order_id'].'|error');
	}
