<?php
/**
 * Worldpay 2 payment integration script that proofs the 3DS response
 * @author Rihards Siliņš
 * @version 1 12/07/2016
 */

use Worldpay\Worldpay;
use Worldpay\WorldpayException;
use Mtc\Shop\Checkout\WorldpayLog;
use Mtc\Shop\Checkout\OrderWorldpay;


/**
 * The first request it to make sure 3ds callback doesn't reset
 * the session cookie -- which will lose the baset and log
 * the user out -- by making sure the request is sent
 * from the website itself.
 */

if (isset($_GET['resend'])) {

    $p = $_REQUEST;
    unset($p['resend']); // To avoid an infinite redirect loop.

    $url = '/shop/checkout/worldpay/3ds_response_check.php';
    $url .= '?' . http_build_query($p);

    header("Location: {$url}");

    exit;
}


/**
 * This second request continues here.
 */

$path = "../../../";
require($path .'core/includes/header.inc.php');


WorldpayLog::saveResponse(json_encode(request()->input()), request()->input('order_id'), '3ds_callback');

if (empty($_REQUEST['PaRes'])) {
    header("HTTP/1.0 400 Bad Request");
    exit();
}

if (empty($_REQUEST['MD'])) {
    header("HTTP/1.0 400 Bad Request");
    exit();
}

$order_id = $_REQUEST['MD'];

$order = new Order($order_id);
$order_eloquent = $order->eloquent();

$worldpay = new Worldpay(WORLDPAY_SERVICE_KEY);

try {
    if (empty($_SESSION['worldpay_sessionid'])) {
        $_SESSION['worldpay_sessionid'] = $order_eloquent->worldpay_session_id;
    }

    $response = $worldpay->authorize3DSOrder(
        $order_eloquent->worldpay_order_code,
        $_REQUEST['PaRes']
    );

    WorldpayLog::saveResponse(json_encode($response), request()->input('order_id'), '3ds_response');

    if (isset($response['paymentStatus']) && $response['paymentStatus'] == 'SUCCESS') {
        $paymentExists = OrderWorldpay::query()
            ->where('transId', $order_eloquent->worldpay_order_code)
            ->exists();
        if (!$paymentExists) {
            if (Order::amountsMatch($order->getTotalCost(), ($response['amount'] / 100))) {
                $order->markPaid(\Order::PAYMENT_TYPE_WORLDPAY);
                $order->saveWorldpay($response);
                if (PPC_TRACKING) {
                    track('sale', $order->getTotalCost(), $order->ref, $order->keywords);
                }
                $order->sendOrderConfirmation();
            }
        }

        $success_url = OrderWorldpay::getOrderCompleteURL($order_id);

        header("HTTP/1.0 200 OK");
        header("Location: {$success_url}");

        exit();

    } else {
        header("HTTP/1.0 502 Bad Gateway");
        header("Location: /shop/checkout/basket_overview.php?worldpay_error=failed_3ds");

        exit();
    }

} catch (WorldpayException $e) {

    WorldpayLog::saveResponse(var_export($e->getMessage(), true), request()->input('order_id'), '3ds_exception');
    header("HTTP/1.0 502 Bad Gateway");
    header("Location: /shop/checkout/basket_overview.php?worldpay_error=failed_3ds");

    exit();

}
