<?php

namespace EstatebudConnect\Core;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Core\Log;
use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Utilities\Helper;

class Locale
{
    protected $_terms = [];
    protected $_dynamic_terms = null;
    protected $_enabled_languages = null;

    use Singleton;

    public function get_localization_plugin()
    {
        if (function_exists('pll_languages_list') && function_exists('pll_home_url')) {
            return 'Polylang';
        }

        if (function_exists('icl_get_languages')) {
            return 'WPML';
        }

        if (class_exists('TRP_Translate_Press')) {
            return 'TranslatePress';
        }

        if (function_exists('weglot_get_languages_available') && function_exists('weglot_get_destination_languages') && function_exists('weglot_get_original_language') && function_exists('weglot_get_current_language')) {
            return 'Weglot';
        }

        return 'WordPress';
    }

    public function get_home_url($locale = null)
    {
        if (is_null($locale)) {
            $locale = $this->get_locale();
        }

        $target_language = $this->get_language($locale);
        $home_url = $target_language['home_url'] ?? home_url();

        return $home_url;
    }

    public function set_urls($languages = [], $payload = null)
    {
        $plugin = $this->get_localization_plugin();

        if ($plugin !== 'WordPress') {
            $service_class = "\\EstatebudConnect\\Services\\{$plugin}";
            if (class_exists($service_class)) {
                $service = $service_class::instance();
                return $service->set_urls($languages, $payload);
            }
        }

        return $payload;
    }

    public function get_enabled_languages()
    {
        if (!empty($this->_enabled_languages)) {
            return $this->_enabled_languages;
        }
        
        $plugin = $this->get_localization_plugin();

        if ($plugin !== 'WordPress') {
            $service_class = "\\EstatebudConnect\\Services\\{$plugin}";
            if (class_exists($service_class)) {
                $service = $service_class::instance();
                $languages = $service->get_enabled_languages();
                if (!empty($languages)) {
                    $this->_enabled_languages = $languages;
                }
            }
        }

        if (!isset($languages)) {
            $this->_enabled_languages = $this->get_wordpress_default_language();
        }

        return $this->_enabled_languages;
    }

    public function get_language($locale = null)
    {
        $locale = explode('_', str_replace("-", "_", $locale))[0];
        $enabled_languages = $this->get_enabled_languages();

        foreach ($enabled_languages as $language) {
            $code = explode('_', str_replace("-", "_", $language['code']))[0];

            if ($code == $locale) {
                return $language;
            }
        }
        
        return null;
    }

    public function get_locale()
    {
        $plugin = $this->get_localization_plugin();

        if ($plugin !== 'WordPress') {
            $service_class = "\\EstatebudConnect\\Services\\{$plugin}";
            if (class_exists($service_class)) {
                $service = $service_class::instance();
                return $service->get_locale();
            }
        }

        return get_locale();
    }

    public function get_wordpress_default_language()
    {
        $locale = Helper::get_locale();

        return [
            [
                'code' => $locale,
                'name' => Helper::get_locale_display_name($locale, $locale . ' (intl extension not installed)'),
                'flag' => '',
                'home_url' => home_url(),
                'slug' => '',
                'active' => true,
            ],
        ];
    }

    public function load($language)
    {
        $locale_dir = realpath(plugin_dir_path(__DIR__) . 'Locales/');
        $file = $language . '.json';

        if (!file_exists($locale_dir . '/' . $file)) {
            $language_only = explode("_", str_replace("-", "_", $language))[0];
            $file = $language_only . '.json';
        }

        if (file_exists($locale_dir . '/' . $file)) {
            $json = file_get_contents($locale_dir . '/' . $file);
            $terms = json_decode($json, true);

            $this->_terms[$language] = $terms;
        }

        return isset($terms);
    }

    public function get_terms($language)
    {
        if (!isset($this->_terms[$language])) {
            self::load($language);
        }

        return $this->_terms[$language] ?? [];
    }

    public function get_term($key, $count = null, $language = null)
    {
        $terms = self::get_terms($language);
        $i = array_search($key, array_column($terms, 'key'));

        $variant = $count == 1 ? 'one' : 'other';

        if ($i !== false && isset($terms[$i]['value'][$variant])) {
            $term = $terms[$i]['value'][$variant];
        } else if($i !== false && isset($terms[$i]['value'])) {
            $term = $terms[$i]['value'];
        }

        if (!isset($term)) {
            $dynamic_terms = self::get_dynamic_terms();
            $i = array_search($key, array_column($dynamic_terms, 'key'));

            if ($i !== false) {
                $term = $dynamic_terms[$i]['value'];
            }
        }

        return $term ?? null;
    }

    public function get_dynamic_terms()
    {
        if (is_null($this->_dynamic_terms)) {
            $this->_dynamic_terms = Helper::get_translatable_dynamic_terms();
        }

        return $this->_dynamic_terms;
    }
}
