<?php

namespace KupShop\AdminBundle\EventListener;

use KupShop\KupShopBundle\Event\CronEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CountSoldProductsByPeriod implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            CronEvent::RUN_EXPENSIVE => [
                ['countSoldProductsByPeriod', 0],
            ],
        ];
    }

    public function countSoldProductsByPeriod(): void
    {
        $settings = \Settings::getDefault();
        $dateCondition = 'DATE(o.date_created) >= (CURDATE() - INTERVAL :days DAY)';

        // pokud to historicky bylo vyplnene, ale pak se smazalo, tak se to nepocitalo vubec
        // takhle dojde k pocitani poctu prodanych kusu za celou dobu fungovani eshopu
        if (empty($settings['prod_count_sold_days'])) {
            $dateCondition = '1=1';
        }

        $qbPiecesSold = sqlQueryBuilder()->select('SUM(oi.pieces)')
            ->from('order_items', 'oi')
            ->innerJoin('oi', 'orders', 'o', 'o.id = oi.id_order')
            ->andWhere('pu.id = oi.id_product')
            ->andWhere($dateCondition)
            ->andWhere('o.status_storno != 1')
            ->groupBy('oi.id_product');

        sqlQueryBuilder()->update('products', 'pu')
            ->set('pu.pieces_sold', "COALESCE(({$qbPiecesSold->getSQL()}),0)")
            ->setParameter('days', $settings['prod_count_sold_days'])
            ->execute();
    }
}
