<?php

namespace KupShop\AdminBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\AdminBundle\Util\Stats\StatsDataLoader;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class StatsProductsTab extends WindowTab
{
    protected $title = 'flapProducts';
    protected $template = 'window/tabs/statsProductsTab.tpl';

    public static function getTypes()
    {
        return [
            'stats' => 97,
        ];
    }

    public function getVars($smarty_tpl_vars)
    {
        $vars = [];

        $format = \Settings::getDateFormat();
        $vars['from'] = getVal('fromProduct', null, date($format, time() - (365 * 86400)));
        $vars['to'] = getVal('toProduct', null, date($format));

        $vars['page'] = getVal('page', null, 0);

        // Load only if submitted
        if (getVal('showProductsStat')) {
            $vars['products'] = ServiceContainer::getService(StatsDataLoader::class)
                ->setFrom($vars['from'])
                ->setTo($vars['to'])
                ->setTypeInterval(getVal('intervalTypeName', null))
                ->getProductsSelling($vars['page'], 20);
        }

        return $vars;
    }

    public function handleGetProductsGraph()
    {
        $statsDataLoader = ServiceContainer::getService(StatsDataLoader::class)
            ->setFrom(getVal('fromProduct'))
            ->setTo(getVal('toProduct'))
            ->setTypeInterval(getVal('intervalTypeName', null));

        if (getVal('intervalProduct') != 'undefined') {
            $statsDataLoader->setInterval(getVal('intervalProduct'));
        }

        $statsDataLoader->setRenderTo('product-graph')
            ->setTypeGraph('product')
            ->getGraph();
    }
}
