<?php

namespace auctionforge\inc\controllers;

use auctionforge\inc\Debug;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\import\LotList;
use auctionforge\inc\model\Lot;

class MultiLanguageSupport
{
    private $lotSupport;
    private $auctionSupport;

    /**
     * MultiLanguageSupport constructor.
     */
    public function __construct()
    {
        $supportTypes = array(
            BidspiritLots::POST_TYPE => false,
            BidspiritLots::TAX_AUCTION_TYPE => false
        );

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $supportTypes = array(
                BidspiritLots::POST_TYPE => pll_is_translated_post_type(BidspiritLots::POST_TYPE),
                BidspiritLots::TAX_AUCTION_TYPE => pll_is_translated_taxonomy(BidspiritLots::TAX_AUCTION_TYPE)
            );
        }

        $supportTypes = apply_filters('auctionforge_multi_language_support_types', $supportTypes);

        $this->setLotSupport($supportTypes[BidspiritLots::POST_TYPE]);
        $this->setAuctionSupport($supportTypes[BidspiritLots::TAX_AUCTION_TYPE]);
    }

    public static function getCurrentLangCode()
    {
        $langCode = SettingsHelper::getOption('lang', 'en');

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $langCode = pll_current_language();
        }

        return apply_filters('auctionforge_current_lang_code', $langCode);
    }

    public static function getDefaultLangCode()
    {
        $langCode = SettingsHelper::getOption('lang', 'en');

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $langCode = pll_default_language();
        }

        return apply_filters('auctionforge_current_lang_code_checker', $langCode);
    }

    public static function getSecondLangCode()
    {
        $defaultLang = self::getDefaultLangCode();
        $options = SettingsHelper::getPluginOptions();

        if (PolylangSupport::isPolylangActive()) {
            $languageList = pll_languages_list();
        } else {
            $languageList[0] = SettingsHelper::getOption('lang', 'en');
        }

        if (isset($options['second_lang']) && $options['second_lang'] != "" && $options['second_lang'] != $defaultLang) {
            $secondLangCode = $options['second_lang'];
        } elseif (count($languageList) >= 2) {
            $key = array_search($defaultLang, $languageList);
            if ($key !== false) {
                unset($languageList[$key]);
                $languageList = array_values($languageList);
            }
            $secondLangCode = apply_filters('auctionforge_current_lang_second_code_checker', $languageList[0]);
        }
        return $secondLangCode;
    }

    /**
     * @return mixed
     */
    public function isLotSupport()
    {
        return $this->lotSupport;
    }

    /**
     * @param  mixed  $lotSupport
     */
    private function setLotSupport($lotSupport)
    {
        $this->lotSupport = $lotSupport;
    }

    /**
     * @return mixed
     */
    public function isAuctionSupport()
    {
        return $this->auctionSupport;
    }

    /**
     * @param  mixed  $auctionSupport
     */
    private function setAuctionSupport($auctionSupport)
    {
        $this->auctionSupport = $auctionSupport;
    }

    public function init()
    {
        add_filter('auctionforge_multi_language_post_data', array($this, 'multiLanguagePostDataFilter'), 10, 3);
        add_filter('auctionforge_multi_other_language_post_data', array($this, 'otherLanguagePostDataFilter'), 10, 4);

        add_action('auctionforge_second_auction_links', array($this, 'auctionSecondLinks'), 10, 3);
        add_action('auctionforge_second_lot_links', array($this, 'lotSecondLinks'), 10, 3);
    }

    /**
     * @param $postData array
     * @param $lot Lot
     * @return array
     */
    public function multiLanguagePostDataFilter($postData, $postId, $lot)
    {
        $secondLangCode = MultiLanguageSupport::getSecondLangCode();
        $otherLots = Lot::findLotByLotID($lot->getLotId(), $postId, $secondLangCode);

        if (!empty($otherLots)) {
            $secondPostId = $otherLots[0]->ID;
            unset($otherLots[0]);
            LotHelper::movedToDraftPosts($otherLots);
        } else {
            $secondPostId = 0;
        }

        if ($secondPostId == $postId) {
            unset($postData['ID']);
            unset($secondPostId);
        }

        if (!empty($secondPostId) && $secondPostId) {
            $postData['ID'] = $secondPostId;
        } else {
            unset($postData['ID']);
        }

        $isSecondLang = true;
        $lotTitle = apply_filters('auctionforge_lot_title_field_second', $lot->getNameL2(), $lot, $isSecondLang);

        if ($lotTitle != "") {
            $postData['post_title'] = "Lot " . wp_strip_all_tags($lot->getItemIndex()) . " - " . wp_strip_all_tags($lotTitle);
        } else if ($lot->getAuthorL2() != "") {
            $postData['post_title'] = "Lot ".wp_strip_all_tags($lot->getItemIndex())." - ".wp_strip_all_tags($lot->getAuthorL2());
        } else {
            $postData['post_title'] = "Lot " . wp_strip_all_tags($lot->getItemIndex());
        }

        $lotSlug = LotHelper::chunkSlug(sanitize_title($postData['post_title']));
        $lotSlug = apply_filters('auctionforge_lot_name_field', $lotSlug);

        $postData['post_name'] = $lotSlug;
        $postData['post_content'] = $lot->getDescriptionL2();
        $postData['post_parent'] = $lot->getLotId();
        return $postData;
    }

    public function otherLanguagePostDataFilter($postData, $postId, $lot, $langCode)
    {
        unset($postData['ID']);
        $otherLots = Lot::findLotByLotID($lot->getLotId(), $postId, $langCode);

        if (!empty($otherLots)) {
            $secondPostId = $otherLots[0]->ID;
            unset($otherLots[0]);
            LotHelper::movedToDraftPosts($otherLots);
        } else {
            $secondPostId = 0;
        }

        if ($secondPostId == $postId) {
            unset($secondPostId);
        }

        if (!empty($secondPostId) && $secondPostId) {
            $postData['ID'] = $secondPostId;
        }

        if (SettingsHelper::getOption(Settings::OPTIONS_OTHER_LANG, 'default') == 'second') {
            $lotTitle = apply_filters('auctionforge_lot_title_field_second', $lot->getNameL2(), $lot, true);
            if ($lotTitle != "") {
                $postData['post_title'] = "Lot " . wp_strip_all_tags($lot->getItemIndex()) . " - " . wp_strip_all_tags($lotTitle);
            } else if ($lot->getAuthorL2() != "") {
                $postData['post_title'] = "Lot ".wp_strip_all_tags($lot->getItemIndex())." - ".wp_strip_all_tags($lot->getAuthorL2());
            } else {
                $postData['post_title'] = "Lot " . wp_strip_all_tags($lot->getItemIndex());
            }
            $postData['post_content'] = $lot->getDescriptionL2();
        } else {
            $postData['post_content'] = $lot->getDescription();
        }

        $lotSlug = LotHelper::chunkSlug(sanitize_title($postData['post_title']));
        $lotSlug = apply_filters('auctionforge_lot_name_field', $lotSlug);
        $postData['post_parent'] = $lot->getLotId();
        $postData['post_name'] = $lotSlug;

        return $postData;
    }

    public function auctionSecondLinks($terms, $defaultLanguage, $otherLanguage)
    {
        if (
            isset($otherLanguage['second']) &&
            ($terms[$defaultLanguage] != $terms[$otherLanguage['second']]) &&
            $terms[$defaultLanguage] &&
            $terms[$otherLanguage['second']] &&
            PolylangSupport::isPolylangActive()
        )
        {
            pll_set_term_language($terms[$defaultLanguage], $defaultLanguage);
            pll_set_term_language($terms[$otherLanguage['second']], $otherLanguage['second']);

            $pllSaveTerms = [
                $defaultLanguage => $terms[$defaultLanguage],
                $otherLanguage['second'] => $terms[$otherLanguage['second']],
            ];

            if (!empty($otherLanguage['other'])) {
                foreach ($otherLanguage['other'] as $item) {
                    pll_set_term_language($terms[$item], $item);
                    $pllSaveTerms[$item] = $terms[$item];
                }
            }

            pll_save_term_translations($pllSaveTerms);
        }
    }

    /**
     * @param $postId int
     * @param $secondPostId int
     * @param $otherPostIds array
     * @return void
     */
    public function lotSecondLinks($postId, $secondPostId, $otherPostIds)
    {
        if (is_int($postId) && is_int($secondPostId) && PolylangSupport::isPolylangActive()) {
            $firstLangCode = MultiLanguageSupport::getDefaultLangCode();
            $secondLangCode = MultiLanguageSupport::getSecondLangCode();

            pll_set_post_language($postId, $firstLangCode);
            pll_set_post_language($secondPostId, $secondLangCode);

            $translates = [
                $firstLangCode => $postId,
                $secondLangCode => $secondPostId,
            ];

            if (!empty($otherPostIds)) {
                foreach ($otherPostIds as $key => $otherPostId) {
                    pll_set_post_language($otherPostId, $key);
                    $translates[$key] = $otherPostId;
                }
            }

            pll_save_post_translations($translates);
        }
    }
}
