<?php
/**
 * @author: Uldis Zvirbulis <uldis.zvirbulis@mtcmedia.co.uk>
 * @version: 11/7/2017
 */

use \Mtc\Plugins\EvoPay\Classes\EvoPay;
use \Illuminate\Support\Facades\DB;

if (!isset($path)) {
    $path = '../../';
    require_once $path . 'core/includes/header.inc.php';
}

unset($_SESSION['order_id']);

$request = $_REQUEST;

$data = EvoPay::processResponse($request);

// Only skip the validation if DEV mode and Evopay test mode
$skip_validation = DEV_MODE && EVOPAY_TEST_MODE;
//$skip_validation = false;

if ((in_array($data['Status'], ['OK', 'AUTHORIZED'], true) && !empty($data['TransID'])) || $skip_validation) {
    $rawTransId = $data['TransID'] ?? null;
    $order_id = EvoPay::extractOrderId($rawTransId);

    if ($order_id === null) {
        $skip_validation = false;
    } elseif (!DB::table('order_evopay')->where('order_id', $order_id)->first()) {
        \Mtc\Shop\Order::query()
            ->where('id', $order_id)
            ->update(['order_ref' => $rawTransId]);

        $order = new Order($order_id);

        $order->markPaid();

        DB::table('order_evopay')->insert([
            'order_id' => $order_id,
            'amount_paid' => $order->getTotalCost(),
            'tnx_id' => $rawTransId,
            'paid_time' => date('Y-m-d H:i:s'),
        ]);

        if (PPC_TRACKING) {
            track('sale', $order->getTotalCost(), $order->ref, $order->keywords);
        }
        $order->sendOrderConfirmation();

        $_SESSION['order_id'] = $order->getId();
        $_SESSION['basket_id'] = '';

        if (GOOGLE_ANALYTICS_USERAGENT != '') {
            $tracking_code[] = $GLOBALS['twig']->render('analytics_js.twig', [
                'order'    => $order,
                'settings' => $GLOBALS['settings'],
            ]);
        }
    } else {
        \Mtc\Shop\Order::query()
            ->where('id', $order_id)
            ->update(['order_ref' => $rawTransId]);
        $order = new Order($order_id);
    }
}

if ($action === 'success' || $skip_validation) {
    echo $twig->render('Evopay\redirect.twig', [
        'url' => SITE_URL . '/plugins/EvoPay/evopay_complete.php',
    ]);
} elseif ($action === 'failure') {
    echo $twig->render('Evopay\redirect.twig', [
        'url' => SITE_URL . '/plugins/EvoPay/evopay_failed.php',
    ]);
}
