<?php

namespace KupShop\ContentBundle\Controller;

use KupShop\CatalogBundle\ProductList\ProductCollectionWrapper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Component\Routing\Annotation\Route;

class LastVisitedController extends AbstractController
{
    /**
     * @Route("/_kupshop/lastvisited/")
     */
    public function getLastVisitedAction(Request $request)
    {
        $jsonProducts = $request->get('products');

        $products = array_filter($jsonProducts ? json_decode_strict($jsonProducts, true) : []);

        $responseData = [
            'html' => '',
            'result' => true,
        ];

        if ($products) {
            $defaultParams = [
                'type' => 'last_visited_stateless',
                'template' => 'null',
                'variations' => false,
                'image' => 2,
                'count' => 6,
                'products' => $products,
            ];

            $params = array_merge($defaultParams, $payload['params'] ?? []);

            $products = ProductCollectionWrapper::wrap((new \InsertProductsTypes())->getProducts($params));

            $smarty = createSmarty(false, true);
            $smarty->assign('last_visited_products', ['products' => $products]);
            $smarty->assign('listType', $request->get('listType'));
            $smarty->assign('listId', $request->get('listId'));

            $responseData['html'] = $smarty->fetch('components/block.products.last-visited.tpl');
        }

        $response = new JsonResponse($responseData);
        $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
        $response->setMaxAge(0);
        $response->setSharedMaxAge(60 * 10); // 10m

        return $response;
    }
}
