<?php

use Mtc\Plugins\Judopay\Classes\Judopay;

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

error_reporting(E_ALL & ~E_WARNING);
header('Content-Type: application/json');

if (! Judopay::canExpressCheckout()) {
    http_response_code(401);
    echo
        json_encode([
            'code' => 401,
            'errors' => [
                [
                    'code' => 'shippingContactInvalid',
                    'field' => 'emailAddress',
                    'message' => 'You must be logged in and have passed ID check.Please feel free to contact us if you need any assistance.',
                ],
            ],
        ])
    ;
    die();
}

$basket = new Basket;
$res = [];
$errors = [];

$basket->Go_Basket();

if (! empty($address = $_POST['billingContact'] ?? '')) {
    $basket->setCustomerAddress('billing', array_merge($basket->address['billing'], [
        'firstname' => $address['givenName'],
        'lastname' => $address['familyName'],
        'address1' => array_shift($address['addressLines']) ?: '',
        'address2' => array_shift($address['addressLines']) ?: '',
        'country' => $address['countryCode'],
        'postcode' => $address['postalCode'],
        'city' => $address['locality'],
        'notes' => 'Apple Pay',
    ]));
} else {
    $errors[] = [
        'code' => 'billingContactInvalid',
        'field' => 'name',
        'message' => "We're sorry we are unable to process this order due to suspected account misuse. If you think this is an error, please contact us",
    ];
}

if (! empty($address = $_POST['shippingContact'] ?? '')) {
    $basket->setCustomerAddress('shipping', array_merge($basket->address['shipping'], [
        'firstname' => $address['givenName'],
        'lastname' => $address['familyName'],
        'address1' => array_shift($address['addressLines']) ?: '',
        'address2' => array_shift($address['addressLines']) ?: '',
        'country' => $address['countryCode'],
        'postcode' => $address['postalCode'],
        'city' => $address['locality'],
        'notes' => 'Apple Pay',
    ]));

    $basket->updateBillingAddressUsed(0);
} else {
    $errors[] = [
        'code' => 'billingContactInvalid',
        'field' => 'name',
        'message' => "We're sorry we are unable to process this order due to suspected account misuse. If you think this is an error, please contact us",
    ];
}

$basket->resetSession();

$basket = new \Basket;

$basket->Go_Basket();

$apay = new \Mtc\Plugins\Judopay\Classes\APay($basket);

if (empty($errors)) {
    $errors = $apay->validateBasket();
}

if (empty($errors)) {
    $basket = \Mtc\Shop\Order::newOrder($basket);
    $order = new \Order($_SESSION['order_id']);
    $judo = Judopay::getService();
    $payment = $judo->createPayment($basket, [
        'pkPayment' => [
            'token' => [
                'paymentNetwork' => $_POST['token']['paymentMethod']['network'] ?? '',
                'paymentData' => $_POST['token']['paymentData'] ?? '',
                'paymentInstrumentName' => $_POST['token']['paymentMethod']['displayName'] ?? '',
            ],
        ],
    ]);

    if (! Judopay::finalizePayment('apay', $order, $payment)) {
        $errors[] = [
            'code' => 'shippingContactInvalid',
            'field' => 'emailAddress',
            'message' =>
                'Unfortunately, your payment with '
                    .config('app.name')
                    .' was rejected. Please feel free to try again or get in touch with them so they can assist you in completing your order.',
        ];
    }
}

if (empty($errors)) {
    $res = [
        'code' => 200,
        'redirect' => '/shop/checkout/judopay/process/?method=apay',
    ];
} else {
    http_response_code(400);

    $res = [
        'code' => 400,
        'errors' => $errors,
    ];
}

echo json_encode($res);
die();
