<?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 (empty($_SESSION['basket_id'])) {
    http_response_code(403);
    die();
}

if (! Judopay::canExpressCheckout()) {
    echo
        json_encode([
            'transactionState' => 'ERROR',
            'error' => [
                'reason' => 'OTHER_ERROR',
                'message' => 'You must be logged in and have passed ID check.Please feel free to contact us if you need any assistance.',
            ],
            'payload' => null,
        ])
    ;
    die();
}

$basket = new Basket;
$error = null;

$basket->Go_Basket();

if (! empty($address = $_POST['shippingAddress'] ?? '')) {
    $name = explode(' ', $address['name'] ?? '');
    $phone = explode(' ', $address['phoneNumber'] ?? '');

    $basket->setCustomerAddress('billing', array_merge($basket->address['billing'], [
        'firstname' => trim(array_shift($name) ?: ''),
        'lastname' => trim(implode(' ', $name) ?: ''),
        'address1' => $address['address1'] ?? '',
        'address2' => $address['address2'] ?? '',
        'country' => $address['countryCode'] ?? '',
        'postcode' => $address['postalCode'] ?? '',
        'city' => $address['locality'] ?? '',
        'gender' => $member->gender ?? '',
        'notes' => 'Google Pay',
    ]));
    $basket->updateBillingAddressUsed(1);
} else {
    $error = [
        'reason' => 'OTHER_ERROR',
        'message' => "We're sorry we are unable to process this order due to incorrect details. If you think this is an error, please contact us",
    ];
}

$basket->resetSession();

$basket = new \Basket;

$basket->Go_Basket();

$gpay = new \Mtc\Plugins\Judopay\Classes\GPay($basket);

if (empty($error)) {
    $error = current($gpay->validateBasket());
}

if (empty($error)) {
    $basket = \Mtc\Shop\Order::newOrder($basket);
    $order = new \Order($_SESSION['order_id']);
    $judo = Judopay::getService();

    $session = $judo->createSession($basket);

    echo
        json_encode([
            'transactionState' => 'SUCCESS',
            'error' => null,
            'payload' => array_merge($session['data'], [
                'paymentSession' => $session['ref'],
                'sandbox' => config('judopay.testmode'),
                'transactionMode' => 'payment',
                'challengeRequestIndicator' => null,
                'scaExemption' => null,
                'delayedAuthorisation' => null,
                'apiToken' => judopayConfig('api_token'),
                'paymentMethodData' => $_POST['paymentMethodData'],
            ]),
        ])
    ;
    die();
}

if (! empty($error)) {
    $error['intent'] = 'PAYMENT_AUTHORIZATION';
}

echo
    json_encode([
        'transactionState' => empty($error) ? 'SUCCESS' : 'ERROR',
        'error' => $error,
        'payload' => null,
    ])
;
die();
