<?php

namespace KupShop\GTMBundle\PageType;

use KupShop\BonusProgramBundle\Utils\BonusProvider;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Context\PriceLevelContext;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\PricelistBundle\Context\PricelistContext;

class CommonPageType extends AbstractPageType
{
    /**
     * @var LanguageContext
     */
    protected $languageContext;

    /**
     * @var PricelistContext
     */
    protected $pricelistContext;

    /**
     * @var PriceLevelContext
     */
    private $priceLevelContext;

    /**
     * @var BonusProvider
     */
    private $bonusProvider;

    /**
     * @var \Cart
     */
    private $cart;

    public function getPageType(&$dataContainer)
    {
        $dataContainer->page->type = 'other';
    }

    public function getPageData(&$dataContainer)
    {
        if (!empty($dataContainer->page)) {
            $page = &$dataContainer->page;
        } else {
            $page = new \stdClass();
        }

        if ($this->languageContext) {
            $page->language = $this->languageContext->getActiveId();
        }

        $page->title = $this->getPageTitle();
        $page->path = $this->getRequest()->server->get('REQUEST_URI') ?? '';

        try {
            $currency = $this->priceComputer->getOutputCurrency();
            $page->currency = $currency->getId();
            $page->currencyRate = $currency->getRate();
        } catch (\Exception $e) {
        }

        $nav = $this->getBreadcrumbs();
        $page->breadCrumbs = $this->getCategoriesMap($nav);
        $page->environment = isBeta() ? 'beta' : 'live';

        // Hnus velebnosti, komponenty maj novou verzi DL, ale ještě mají některý věci přes smarty kde se volá tohle
        if (findModule(\Modules::COMPONENTS)) {
            $dataContainer->bread_crumbs = '@breadcrumbs';
            $dataContainer->currency_rate = $page->currencyRate;
            unset($page->breadCrumbs, $page->currencyRate);
        }

        $dataContainer->page = $page;

        if (!findModule(\Modules::JS_SHOP)) {
            $dataContainer->user = $this->getUserData();
        }

        $dataContainer->resetRefferer = false;
        if ($this->getRequest()->get('wpj_utm')) {
            $dataContainer->resetRefferer = true;
        }

        $dataContainer->event = 'pageView';

        // Hnus velebnosti, komponenty maj novou verzi DL, ale ještě mají některý věci přes smarty kde se volá tohle
        if (findModule(\Modules::COMPONENTS)) {
            $dataContainer->event = 'page_view';
            $dataContainer->reset_refferer = $dataContainer->resetRefferer;
            unset($dataContainer->resetRefferer);
        }

        $this->addAdditionalFields($dataContainer, $this->getUserData());
    }

    public function getUserData()
    {
        $user = new \stdClass();

        $user->sessionId = $this->getRequest()->getSession()->getId() ?: '';

        if ($admin = getAdminUser()) {
            $user->admin = $admin['login'];
        }

        $user->cartId = \Cart::getCartID();

        $userObj = Contexts::get(UserContext::class)->getActive();
        if ($userObj) {
            $dbcfg = \Settings::getDefault();

            $user->type = 'loggedIn';
            $user->id = $userObj->id;

            if ($this->priceLevelContext->getActive()) {
                $user->priceLevel = $this->priceLevelContext->getActive()->name;
            }

            if ($userObj->getGroups()) {
                $groups = [];
                foreach ($userObj->getGroups() as $g) {
                    $groups[] = $g['name'];
                }
            }
            $user->groups = $groups ?? [];

            if ($this->pricelistContext && $this->pricelistContext->getActiveId()) {
                $user->priceList = $this->pricelistContext->getActive()?->getName();
            } else {
                $user->priceList = null;
            }

            $user->email = $userObj->email;
            $user->phone = $userObj->phone;
            $user->name = $userObj->name;
            $user->surname = $userObj->surname;

            $user->shaEmail = hash('sha256', $userObj->email.($dbcfg->analytics['google_tag_manager']['sha_salt'] ?? false ?: ''));

            if (findModule(\Modules::BONUS_PROGRAM)) {
                // TODO: Potom přidat do pStatu?
                $user->bonusPoints = $this->bonusProvider->getActivePointsAmount($userObj);
            } else {
                $user->bonusPoints = null;
            }
        } else {
            // userlogin cookie uz se nesetuje, jen ro historii. Nevadi ze posilame vsude anonymous (snad)
            if ($this->getRequest()->cookies->get('userlogin')) {
                $user->type = 'loggedOut';
            } else {
                $user->type = 'anonymous';
            }
        }

        $pState = $this->cart->getPurchaseState();

        $user->cartValue = $this->priceComputer->getPrice($pState->getProductsTotalPrice());
        $user->cartValueWithVat = $this->priceComputer->getPrice($pState->getProductsTotalPrice(), true);
        $user->cartValueWithoutVat = $this->priceComputer->getPrice($pState->getProductsTotalPrice(), false);
        $user->cartItems = 0;
        foreach ($pState->getProducts() as $p) {
            $user->cartItems += $p->getPieces();
        }

        // Hnus velebnosti, komponenty maj novou verzi DL, ale ještě mají některý věci přes smarty kde se volá tohle
        if (findModule(\Modules::COMPONENTS)) {
            foreach (['priceList' => 'price_list',
                'priceLevel' => 'price_level',
                'shaEmail' => 'sha_email',
                'cartValue' => 'cart_value',
                'cartValueWithVat' => 'cart_value_with_vat',
                'cartValueWithoutVat' => 'cart_value_without_vat',
                'cartItems' => 'cart_items',
                'bonusPoints' => 'bonus_points'] as $old_member_name => $new_member_name) {
                if (isset($user->{$old_member_name})) {
                    $user->{$new_member_name} = $user->{$old_member_name};
                }
                unset(
                    $user->{$old_member_name}
                );
            }
        }

        return $user;
    }

    /**
     * @required
     */
    public function setLanguageContext(?LanguageContext $languageContext): void
    {
        $this->languageContext = $languageContext;
    }

    /**
     * @required
     */
    public function setPricelistContext(?PricelistContext $pricelistContext): void
    {
        $this->pricelistContext = $pricelistContext;
    }

    /**
     * @required
     */
    public function setPriceLevelContext(?PriceLevelContext $priceLevelContext): void
    {
        $this->priceLevelContext = $priceLevelContext;
    }

    /**
     * @required
     */
    public function setBonusProvider(?BonusProvider $bonusProvider): void
    {
        $this->bonusProvider = $bonusProvider;
    }

    /**
     * @required
     */
    public function setCart(\Cart $cart): void
    {
        $this->cart = $cart;
    }
}
