<?php
declare(strict_types=1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

define('ROOT', $_SERVER['DOCUMENT_ROOT']);

include_once ROOT . '/sys/db.php';


$sett = $pdo->query("SELECT key_yoo, key_payeer FROM `sett` LIMIT 1")->fetch();

$mode = $_GET['mode'] ?? '';


switch ($mode) {

    case 'yoomoney':
        $amount = $_POST['withdraw_amount'] ?? 0;

        $notification_type = $_POST['notification_type'] ?? '';
        $operation_id = $_POST['operation_id'] ?? '';
        $amount_hash = $_POST['amount'] ?? 0;
        $currency = $_POST['currency'] ?? '';
        $datetime = $_POST['datetime'] ?? '';
        $sender = $_POST['sender'] ?? '';
        $codepro = $_POST['codepro'] ?? '';
        $order_id = $_POST['label'] ?? '';
        $sha1_hash = $_POST['sha1_hash'] ?? '';
        $notification_secret = $sett['key_yoo'];

        $hash_string = implode('&', [
            $notification_type,
            $operation_id,
            $amount_hash,
            $currency,
            $datetime,
            $sender,
            $codepro,
            $notification_secret,
            $order_id
        ]);

        $expected_hash = sha1($hash_string);

        file_put_contents(ROOT . '/yoo.txt', print_r($_REQUEST, true) . PHP_EOL, FILE_APPEND);

        if (!hash_equals($expected_hash, $sha1_hash)) {
            http_response_code(400);
            die('Ошибка проверки подлинности уведомления');
        }

        break;
    case 'payeer':

        $order_id = $_POST['m_orderid'] ?? '';
        $amount = $_POST['m_amount'] ?? '';

        $arHash = [
            $_POST['m_operation_id'] ?? '',
            $_POST['m_operation_ps'] ?? '',
            $_POST['m_operation_date'] ?? '',
            $_POST['m_operation_pay_date'] ?? '',
            $_POST['m_shop'] ?? '',
            $order_id,
            $amount,
            $_POST['m_curr'] ?? '',
            $_POST['m_desc'] ?? '',
            $_POST['m_status'] ?? '',
            $sett['key_payeer'] ?? ''
        ];

        $sign_hash = strtoupper(hash('sha256', implode(':', $arHash)));

        file_put_contents(ROOT . '/payeer.txt', print_r($_REQUEST, true) . PHP_EOL, FILE_APPEND);

        $m_sign = !empty($_POST['m_sign']) ? $_POST['m_sign'] : '';

        if (!hash_equals($sign_hash, $m_sign)) {
            die($order_id . '|error');
        }
        break;
    default:
        http_response_code(404);
}


if (!empty($order_id)) {

    $sql_iframe = "SELECT `id`, `summa`, `status` FROM `iframe` WHERE `id_hash` = ? and `status` = ? LIMIT 1";

    $getIframeSmtp = $pdo->prepare($sql_iframe);
    $getIframeSmtp->execute([
        $order_id, 0
    ]);

    $getIframe = $getIframeSmtp->fetch();

    $sql_ads = "SELECT `id`, `summa`, `status` FROM `reklama` WHERE `id_hash` = ? and `status` = ? LIMIT 1";

    $getAdsSmtp = $pdo->prepare($sql_ads);
    $getAdsSmtp->execute([
        $order_id, 0
    ]);

    $getAds = $getAdsSmtp->fetch();

    if (empty($getIframe) && empty($getAds)) {
        http_response_code(400);
        die('Заказ не найден в системе');
    }

    if (!empty($getIframe) && $getIframe['status'] == 0) {
        if (floatval($getIframe['summa']) != floatval($amount)) {
            http_response_code(400);
            die('Несоответствие суммы платежа сумме заказа');
        }
        $pdo->query("UPDATE `iframe` SET `status` = '1' WHERE `id` = " . $getIframe['id']);
    }

    if (!empty($getAds) && $getAds['status'] == 0) {
        if (floatval($getAds['summa']) != floatval($amount)) {
            http_response_code(400);
            die('Несоответствие суммы платежа сумме заказа');
        }
        $pdo->query("UPDATE `reklama` SET `status` = '1' WHERE `id` = " . $getAds['id']);
    }
    http_response_code(200);

    // если payeer, возвращаем ответ
    // https://payeer.com/ru/account/api/
    if (!empty($_GET['mode']) && $_GET['mode'] == 'payeer' && $_POST['m_status'] == 'success') {
        die($order_id . '|success');
    }

    die('OK');
}
http_response_code(400);