<?php

namespace EstatebudConnect\Services;

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

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

class TranslatePress
{
    use Singleton;

    public function __construct() {}

    public function get_enabled_languages()
    {
        if (!class_exists('TRP_Translate_Press')) {
            return [];
        }

        $trp = \TRP_Translate_Press::get_trp_instance();
        $trp_settings_component = $trp->get_component('settings');
        
        $settings = $trp_settings_component->get_settings();
        $languages = $settings['translation-languages'] ?? [];

        if (empty($languages) || !is_array($languages)) {
            return [];
        }       

        $enabled_languages = [];
        foreach ($languages as $language) {
            $default_language = $settings['default-language'] ?? '';
            $is_default_language = $default_language === $language;
            $slugify_default_language = $settings['add-subdirectory-to-default-language'] === 'yes';

            $current_slug = $settings['url-slugs'][get_locale()] ?? '';
            $home_url = get_home_url();

            if (!empty($current_slug)) {
                $present_url_slug = substr($home_url, -strlen($current_slug));
                if ($present_url_slug === $current_slug) {
                    $home_url = rtrim(substr($home_url, 0, -strlen($current_slug)), '/');
                }
            }

            if (!$is_default_language || $slugify_default_language) {
                $home_url .= '/' . $settings['url-slugs'][$language] ?? '';
            }

            $enabled_languages[] = [
                'code' => $language,
                'name' => Helper::get_locale_display_name($language, $language . ' (unidentified)'),
                'flag' => TRP_PLUGIN_URL . 'assets/images/flags/' . $language . '.png',
                'home_url' => rtrim($home_url ?? '', '/'),
                'slug' => $settings['url-slugs'][$language] ?? '',        
                'active' => $this->get_locale() === $language,
            ];
        }

        return $enabled_languages;
    }

    public function get_locale()
    {
        return get_locale();
    }
    
    public function set_urls($languages = [], $payload)
    {
        return $payload;
    }
}
