<?php

namespace Clonable\Services;

use Clonable\Helpers\Functions;
use Clonable\Helpers\Json;
use Clonable\Helpers\MultiCurrency as MultiCurrencyHelper;
use Clonable\Models\MultiCurrency;
use Clonable\Objects\ClonableConfig;
use Clonable\Traits\PluginCheck;

class MultiCurrencyService {
    use PluginCheck;

    public function __construct() {
        if ($this->curcy_multicurreny_installed() && get_option(MultiCurrency::CURCY_SUPPORT_SETTING, 'off') === 'on') {
            add_action("wp_head", array($this,'curcy_cookie_setter_script'), 1);
            add_action('init', [$this,'set_curcy_currency'], 1);
            add_action('clonable_before_page_translation', [$this,"set_curcy_currency"], 1);
        }

        if ($this->aelia_currency_installed() && get_option(MultiCurrency::AELIA_SUPPORT_SETTING, 'off') === 'on') {
            $default_value = MultiCurrency::$fields[MultiCurrency::MULTI_CURRENCY_FORCE_PER_CLONE] ? 'on' : 'off';
            $enforce_currency = get_option(MultiCurrency::MULTI_CURRENCY_FORCE_PER_CLONE, $default_value);

            if ($enforce_currency === 'on') {
                add_filter('wc_aelia_cs_selected_currency', [$this, 'set_aelia_currency'], 1);
            } else {
                $this->set_aelia_currency_cookies();
            }
        }
    }

    public function curcy_cookie_setter_script() {
        if (get_option(MultiCurrency::CURCY_SUPPORT_SETTING, 'off') !== 'on') {
            return;
        }

        if (is_admin()) {
            return;
        }

        $current_currency = $this->get_currency();
        if ($current_currency !== null) {
            ?>
<!-- WooCommerce Multi-Currency Cookie compatibility scripts -->
<script type="application/javascript">
    document.cookie = "wmc_current_currency=<?php echo esc_js($current_currency) ?>'; path=/";
    document.cookie = "wmc_current_currency_old=<?php echo esc_js($current_currency) ?>; path=/";
</script>
            <?php
        }
    }

    public function set_curcy_currency($url) {
        if (is_admin()) {
            return;
        }

        $current_currency = $this->get_currency();
        if (class_exists('WOOMULTI_CURRENCY_Data')) {
            $settings = \WOOMULTI_CURRENCY_Data::get_ins();
            $settings->set_current_currency($current_currency);
        }
    }

    private function get_currency() {
        $custom_currencies = get_option(
            MultiCurrency::backwards_compatibility(MultiCurrency::MULTI_CURRENCY_BY_CLONE)
        );

        $server_data = $_SERVER;
        $target_region = $server_data['HTTP_CLONABLE_TARGET_REGION'] ?? null;

        if (empty($custom_currencies)) {
            return MultiCurrencyHelper::get_currency_by_region($target_region);
        } else {
            $currency_data = Json::handle_input($custom_currencies);
            foreach ($currency_data as $currency) {
                if ($currency->target_region === $target_region) {
                    // If a custom currency has been defined, return that one instead of the custom one
                    return $currency->currency;
                }
            }
            return MultiCurrencyHelper::get_currency_by_region($target_region);
        }
    }

    /**
     * @param $selected_currency
     * @return mixed
     */
    public function set_aelia_currency($selected_currency) {
        $server_data = $_SERVER;
        $target_region = $server_data['HTTP_CLONABLE_TARGET_REGION'] ?? null;
        if($target_region === null) {
            return $selected_currency;
        }

        $currency = $this->get_currency_by_region($target_region);
        if ($currency !== null) {
            return $currency;
        }

        return $selected_currency;
    }

    public function set_aelia_currency_cookies() {
        $server_data = $_SERVER;
        $target_region = $server_data['HTTP_CLONABLE_TARGET_REGION'] ?? null;
        if($target_region === null) {
            return; // if we cannot detect a target region, then we should do nothing
        }

        $selected_currency = $_COOKIE['aelia_cs_selected_currency'] ?? null;
        if ($selected_currency !== null) {
            return; // this allows the user to keep their selected currency without being overridden.
        }

        $currency = $this->get_currency_by_region($target_region);
        if (function_exists('wc_setcookie')) {
            wc_setcookie('aelia_cs_selected_currency', $currency);
        }
        $user_id = get_current_user_id();
        if ($user_id !== 0) {
            update_user_meta($user_id, 'aelia_cs_selected_currency', $currency);
        }
    }

    /**
     * Get the currency that should be selected based on the target region
     * @param $target_region
     * @return null
     */
    private function get_currency_by_region($target_region) {
        $clone_currency_map = get_option(
            MultiCurrency::backwards_compatibility(MultiCurrency::MULTI_CURRENCY_BY_CLONE)
        );
        if ($clone_currency_map === false) {
            return null;
        }
        $currency_data = Json::handle_input($clone_currency_map);
        foreach ($currency_data as $currency) {
            if ($currency->target_region === $target_region) {
                // If a custom currency has been defined, return that one instead of the custom one
                return $currency->currency;
            }
        }
        return null;
    }
}