<?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);

// The app.env check repeats what DEV_MODE already implies — defence in depth so
// the bypass can never be true on production.
$skip_validation = DEV_MODE
    && (defined('EVOPAY_TEST_MODE') && EVOPAY_TEST_MODE)
    && config('app.env') !== 'production';

$mac_valid = EvoPay::verifyResponseMac($data);

if ((in_array($data['Status'], ['OK', 'AUTHORIZED'], true) && !empty($data['TransID']) && $mac_valid) || $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_ref was recorded above, so a rejected attempt stays traceable.
        if (!$skip_validation && !EvoPay::verifyResponseAmount($data, $order)) {
            echo $twig->render('Evopay\redirect.twig', [
                'url' => SITE_URL . '/plugins/EvoPay/evopay_failed.php',
            ]);
            die;
        }

        $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',
    ]);
}
