<?php

/**
 *  Copyright (C) 2020 OTP Mobil Kft.
 *
 *  PHP version 7
 *
 *  This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  SDK
 * @package   SimplePayV2_SDK
 * @author    SimplePay IT Support <itsupport@otpmobil.com>
 * @copyright 2020 OTP Mobil Kft.
 * @license   http://www.gnu.org/licenses/gpl-3.0.html  GNU GENERAL PUBLIC LICENSE (GPL V3.0)
 * @link      http://simplepartner.hu/online_fizetesi_szolgaltatas.html
 */

function back($orderId)
{
    //Optional error riporting
    error_reporting(E_ALL);
    ini_set('display_errors', '1');

    //Import config data
    require_once 'src/config.php';

    //Import SimplePayment class
    require_once 'src/SimplePayV21.php';

    $trx = new SimplePayBack;

    $trx->addConfig($config);


    //result
    //-----------------------------------------------------------------------------------------
    $result = array();
    if (isset($_REQUEST['r']) && isset($_REQUEST['s'])) {
        if ($trx->isBackSignatureCheck($_REQUEST['r'], $_REQUEST['s'])) {
            $result = $trx->getRawNotification();
        }
    }

    $pdo = getConnection();
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$order['productId']]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    $redirectUrl =  siteUrl() . "/termekek/" . $product['slug'];

    switch ($result['e']) {
        case 'SUCCESS':
            updateOrderStatus('SUCCESS', $orderId);
            header('Location: ' . $redirectUrl . '?status=transactionSuccessful&orderRef=' . $result['o'] . '&transactionId=' . $result['t']);
            break;
        case 'FAIL':
            updateOrderStatus('FAIL', $orderId);
            initializeNewOrder($order);
            header('Location: ' . $redirectUrl . '?status=transactionFailed&transactionId=' . $result["t"]);
            break;
        case 'CANCEL':
            updateOrderStatus('CANCEL', $orderId);
            initializeNewOrder($order);
            header('Location: ' . $redirectUrl . '?status=transactionCancelled');
            break;
        case 'TIMEOUT':
            updateOrderStatus('TIMEOUT', $orderId);
            header('Location: ' . $redirectUrl . '?status=transactionTimeout');
            break;
    }
}

function updateOrderStatus($status, $orderId)
{
    $pdo = getConnection();
    $stmt = $pdo->prepare("UPDATE `orders` SET `status` = ? WHERE `orders`.`id` = ?;");
    $stmt->execute([$status, $orderId]);
}

function initializeNewOrder($order)
{
    $pdo = getConnection();
    $stmt = $pdo->prepare("INSERT INTO `orders` (`userId`, `productId`, `ref`, `status`) VALUES (?, ?, ?, ?);");
    $stmt->execute([$order['userId'], $order['productId'], uniqid(), "INITIALIZED"]);
}