<?php

namespace KupShop\CatalogBundle\Admin;

use KupShop\CatalogBundle\ProductList\ProductList;
use KupShop\CatalogBundle\Util\ProductsFilterSpecs;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class ProductsFilter extends \Window
{
    protected $template = 'window/productsFilter.tpl';

    public function get_vars()
    {
        $vars = parent::get_vars();

        $vars['filter'] = json_decode(getVal('filter'), true);

        $vars['blocekProducts'] = getVal('callback') == 'blocek_setProducts';
        $vars['productsSortable'] = $vars['blocekProducts'];

        return $vars;
    }

    public function handleLoadProducts()
    {
        $filter = getVal('filter');
        $filter = \KupShop\AdminBundle\Admin\ProductsFilter::cleanFilter($filter);

        $productList = ServiceContainer::getService(ProductList::class);
        $productsFilterSpecs = ServiceContainer::getService(ProductsFilterSpecs::class);
        $filterSpecs = $productsFilterSpecs->getSpecs($filter);
        $productList->andSpec($filterSpecs);
        $productList->fetchImages('admin');
        $productList->limit(20);

        $result = [];
        $result['count'] = 0;
        $result['filter'] = json_encode($filter);
        foreach ($productList->getProducts($result['count']) as $product) {
            /* @var $product \Product */
            $result['products'][] = [
                'id' => $product->id,
                'title' => $product->title,
                'code' => $product->code,
                'inStore' => $product->inStore,
                'photo' => $product->image['src'] ?? false,
            ];
        }
        header('Content-Type: application/json');
        echo json_encode($result);
        exit;
    }
}

return ProductsFilter::class;
