<?php
/**
 * Worldpay 2 payment integration script that sets up and send call to WorldPay
 * @author Rihards Siliņš
 * @version 1 12/07/2016
 */

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

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

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

if (!defined('WORLDPAY') || WORLDPAY == false) {
    header("HTTP/1.0 501 Not Implemented");
    exit();
}

if (empty($_POST['order_id'])) {
    header("HTTP/1.0 400 Bad Request");
    exit("Order id not found");
}

if (empty($_POST['token'])) {
    header("HTTP/1.0 400 Bad Request");
    exit("Token not found");
}

if (empty($_POST['name'])) {
    header("HTTP/1.0 400 Bad Request");
    exit("Name not found");
}

$order = new Order($_POST['order_id']);
$order_eloquent = $order->eloquent();

if (empty($order->getId())) {
    header("HTTP/1.0 400 Bad Request");
    exit("No such order");
}


$worldpay = new Worldpay(WORLDPAY_SERVICE_KEY);
// Testing exceptions https://online.worldpay.com/docs/testing
if (!in_array($_POST['name'], ["FAILED",  "SUCCESS", "ERROR"])) {
    $_POST['name'] = "3D";
}

try {
    $data = [
        'token'                 => $_POST['token'],
        'amount'                => $order->getTotalCost() * 100,
        'currencyCode'          => 'GBP',
        'name'                  => $_POST['name'],
        'billingAddress'        => [
            'address1'              => $order->address['billing']['address1'],
            'address2'              => $order->address['billing']['address2'],
            'address3'              => '',
            'postalCode'            => $order->address['billing']['postcode'],
            'city'                  => $order->address['billing']['city'],
            'state'                 => $order->address['billing']['state'],
            'countryCode'           => $order->address['billing']['country'],
            'telephoneNumber'       => $order->info['contact_no']
        ],
        'orderDescription'      => config('app.name') . " Order:".$order->getId(),
        'customerOrderCode'     => $order->getId(),
        'is3DSOrder'            => true,
        'shopperAcceptHeader'   => $_SERVER['HTTP_ACCEPT']
    ];
    $response = $worldpay->createOrder($data);

    WorldpayLog::saveResponse(json_encode($response), $order->getId(), 'capture_response');

    $_SESSION['worldpayOrderCode'] = $response['orderCode'];

    $order_eloquent->worldpay_order_code = $response['orderCode'];
    $order_eloquent->worldpay_session_id = $_SESSION['worldpay_sessionid'];

    $order_eloquent->save();

    header("HTTP/1.0 200 OK");
    echo json_encode($response);

} catch (Exception $e) {
    header("HTTP/1.0 502 Bad Gateway");
    echo 'Error message: '. $e->getMessage();
}
