<?php

if (! defined('ABSPATH')) {
    exit;
} final class PufferGo_Language_Redirect
{
    public const COOKIE_NAME = 'puffergo_lang_decided';

    public const STORAGE_KEY = 'puffergo_lang_decided';

    public static function init(): void
    {
        add_action('wp_enqueue_scripts', array(__CLASS__, 'maybe_output'));
    }

    public static function maybe_output(): void
    {
        if (is_admin() || wp_doing_ajax() || defined('REST_REQUEST') && REST_REQUEST) {
            return;
        }

if (! PufferGo_Polylang::is_active()) {
            return;
        } $languages = PufferGo_Polylang::languages();

        if (count($languages) < 2) {
            return;
        } $default_language = PufferGo_Polylang::default_language();

        if ('' === $default_language) {
            return;
        } $targets = self::targets_by_language($languages);

        if (empty($targets)) {
            return;
        } $config = array('cookieName' => self::COOKIE_NAME, 'storageKey' => self::STORAGE_KEY, 'defaultLang' => $default_language, 'languages' => array_map(static function (array $language) use ($targets) { return array('slug' => $language['slug'], 'locale' => str_replace('_', '-', $language['locale']), 'url' => isset($targets[ $language['slug'] ]) ? $targets[ $language['slug'] ] : null, ); }, $languages), );
        wp_enqueue_script('puffergo-language-redirect', plugins_url('assets/js/puffergo-language-redirect.js', PUFFERGO_PLUGIN_FILE), array(), PUFFERGO_CORE_VERSION, true);
        wp_localize_script('puffergo-language-redirect', 'puffergoLangRedirect', $config);
    }

    private static function targets_by_language(array $languages): array
    {
        $targets = array();

        if (is_front_page()) {
            foreach ($languages as $language) {
                $targets[ $language['slug'] ] = PufferGo_Polylang::home_url($language['slug']);
            }

return $targets;
        }

if (! is_singular()) {
            return $targets;
        } $post_id = get_queried_object_id();

        if (! $post_id) {
            return $targets;
        }

foreach ($languages as $language) {
            $translated_id = PufferGo_Polylang::get_translation($post_id, $language['slug']);

            if (! $translated_id || $translated_id === $post_id) {
                continue;
            } $permalink = get_permalink($translated_id);

            if (is_string($permalink) && '' !== $permalink) {
                $targets[ $language['slug'] ] = $permalink;
            }
        }

return $targets;
    }
}
