<?php
require_once(__DIR__."/../../conf.php");
use Qiwi\QiwiApi;

$list = get_list("invest", "`system` = ".escape_db('Qiwi')." AND `status` = ".escape_db(0));

if ($qiwi_auto_invest === "off") {
    log_write("cron/auto_invest_qiwi.php: Пополнения на киви выключены, включите их в таблицы payment_system"); die();
}

$phone = $qiwi_invest_phone;
$password = $qiwi_invest_password;
$token = $qiwi_invest_password;
//проверка суммы по комментарию.
$function = 'qiwi_get_info_by_transaction';
/*$qiwi = new QiwiApi($phone, $token);
$history = $qiwi->getHistoryList();*/

foreach ($list as $item) {
    $id = $item['id'];
    $id_oreder = "#".$id;
    $transaction = $item['transaction'];
    /*if ($qiwi_auto_invest === 'on') {
        if (!$history['error']) {
            foreach ($history['data']['list'] as $his) {
                if ($item['transaction'] == $his['transaction'] && $his['status'] === 'success') {
                    $summa_check = $item["summa"] * $item["exch_rate"];
                    if (format_money($summa_check) === format_money($his['sum'])) {
                        $sql = "UPDATE `invest` SET `status`= '1' WHERE `transaction` = ".escape_db($his['transaction'])." LIMIT 1;";
                        if (!$mysqli->query($sql)) {
                            log_write(555, $mysqli->error);
                        } else {
                            if($auto_depozit) {
                                add_depozit_plans($item['login'], $item['summa'], $id);
                            }
                            add_operation_invest($item['login'], $item['summa'], $item['system'], $id);
                            //начисление реферальных
                            accrued_referral_add_note($item['login'], $item['summa'], $item['currency'], $item['system'], 'invest', $id);
                            $mysqli->query("UPDATE `cache` SET balans_invest = balans_invest + " . escape_db($item['summa']));
                        }
                    } else {
                        log_write(444, format_money($summa_check) === $summa_check($his['sum']), format_money($summa_check), $summa_check($his['sum']));
                    }
                } else {
                    log_write(333, $item['transaction'] == $his['transaction'], $item['transaction'], $his['transaction'], $item);
                }
            }
        } else {
            log_write(222, $history);
        }
    } else {
        log_write(111, $qiwi_auto_invest);
    }
    continue;*/
    //проверка по комментарию
    if ($function === 'qiwi_get_info_by_transaction') {
        if (!$transaction) {
            log_write("cron/auto_invest_qiwi.php: Транзакция пуста!");
            continue;
        }
        $currency = $item['currency'];

        //обработка через hyiponline24.ru
        if (true) {
            $wallet = new BM_FullQiwi($phone, $password);
            $result_qiwi['data'] = $wallet->check_by_transaction($transaction);
            var_dump($result_qiwi);
        } else {
            $result_qiwi = qiwi_get_info_by_comment($phone, $password, $id_oreder);
        }

        //результат запроса
        if (!$result_qiwi) {
            continue;
        }
        if ($result_qiwi["error"])
            //echo "Платеж не найден!<br>";
            continue;

        if ($result_qiwi['data']['type'] === 'income' &&  $result_qiwi['data']['status'] === 'success') {
        } else {
            log_write(["cron/auto_invest_qiwi.php: Проверка платежа: ", $result_qiwi]);
            continue;
        }

        $m_amount = $result_qiwi['data']['sum'];

        $summa_check = $item["summa"];
        if ($item["currency"] === "USD") {
            //если USD тогда высчитываем сумму пополнения в рублях и сравниваем.
            $summa_check = $summa_check * $item["exch_rate"];
        }

        if (format_money($m_amount) !== format_money($summa_check)) {
            log_write(["cron/auto_invest_qiwi.php: Проверка платежа: суммы не совпадают", $m_amount, $summa_check, $item["exch_rate"]]);
            continue;
        }

        $qiwi_currency = 'none';
        switch ($item['currency']) {
            case 'RUB': $qiwi_currency = 643; break;
            case 'USD': $qiwi_currency = 840; break;
            case 'EUR': $qiwi_currency = 978; break;
        }

        if ($result_qiwi['data']['currency'] !== $qiwi_currency) {
            log_write(["cron/auto_invest_qiwi.php: Валюты не совпадают: ", $result_qiwi, $item]);
            continue;
        }


        $m_amount = $item["summa"];

        if (!$m_amount) {
            log_write(["cron/auto_invest_qiwi.php: Сумма не существует: ", $m_amount, $result_qiwi]);
            continue;
        }
        $m_amount = format_money($m_amount);

        $transaction = $result_qiwi['data']['transaction'];

        $sql = "SELECT * FROM `invest` WHERE `id` = ".escape_db($id)." AND `summa` = ".escape_db($m_amount)." AND `status` = ".escape_db(0).condition_delete()." LIMIT 1;";

        $result = $mysqli->query($sql);
        if ($result->num_rows !== 1) {
            log_write(["cron/auto_invest_qiwi.php: Ошибка запроса: ", $sql, $result]);
            continue;
        }
        $row = $result->fetch_assoc();
        if (!$row) {
            log_write(["cron/auto_invest_qiwi.php: Ошибка запроса: ", $sql, $result, $row]);
            continue;
        }
        if ($row["status"]) {
            log_write(["cron/auto_invest_qiwi.php: Платеж уже оплачен: ", $sql, $row]);
            continue;
        }
        if ($row["delete"] == 0) {
            log_write(["cron/auto_invest_qiwi.php: Заявка была удалена: ", $sql, $row]);
            continue;
        }

        $login = $row['login'];//получаем логин
        $invest_id = $id;//получаем id пополнения
        $summa = $row['summa'];//сумма пополнения
        $exch_rate = $row['exch_rate'];
        $currency = $val;//сумма пополнения
        $system = $row['system'];

        $sql = "UPDATE `invest` SET `status`= '1', `transaction` = ".escape_db($transaction)." WHERE `id` = ".escape_db($id)." LIMIT 1;";
        if (!$mysqli->query($sql)) {
            log_write(["cron/auto_invest_qiwi.php: Не удалось обновить запись о пополнении и установить номер транзакции: ", $sql, $transaction, $id]);
            continue;
        }
        if($auto_depozit) {
            add_depozit_plans($login, $summa, $invest_id);
        }
        add_operation_invest($login, $summa, $system, $invest_id);
        //начисление реферальных
        accrued_referral_add_note($login, $summa, $currency, $system, "invest", $invest_id);
        $mysqli->query("UPDATE `cache` SET balans_invest = balans_invest + '$summa'");
    }
}
