<?php

namespace auctionforge\inc\controllers;

use PLL_Frontend;
use auctionforge\inc\Debug;
use auctionforge\inc\helpers\SettingsHelper;
use WP_Term;

class PolylangSupport
{
    const NAME_GET_PARAM = 'poly';
    const LANG_SWITCH_PARAM = 'bs-lang';

    public function init()
    {
        if (!self::isFullSupport()) {
            add_action('pll_language_defined', array($this, 'bidspirit_switch_language'), 1);
            add_filter('pll_the_language_link', array($this, 'bidspirit_language_link'), 10, 3);
        } else {
            add_filter('pll_the_language_link', array($this, 'bidspirit_full_language_link'), 10, 3);
        }
    }

    /**
     * @return bool
     */
    public static function isFullSupport()
    {
        $polylangOptions = self::getPolylangOptions();
        return self::isAuctionSupport($polylangOptions) && self::isLotSupport($polylangOptions);
    }

    public static function getSupportedLanguages()
    {
        $options = SettingsHelper::getPluginOptions();
        $languages = [
            'default' => !empty($options['lang']) ? $options['lang'] : MultiLanguageSupport::getDefaultLangCode(),
            'second' => !empty($options['second_lang']) ? $options['second_lang'] : MultiLanguageSupport::getSecondLangCode(),
        ];

        if (self::isFullSupport() && function_exists('pll_languages_list')) {
            $pllLanguages = pll_languages_list();
            $otherLangs = [];
            foreach ($pllLanguages as $pllLanguage) {
                if (array_search($pllLanguage, $languages) === false) {
                    $otherLangs[] = $pllLanguage;
                }
            }
            $languages['other'] = $otherLangs;
        }

        return $languages;
    }

    public static function isLotSupport($polylangOptions)
    {
        if (is_array($polylangOptions) && !empty($polylangOptions['post_types'])) {
            return in_array(BidspiritLots::POST_TYPE, $polylangOptions['post_types']);
        } else {
            return false;
        }
    }

    public static function isAuctionSupport($polylangOptions)
    {
        if (is_array($polylangOptions) && !empty($polylangOptions['taxonomies'])) {
            return in_array(BidspiritLots::TAX_AUCTION_TYPE, $polylangOptions['taxonomies']);
        } else {
            return false;
        }
    }

    public static function getPolylangOptions()
    {
        return get_option('polylang');
    }

    /**
     * @return bool
     */
    public static function isThumbnailSync()
    {
        $polylangSettings = self::getPolylangOptions();
        if (!empty($polylangSettings['sync'])) {
            return (in_array('_thumbnail_id', $polylangSettings['sync']) !== false);
        }

        return false;
    }

    public static function isPolylangActive()
    {
        if ((is_plugin_active('polylang/polylang.php') || is_plugin_active('polylang-pro/polylang.php')) && function_exists('pll_current_language')) {
            return true;
        }
        return false;
    }

    public function bidspirit_switch_language()
    {
        global $post;
        $locale = !empty($_GET[self::NAME_GET_PARAM]) ? $_GET[self::NAME_GET_PARAM] : "";

        if (!headers_sent() && $locale !== "") {
            $slug = explode("_", $locale);

            if (empty($slug)) {
                $slug = pll_current_language();
            } else {
                $slug = $slug[0];
            }

            if ($this->isLot()) {
                $this->setCookieLang($slug);
                pll_set_post_language($post->ID, $locale);
                $this->redirect($slug);
            }

            if (is_tax('auction_number') && is_archive()) {
                $this->setCookieLang($slug);
                $category = get_queried_object();
                $auction = get_term($category->term_id, 'auction_number');
                pll_set_term_language($auction->term_id, $locale);
                $this->redirect($slug);
            }
        }
    }

    public function bidspirit_language_link($url, $slug, $locale)
    {
        if ($this->isArchivePage() || $this->isLot()) {
            global $post;
            $category = get_queried_object();
            if ($this->isArchivePage() && $category instanceof WP_Term) {
                $url = get_term_link($category->term_id);
            } else {
                $url = get_permalink($post->ID);
            }

            $pll_language = pll_current_language();

            if ($pll_language != $slug) {
                $uri = parse_url($_SERVER['REQUEST_URI']);
                (!empty($uri['query'])) ? $delimiter = '&' : $delimiter = '?';

                if (!empty($uri['query'])) {
                    $url = "?".$uri['query'].$delimiter.self::NAME_GET_PARAM."=".$locale;
                } else {
                    $url = $url.$delimiter.self::NAME_GET_PARAM."=".$locale;
                }
            }
        }
        return $url;
    }

    /**
     * @param $args array
     * @param $isArchived bool
     * @return array
     */
    public function pll_query_auction_params($args)
    {
        $supportedLanguages = self::getSupportedLanguages();
        $currentLanguage = pll_current_language();
        if (array_search($currentLanguage, $supportedLanguages) === false) {
            $args['lang'] = $supportedLanguages['default'];
        }
        return $args;
    }

    public function bidspirit_full_language_link($url)
    {
        if (!$this->isArchivePage()) {
            return $url;
        }

        if (!empty(get_query_var('part'))) {
            $uri = parse_url($_SERVER['REQUEST_URI']);
            if (!empty($uri['query'])) {
                $url .= "?" . $uri['query'];
            }
        }

        return $url;
    }

    private function setCookieLang($codeLang)
    {
        /** @var PLL_Frontend $polylang */
        global $polylang;
        setcookie(
            PLL_COOKIE,
            $codeLang,
            time() + 3600,
            COOKIEPATH,
            2 == $polylang->options['force_lang'] ? wp_parse_url($polylang->links_model->home, PHP_URL_HOST) : COOKIE_DOMAIN,
            is_ssl()
        );
    }

    private function isArchivePage()
    {
        if (is_tax('auction_number') && is_archive()) {
            return true;
        }
        return false;
    }

    private function isLot()
    {
        global $post;
        if (is_single() && !empty($post) && $post->post_type == 'lot') {
            return true;
        }
        return false;
    }

    private function redirect($slug)
    {
        $lang = MultiLanguageSupport::getDefaultLangCode();
        $uriBase = explode('?', $_SERVER['REQUEST_URI']);
        $base = get_site_url() . $uriBase[0];
        $params = '';

        $uri = parse_url($_SERVER['REQUEST_URI']);

        if (!empty($uri['query'])) {
            parse_str($uri['query'], $params);
            unset($params[self::NAME_GET_PARAM]);
            unset($params[self::LANG_SWITCH_PARAM]);
            if ($lang != $slug) {
                $params[self::LANG_SWITCH_PARAM] = $slug;
            }
            if (!empty($params)) {
                $base .= "?" . http_build_query($params);
            }
        } else {
            if ($lang != $slug) {
                $params[self::LANG_SWITCH_PARAM] = $slug;
                $base .= "?" . http_build_query($params);
            }
        }

        header('Vary: Accept-Language');
        wp_safe_redirect($base, 302);
        exit;
    }
}

$polylangSupport = new PolylangSupport();
if (is_plugin_active('polylang/polylang.php') && class_exists('PLL_Frontend')) {
    $polylangSupport->init();
}
