<?php

    $auto_depozit = true;
  	//session_start();
  	require_once(__DIR__."/../../conf.php");
    //$system = "PayKassa";
	$ip = check_ip();
    // Fill these in with the information from your CoinPayments.net account.
    $coinpayments_merchant_id;
    $coinpayments_ipn_secret;
    $cp_debug_email = '';
    $system = 'BitCoin';

    //These would normally be loaded from your database, the most common way is to pass the Order ID through the 'custom' POST field.
    $order_currency = 'BTC';
    $order_total = 0.00000000;

    function errorAndDie($error_msg) {
        log_write(['message' => $error_msg, 'post' => $_POST, 'get' => $_GET, 'request' => $_REQUEST, 'server' => $_SERVER]);
        global $cp_debug_email;
        if (!empty($cp_debug_email)) {
            $report = 'Error: '.$error_msg."\n\n";
            $report .= "POST Data\n\n";
            foreach ($_POST as $k => $v) {
                $report .= "|$k| = |$v|\n";
            }
            mail($cp_debug_email, 'CoinPayments IPN Error', $report);
        }
        die('IPN Error: '.$error_msg);
    }

    if (!isset($_POST['ipn_mode']) || $_POST['ipn_mode'] != 'hmac') {
        errorAndDie('IPN Mode is not HMAC');
    }

    if (!isset($_SERVER['HTTP_HMAC']) || empty($_SERVER['HTTP_HMAC'])) {
        errorAndDie('No HMAC signature sent.');
    }

    $request = file_get_contents('php://input');
    if ($request === FALSE || empty($request)) {
        errorAndDie('Error reading POST data');
    }

    if (!isset($_POST['merchant']) || $_POST['merchant'] != trim($coinpayments_merchant_id)) {
        errorAndDie('No or incorrect Merchant ID passed');
    }

    $hmac = hash_hmac("sha512", $request, trim($coinpayments_ipn_secret));
    if ($hmac != $_SERVER['HTTP_HMAC']) {
        errorAndDie('HMAC signature does not match');
    }

    // HMAC Signature verified at this point, load some variables.

    $txn_id = $_POST['txn_id'];
    $item_name = $_POST['item_name'];
    $item_number = $_POST['item_number'];
    $amount1 = floatval($_POST['amount1']);
    $amount2 = floatval($_POST['amount2']);
    $currency1 = $_POST['currency1'];
    $currency2 = $_POST['currency2'];
    $status = intval($_POST['status']);
    $status_text = $_POST['status_text'];

    //depending on the API of your system, you may want to check and see if the transaction ID $txn_id has already been handled before at this point

    $sql = "SELECT * FROM `invest` WHERE `id` = ".escape_db($item_name)." AND `status` = ".escape_db(0).condition_delete()." LIMIT 1;";
    $result = $mysqli->query($sql);
    if ($result->num_rows !== 1) {
        errorAndDie('Такого платежа нет в системе, либо он уже подтвержден');
    }

    $row = $result->fetch_assoc();
    if (!$row) {
        errorAndDie('Такого платежа нет в системе, либо он уже подтвержден');
    }
    if ($row["status"]) {
        errorAndDie('Этот платеж уже подтвержден');
    }
    if ($row["delete"] == 0) {
        errorAndDie('Этот платеж удален');
    }
    //исправление безопасности
    if ($row["system"] !== $system) {
       errorAndDie('Подмена системы');
    }

    // Check the original currency to make sure the buyer didn't change it.
    if ($currency1 !== $order_currency) {
        errorAndDie('Original currency mismatch!');
    }

    // Check amount against order total
    if (sprintf("%01.6f", $amount1) !== sprintf("%01.6f", $row["summa"]*$row["exch_rate"])) {
        log_write(sprintf("%01.6f", $amount1), sprintf("%01.6f", $row["summa"]*$row["exch_rate"]), $row["summa"], $row["exch_rate"]);
        errorAndDie('Amount is less than order total!');
    }

    if ($status >= 100 || $status == 2) {
        log_write(['message' => 'payment is complete or queued for nightly payout, success', 'post' => $_POST, 'get' => $_GET, 'request' => $_REQUEST, 'server' => $_SERVER]);
        $sql = "UPDATE `invest` SET ";
        $sql .= " `status`= ".escape_db(1);
        $sql .= ", `transaction` = ".escape_db($txn_id);
        $sql .= " WHERE `id` = ".escape_db($row["id"]);
        $sql .= " LIMIT 1;";
        if (!$mysqli->query($sql)) {
            log_write("error_update", [
                'система'    => $system,
                'данные'     => $row,
                'SQL скрипт' => $sql,
            ]);
        }
        if($auto_depozit) {
            add_depozit_plans($row["login"], $row["summa"], $row["id"]);
        }
        add_operation_invest($row["login"], $row["summa"], $system, $row["id"]);
        //начисление реферальных
        accrued_referral_add_note("invest", $row["id"]);
        $sql = "UPDATE `cache` SET `balans_invest` = `balans_invest` + ".escape_db($row["summa"]);
        $mysqli->query($sql);
        log_write([
            $system,
            "accept_invest",
            $row,
        ]);
        // payment is complete or queued for nightly payout, success
    } else if ($status < 0) {
        log_write(['message' => 'payment error, this is usually final but payments will sometimes be reopened if there was no exchange rate conversion or with seller consent', 'post' => $_POST, 'get' => $_GET, 'request' => $_REQUEST, 'server' => $_SERVER]);
        // payment error, this is usually final but payments will sometimes be reopened if there was no exchange rate conversion or with seller consent
    } else {
        log_write(['message' => 'payment is pending, you can optionally add a note to the order page', 'post' => $_POST, 'get' => $_GET, 'request' => $_REQUEST, 'server' => $_SERVER]);
        // payment is pending, you can optionally add a note to the order page
    }
    die('IPN OK');
