<?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($orderRef)
{
    //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 ref = ?");
    $stmt->execute([$orderRef]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    $redirectUrl =  siteUrl() . "/fizetes/" . $order["ref"];

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

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

function initializeNewOrder($prevOrder)
{

    $pdo = getConnection();

    $stmt = $pdo->prepare("SELECT * FROM `orderedProducts` WHERE `orderId` = ?");
    $stmt->execute([$prevOrder['id']]);
    $orderedProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $items = [];
    foreach ($orderedProducts as $orderedProduct) {
        $stmt = $pdo->prepare("SELECT * FROM `products` WHERE `id` = ?");
        $stmt->execute([$orderedProduct['productId']]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        $items[] = [
            'product' => $product,
            'quantity' => $orderedProduct['quantity'],
        ];
    }

    $ref = uniqid();
    $paymentUrl = getPaymentUrl($items, $ref);
    $stmt = $pdo->prepare("INSERT INTO `orders` (`userId`, `ref`, `status`, `paymentUrl`, `createdAt`) VALUES (?, ?, ?, ?, ?);");
    $stmt->execute([1, $ref, "STARTED", $paymentUrl, time()]);

    $orderId = $pdo->lastInsertId();

    foreach ($items as $item) {
        $stmt = $pdo->prepare("INSERT INTO `orderedProducts` (`productId`, `orderId`, `quantity`) VALUES (?, ?, ?);");
        $stmt->execute([$item['product']['id'], $orderId, $item['quantity']]);
    }

    return $ref;
}
