<?php
namespace OxygenApp\Utils;
if ( ! defined( 'ABSPATH' ) ) exit;

use OxygenApp\Utils\OptionUtils;
use OxygenApp\Config\Config;
use OxygenApp\Config\DefaultLabels;
use OxygenApp\Config\Flags;
use OxygenApp\Utils\OxySession;

class LanguagesHelper {

    private static $instance = null;
    private array $labels = [];
    private bool $isRtl = false;
    private array $langCodes = [];
    private string $currentLanguageCode = '';

    private function __construct() {

        $languahesMetaKey = Config::getInstance()->getSetting('languages_meta_key');
        $langs = OptionUtils::getInstance()->getOption($languahesMetaKey);
        $langCode = self::getCurrentLanguageCode();

        if (is_array($langs)) {

            $this->labels = $langs[$langCode]['labels'] ?? [];
            $this->isRtl = ($langs[$langCode]['rtl'] ?? '') === 'on';
            $this->langCodes = array_keys($langs);

        } else {

            $defaultLanguage = DefaultLabels::getDefaultLanguage();
            if (is_array($defaultLanguage) && isset($defaultLanguage['code']) && $defaultLanguage['code'] === $langCode) {
                $this->isRtl = ($defaultLanguage['rtl'] ?? '') === 'on';
                $this->langCodes = [$defaultLanguage['code'] ?? ''];
                $transformed = ['labels' => []];
                $defaultLabels = $defaultLanguage['labels'] ?? [];
                foreach ($defaultLabels as $item) {
                    if (isset($item['name'])) {
                        $transformed['labels'][$item['name']] = $item['value'];
                    }
                }
                $this->labels = $transformed['labels'];
            }
            
        }
    }

    function getExistingLangCodes(): array {
        return $this->langCodes;
    }

    function isValidLanguageCode(string $langCode): bool {
        return in_array($langCode, $this->langCodes);
    }

    function getLangLabel(string $langKey): string  {
        return $this->labels[$langKey] ?? '';
    }

    function isRtl(): bool {
        return $this->isRtl;
    }

    private function __clone() {}

    function getCurrentLanguageCode() {
        if (!empty($this->currentLanguageCode)) {
            return $this->currentLanguageCode;
        }

        $languahesMetaKey = Config::getInstance()->getSetting('languages_meta_key');
        $langs = OptionUtils::getInstance()->getOption($languahesMetaKey);
        $langCode = '';
        $isDefaultLanguageFromConfig = false;

        if (is_array($langs) && count($langs) > 0) {
            // Get the first language code
            $langCode = array_key_first($langs);
        } else {
            // Fallback to default language code
            $defaultLanguage = DefaultLabels::getDefaultLanguage();
            if (is_array($defaultLanguage) && isset($defaultLanguage['code'])) {
                $langCode = $defaultLanguage['code'];
                $isDefaultLanguageFromConfig = true;
            }
        }

        if ($isDefaultLanguageFromConfig) {
            $this->currentLanguageCode = $langCode;
            return $this->currentLanguageCode;
        }

        // use session here
        OxySession::initSession();

        if (isset($_SESSION['current_language_code']) && !empty($_SESSION['current_language_code'])) {
            $langCode = sanitize_text_field($_SESSION['current_language_code']);
        }
        $this->currentLanguageCode = $langCode;
        return $this->currentLanguageCode;
    }

    function getFlagIconUrl(string $langCode = ''): string {
        if (empty($langCode)) {
            $langCode = $this->getCurrentLanguageCode();
        }
        $langData = Flags::findLangByCode($langCode);
        $flagIcon = $langData['flag_4x3'] ?? '';
        $baseFlagsUrl = Flags::getBaseURL();
        return $baseFlagsUrl . $flagIcon;
    }

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new LanguagesHelper();
        }
        return self::$instance;
    }
}