<?php

use Mtc\Core\Currency;

if (ENABLE_CURRENCIES === true) {

    $enabled_currencies = Currency::getEnabledCurrencies();

    // Set the currency based on whats been selected on client side
    if (!empty($_COOKIE['currency'])) {
        $_SESSION['selected_currency'] = $_COOKIE['currency'];
    }

    // Change currency if requested.

    if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'changecurrency') {

        if (!empty($_GET['currency'])) {
            if (in_array(strip_tags($_GET['currency']), array_keys($enabled_currencies))) {
                $_SESSION['selected_currency'] = $_GET['currency'];
                setcookie('currency', $_SESSION['selected_currency']);
            }
        }
    }

    if (!empty($_SERVER['REMOTE_ADDR']) && empty($_SESSION['selected_currency'])) {
        $location_array = @file_get_contents('http://www.geoplugin.net/json.gp?ip=' . $_SERVER['REMOTE_ADDR']);
        $location_details = @json_decode($location_array);

        if (json_last_error() === JSON_ERROR_NONE && !empty($location_details)) {
            if (floor($location_details->geoplugin_status / 100) == 2) { // accept any 2xx status code
                // Get the symbol for the returned currency code.
                $currency = Currency::getCurrencyFromCode($location_details->geoplugin_currencyCode);

                // If we have a currency code, update the session with it's details
                if (!empty($currency)) {
                    $_SESSION['currency'] = $currency;
                }
            }
        }
    }

} else {
    $_SESSION['selected_currency'] = 'GBP';
}

$_SESSION['currency'] = Currency::getCurrencyFromCode($_SESSION['selected_currency'] ?? null);

app('twig')->addGlobal('session_currency', $_SESSION['currency']);
