<?php

namespace KupShop\WarehouseBundle\Admin\lists;

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\AdminBundle\AdminList\FiltersStorage;
use KupShop\AdminBundle\Query\StockIn;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\WarehouseBundle\Util\InventoryWorker;
use Query\Operator;
use Query\QueryBuilder;

class WarehouseInventoryList extends BaseList
{
    use FiltersStorage;

    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Produkt' => ['field' => 'p_title', 'size' => 2, 'type' => 'product', 'type_id' => 'id_product'],
            'Varianta' => ['field' => 'pv_title'],
            'EAN' => ['field' => 'ean'],
            'Počet kusů' => ['field' => 'inv_pieces'],
            'Prodejní cena' => ['field' => 'price', 'render' => 'renderPricePreferred', 'class' => 'right'],
            'Uživatel' => ['field' => 'login'],
            'DPH' => ['field' => 'vat_value', 'spec' => 'v.vat as vat_value', 'visible' => 'N'],
        ],
    ];

    protected $orderParam = [
        'sort' => 'Počet kusů',
        'direction' => 'DESC',
    ];

    public function customizeTableDef($tableDef)
    {
        $tableDef = parent::customizeTableDef($tableDef);

        $tableDef['fields']['Kód'] = ['field' => 'code', 'visible' => 'N', 'spec' => function (QueryBuilder $qb) {
            $codeField = 'p.code';
            if (findModule(\Modules::PRODUCTS_VARIATIONS, \Modules::SUB_CODE)) {
                $codeField = 'COALESCE(pv.code, p.code) as code';
            }

            $qb->addSelect($codeField);
        }];

        $tableDef['fields']['Nákupní cena bez dph'] = ['field' => 'price_buy', 'render' => 'renderPrice', 'class' => 'right', 'visible' => 'N', 'spec' => function (QueryBuilder $qb) {
            $filterDateTo = getVal('dateTo');

            $date = null;
            if ($filterDateTo) {
                if ($tmpDate = \DateTime::createFromFormat('d.m.Y H:i:s', $filterDateTo)) {
                    $date = $tmpDate;
                }
            }

            $qb->addSelect('SUM((wl.pieces*COALESCE(r.average_price, COALESCE(pv.price_buy, p.price_buy)))) as price_buy')
                ->leftJoinSubQuery('pv', StockIn::getAveragePriceSubQuery($date), 'r', 'r.id_product = p.id AND ((pv.id IS NULL AND r.id_variation IS NULL) OR pv.id = r.id_variation)');
        }];

        return $tableDef;
    }

    public function getQuery()
    {
        $qb = sqlQueryBuilder()
            ->select('wl.*, p.title as p_title, 
            pv.title as pv_title, COALESCE(pv.ean, p.ean) as ean, a.id, GROUP_CONCAT(DISTINCT a.login) as login, p.vat,
            SUM(wl.pieces) as inv_pieces, FLOOR(COALESCE(pv.price, p.price) * SUM(wl.pieces)) as price')
            ->from('warehouse_log', 'wl')
            ->leftJoin('wl', 'products', 'p', 'p.id=wl.id_product')
            ->leftJoin('wl', 'products_variations', 'pv', 'pv.id=wl.id_variation')
            ->join('p', 'vats', 'v', 'v.id = p.vat')
            ->leftJoin('wl', 'admins', 'a', 'wl.id_admin=a.id')
            ->addGroupBy('p.id, pv.id')
            ->andHaving('inv_pieces != 0');

        $inventoryWorker = ServiceContainer::getService(InventoryWorker::class);
        $inventoryPositionID = $inventoryWorker->getInventoryPosition();

        $qb->andWhere(Operator::equals(['old_id_position' => $inventoryPositionID]));

        if (getVal('id_product')) {
            $qb->andWhere(\Query\Operator::equalsNullable(['wl.id_product' => getVal('id_product'), 'wl.id_variation' => getVal('id_variation') ?: null]));
        }

        if ($dateFrom = getVal('dateFrom')) {
            $qb->andWhere('wl.update_datetime>=:dateFromParam')
                ->setParameter('dateFromParam', "{$this->prepareDateTime($dateFrom)}");
        }

        if ($dateTo = getVal('dateTo')) {
            $qb->andWhere('wl.update_datetime<=:dateToParam')
                ->setParameter('dateToParam', "{$this->prepareDateTime($dateTo)}");
        }

        return $qb;
    }
}

return WarehouseInventoryList::class;
