<?php

namespace KupShop\GTMOldBundle\PageType;

use KupShop\CatalogBundle\View\SearchView;
use KupShop\GTMOldBundle\Utils\PriceComputer;

class SearchPageType extends AbstractPageType
{
    /** @var SearchView */
    protected $view;
    /**
     * @var PriceComputer
     */
    private $priceComputer;

    public function __construct(PriceComputer $priceComputer)
    {
        $this->priceComputer = $priceComputer;
    }

    public function getPageData(&$dataContainer)
    {
        $dataContainer->page->searchTerm = $this->view->getTitle();
    }

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

    public static function getSupportedViews()
    {
        return [SearchView::class];
    }

    public function getTagParamsData(&$dataContainer)
    {
        $dataContainer->google_tag_params->ecomm_pagetype = 'search';

        $templateData = $this->view->getTemplateData();

        if (!empty($templateData['body']['results']['products']['list'])) {
            $products = $templateData['body']['results']['products']['list']->getIterator();

            $counter = 0;

            /** @var \Product $product */
            foreach ($products as $product) {
                if ($counter > 8) {
                    break;
                }
                $dataContainer->google_tag_params->ecomm_prodid[] = $product->id;
                $dataContainer->google_tag_params->ecomm_totalvalue[] = $this->priceComputer->getPrice($product->getProductPrice());
                $counter++;
            }
        }
    }
}
