<?php

require_once '../../../../init.php';
require ROOTDIR . "/includes/orderfunctions.php";

// --- CSRF ---
$submittedToken = $_POST['token'] ?? '';
if (!hash_equals((string) generate_token("plain"), (string) $submittedToken)) {
    http_response_code(403);
    die(json_encode(['status' => '403', 'text' => 'Invalid CSRF token']));
}

$country = $_POST['country'] ?? '';
$state = $_POST['state'] ?? '';
if(isset($_GET['currency']))
    $currency = getCurrency(NULL, (int)WHMCS\Session::get("currency"));
else
    $currency = getCurrency(WHMCS\Session::get("uid"), WHMCS\Session::get("currency"));

if (isset($country) && !empty($country)){
    $_SESSION["cart"]["user"]["state"] = $state;
    $_SESSION["cart"]["user"]["country"] = $country;
    
    $response = new WHMCS\Http\JsonResponse();
    $response->setData(calcCartTotals(\Auth::client(), false, $currency));
    $response->send();
    WHMCS\Terminus::getInstance()->doExit();
}