<?php

$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;
}

$basket = new Basket();

$basket->Go_Basket();

switch($_POST['callbackTrigger']) {
    case 'INITIALIZE':
    case 'SHIPPING_OPTION':
    case 'SHIPPING_ADDRESS':
        if(!empty($address = $_POST['shippingAddress'] ?? NULL)) {
            $basket->setCustomerAddress('billing', array_merge($basket->address['billing'], [
                'country'       => $address['countryCode'],
                'postcode'      => $address['postalCode'],
                'city'          => $address['locality'],
            ]));
            $basket->updateBillingAddressUsed(1);
        }

        if(!empty($delivery = $_POST['shippingOptionData'] ?? NULL)) {
            $basket->delivery_selected = (int) $delivery['id'];
            $basket->Set_Delivery_Cost();
        }
        break;
    default:
        http_response_code(401);
        die;
        break;
}

$basket->resetSession();

$basket = new \Basket();

$basket->Go_Basket();

$gpay = new \Mtc\Plugins\Judopay\Classes\GPay($basket);
$res = $gpay->getPaymentDataRequestUpdate();

if(!empty($res['error'])) {
    $res['error']['intent'] = $_POST['callbackTrigger'];

    if($_POST['callbackTrigger'] == 'INITIALIZE') {
        unset($res['error']);
    }
}

echo json_encode($res);
die;
