<?php

namespace EstatebudConnect\Services;

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

use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Core\Locale;

class Weglot
{
    use Singleton;

    public function __construct() {}

    public function get_enabled_languages()
    {
        if (!function_exists('weglot_get_languages_available') || !function_exists('weglot_get_destination_languages') || !function_exists('weglot_get_original_language')) {
            return [];
        }

        $languages = weglot_get_languages_available();
        $active_languages = weglot_get_destination_languages();
        $original_language = weglot_get_original_language();

        $all_languages = array_column($active_languages, 'language_to');
        $all_languages[] = $original_language;

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

        $enabled_languages = [];
        foreach ($languages as $language) {
            $code = $language->getInternalCode();
            $is_default_language = $original_language === $code;

            if (!in_array($code, $all_languages)) {
                continue;
            }

            $home_url = home_url();

            if (!$is_default_language) {
                $home_url .= '/' . $code ?? '';
            }

            $enabled_languages[] = [
                'code' => $code,
                'name' => $language->getLocalName(),
                'flag' => 'https://cdn.weglot.com/flags/square/' . $code . '.svg',
                'home_url' => rtrim($home_url, '/'),
                'slug' => $code,
                'active' => $this->get_locale() === $code,
            ];
        }

        return $enabled_languages;
    }

    public function get_locale()
    {
        if (!function_exists('weglot_get_current_language')) {
            return get_locale();
        }

        return weglot_get_current_language();
    }

    public function set_urls($languages = [], $html)
    {
        $locale = Locale::instance()->get_locale();
        $codes = array_column($languages, 'code');
        $index = array_search($locale, $codes);

        if ($index === false) {
            return $html;
        }

        $active_language = $languages[$index];

        foreach ($languages as $language) {
            if ($language === $active_language) {
                continue;
            }

            $url_to_replace = str_replace($active_language['home_url'], $language['home_url'], $active_language['url']);

            if (str_contains($html, $url_to_replace)) {
                $html = str_replace($url_to_replace, $language['url'], $html);
            }
        }

        return $html;
    }
}
