<?php

namespace EstatebudConnect\Services;

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

use EstatebudConnect\Traits\Singleton;

class WPML
{
    use Singleton;

    public function __construct() {}

    public function get_enabled_languages()
    {
        if (!function_exists('icl_get_languages')) {
            return [];
        }

        $languages = apply_filters('wpml_active_languages', null, 'orderby=id&order=desc');

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

        $enabled_languages = [];
        foreach ($languages as $language) {
            $enabled_languages[] = [
                'code' => $language['default_locale'],
                'name' => $language['native_name'] ?? ($language['translated_name'] ?? ''),
                'flag' => $language['country_flag_url'] ?? '',
                'home_url' => rtrim($language['url'] ?? '', '/'),
                'slug' => $language['code'] ?? '',
                'active' => $language['active'] ?? false,
            ];
        }

        return $enabled_languages;
    }

    public function get_locale()
    {
        return get_locale();
    }

    public function set_urls($languages = [], $wpml_languages = null)
    {
        if (!is_array($wpml_languages)) {
            return $wpml_languages;
        }

        $codes = array_column($languages, 'code');

        foreach ($wpml_languages as &$wpml_language) {
            $index = array_search($wpml_language['default_locale'], $codes);

            if ($index === false) {
                continue;
            }

            $wpml_language['url'] = $languages[$index]['url'];
        }

        return $wpml_languages;
    }
}
