<?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) {
    $order_id = $data['TransID'];

    if (!DB::table('order_evopay')->where('order_id', $order_id)->first()) {
        $order = new Order($order_id);

        $order->markPaid();

        DB::table('order_evopay')->insert([
            'order_id' => $order_id,
            'amount_paid' => $order->getTotalCost(),
            'tnx_id' => $order_id,
            '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 {
        $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',
    ]);
}