<?php

namespace KupShop\AdminBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\AdminBundle\Util\Stats\StatsDataLoader;
use KupShop\AdminBundle\Util\Stats\StoreDataLoader;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\StoresBundle\Utils\Export\StoreHistoryExport;
use KupShop\StoresBundle\Utils\Export\StoreStatsExport;
use KupShop\StoresBundle\Utils\StoresInStore;
use Query\Operator;

class StatsStoreTab extends WindowTab
{
    use \DatabaseCommunication;
    protected $title = 'flapStore';

    protected $template = 'window/tabs/statsStoreTab.tpl';

    protected ?StoresInStore $storesInStore = null;

    private $from;
    private $to;

    /** @required */
    public function setStoresInStore(?StoresInStore $storesInStore): void
    {
        $this->storesInStore = $storesInStore;
    }

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

    public static function isAllowed()
    {
        return findModule(\Modules::STOCK_IN);
    }

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

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

        if (getVal('showStoreStat')) {
            /**
             * @var $storeDataLoader StoreDataLoader
             */
            $storeDataLoader = ServiceContainer::getService(StoreDataLoader::class);
            $vars['closure_now'] = $storeDataLoader->getCurrentStoreValue();
        }
        $vars['date'] = getVal('date') ?? date('d.m.Y');

        $vars['externalStores'] = $this->getStores();

        return $vars;
    }

    public function handleGetStoreGraph()
    {
        $format = \Settings::getDateFormat();
        $stockIn = sqlQueryBuilder()->select('MIN(number) as `from`, MAX(number) as `to`')
        ->from('stock_in')
        ->where(Operator::equals(['id_index' => 'closure']))->execute()->fetch();
        $this->from = date($format, strtotime($stockIn['from'].'-01-01'));
        $this->to = date($format);

        ServiceContainer::getService(StatsDataLoader::class)
            ->setTypeGraph(getVal('typegraph'))
            ->setFrom($this->from)
            ->setTo($this->to)
            ->setInterval('year')
            ->setTabInstance($this)
            ->getGraph();
    }

    public function getDBStoreData()
    {
        $from = \DateTime::createFromFormat(\Settings::getDateFormat(), $this->from);
        $years = range($from->format('Y'), date('Y'));
        $data = array_fill_keys($years, []);

        $sql = sqlQueryBuilder()->select('total_price, number')
        ->from('stock_in')
        ->where(Operator::equals(['id_index' => 'closure']));
        foreach ($sql->execute()->fetchAll() as $stockIn) {
            $data[$stockIn['number']] = $stockIn['total_price'];
        }

        /**
         * @var $storeDataLoader StoreDataLoader
         */
        $storeDataLoader = ServiceContainer::getService(StoreDataLoader::class);

        $closure_now = $storeDataLoader->getCurrentStoreValue();
        $data[date('Y')] = $closure_now['without_vat'];

        return [0 => array_values($data)];
    }

    public function getYearsData(&$data, $DBData, $year)
    {
        $i = 0;
        foreach ($DBData as $key => $userData) {
            $data[$i]['name'] = $key;
            $data[$i++]['data'][] = (!empty($DBData[$key][$year])) ? round($DBData[$key][$year], 2) : 0;
        }
    }

    public function handleExportCurrentExternalStore(): void
    {
        if (!($storeId = getVal('storeId'))) {
            return;
        }

        if ($date = getVal('date')) {
            $date = \DateTime::createFromFormat('d.m.Y', $date);
        }

        $storeIds = array_filter(explode(',', $storeId));

        $storeStatsExport = ServiceContainer::getService(StoreStatsExport::class);
        $storeStatsExport->exportStoreStats($storeIds, $date);

        exit;
    }

    public function handleExportStoreHistory(): void
    {
        if (!($storeId = getVal('storeId'))) {
            return;
        }

        if (!($date = getVal('date'))) {
            return;
        }

        $storeHistoryExport = ServiceContainer::getService(StoreHistoryExport::class);
        $storeHistoryExport->exportStoreHistory($storeId, $date);

        exit;
    }

    public function getStores(): array
    {
        if (!findModule(\Modules::STORES)) {
            return [];
        }

        return $this->storesInStore->getStores();
    }
}
