<?php

namespace Clonable\Services;

use Clonable\Helpers\Functions;
use Clonable\Helpers\UrlTranslator;
use Clonable\Models\Site;
use Throwable;

class LanguageTagService {

    public function clonable_echo_language_tags() {
        if (get_option('clonable_language_tag_service_enabled', 'on') !== 'on') {
            return;
        }

        $path = $_SERVER["REQUEST_URI"] ?? '/';
        if (Functions::str_starts_with($path, $this->external_subfolders())) {
            // Do not generate language tags when on external subfolders.
            return;
        }

        try {
            $tags = $this->clonable_get_all_language_tags();
        } catch (Throwable $exception) {
            error_log('Error while getting language tag data: ' . $exception->getMessage() . " || " . $exception->getTraceAsString());
            $tags = [];
        }

        try {
            foreach ($tags as $tag) {
                if (empty($tag['hreflang']) || empty($tag['href'])) {
                    continue;
                }
                echo "<link rel=\"alternate\" hreflang=\"" . esc_attr($tag['hreflang']) . "\" href=\"" . esc_url($tag['href']) . "\" />\n";
            }
        } catch (Throwable $exception) {
            error_log("[Clonable] Error while rendering language tags: {$exception->getMessage()}");
        }
    }

    private function external_subfolders()
    {
        $response = get_option("clonable_site");
        if (empty($response)) {
            return array();
        }
        $site = new Site($response);
        return $site->external_subfolders();
    }

    private function clonable_get_all_language_tags() {
        $tags = [];

        $json = get_option('clonable_langtag_data');
        if ($json == null) {
            return $tags;
        }

        $decoded_json = json_decode($json);
        // check if the saved data is valid json
        if ($decoded_json == null || $decoded_json->data == null || $decoded_json->version == null) {
            return $tags;
        }

        $data = $decoded_json->data;

        $include_original = true;
        if ($decoded_json->version > 1) { // backwards compatibility with the old plugin
            $include_original = $data->original->include;
        }

        if (isset($data->original) && $include_original) {
            $href = UrlTranslator::clonable_get_full_url($data->original);
            $tags[] = [
                'href' => $href,
                'hreflang' => 'x-default',
                'use_url_translation' => false,
            ];

            $tags[] = [
                'href' => $href,
                'hreflang' => $data->original->langcode,
                'use_url_translation' => false,
            ];
        }

        $translate_all_urls = get_option('clonable_langtag_switch', 'off') == 'on';
        if (isset($data->clones)) {
            foreach ($data->clones as $clone) {
                $translate_clone_url = ($clone->translate_urls ?? false);
                $href = UrlTranslator::clonable_get_full_url($clone);
                $tags[] = [
                    'href' => $href,
                    'hreflang' => $clone->langcode,
                    'use_url_translation' => ($translate_all_urls && $translate_clone_url),
                ];
            }
        }

        // filter all the url that need to be translated
        $translatable_language_tags = [];
        foreach ($tags as $tag) {
            if ($tag['use_url_translation']) {
                $translatable_language_tags[] = [
                    'o' => $tag['href'],
                    'r' => $tag['href'],
                ];
            }
        }

        // If we have no urls to translate, return as-is
        if (count($translatable_language_tags) == 0) {
            return $tags;
        }

        // translate the actual urls
        $translation_output = UrlTranslator::clonable_translate_hrefs($translatable_language_tags);

        // Update tags
        // This is O(n2), but that's not really an issue because of the small size of tags (typically <10)
        foreach ($translation_output as $translation) {
            foreach ($tags as $key => $tag) {
                if ($tag['href'] == $translation['o']) {
                    $tags[$key]['href'] = $translation['r'];
                    break;
                }
            }
        }

        return $tags;
    }


 
}