<?php

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\AdminBundle\AdminList\FiltersStorage;
use KupShop\AdminBundle\Query\Invert;

class ProductsOfSuppliersList extends BaseList
{
    use FiltersStorage;
    protected $showMassEdit = true;
    protected $tableName = 'products_of_suppliers';
    protected ?string $tableAlias = 'pos';

    protected $tableDef = [
        'id' => 'pos.id',
        'fields' => [
            'ID' => ['field' => 'pos.id', 'size' => 0.5],
            'product' => ['translate' => true, 'field' => 'p.title', 'spec' => 'p.title', 'size' => 2, 'type' => 'product', 'type_id' => 'p_id', 'fieldType' => BaseList::TYPE_STRING],
            'variation' => ['translate' => true, 'field' => 'pv_title', 'size' => 1],
            'supplier' => ['translate' => true, 'field' => 's.name'],
            'code' => ['translate' => true, 'field' => 'pos.code'],
            'supplierEAN' => ['translate' => true, 'field' => 'pos.ean', 'visible' => 'N'],
            'ean' => ['translate' => true, 'field' => 'product_ean', 'visible' => 'N'],
            'inStore' => ['translate' => true, 'field' => 'pos.in_store', 'spec' => 'pos.in_store', 'size' => 0.5, 'fieldType' => BaseList::TYPE_INT],
            // 'VOC Dod.' => ['field'=>'pos.price_buy', 'size'=>0.5, 'class'=>'right', 'render'=>function ($label, $variables]{return $label > 0 ? setPrice($variables['price_buy'], null, $variables['vat']] : "-";}],
            'lastSync' => ['translate' => true, 'field' => 'pos.last_sync', 'size' => 1, 'visible' => 'N'], // 'class'=>'center'
            'productCode' => ['translate' => true, 'field' => 'product_code', 'visible' => 'N'],
            'figure' => ['field' => 'figure', 'translate' => true, 'translation_section' => 'products', 'visible' => 'N', 'render' => 'renderFigure'],
            'priceBuy' => ['field' => 'pos.price_buy', 'translate' => true, 'visible' => 'N', 'spec' => 'pos.price_buy', 'fieldType' => BaseList::TYPE_PRICE],
            'priceSell' => ['field' => 'pos.price_sell', 'translate' => true, 'visible' => 'N', 'spec' => 'pos.price_sell', 'fieldType' => BaseList::TYPE_PRICE],
            'note' => ['translate' => true, 'field' => 'pos.note', 'spec' => 'pos.note', 'visible' => 'N', 'fieldType' => BaseList::TYPE_STRING],
        ],
        'class' => 'getRowClass',
    ];
    protected $showAddItem = 'data[id_product]={productId}&data[id_variation]={variationId}';
    protected $figure;

    public function getRowClass($values)
    {
        $dbcfg = Settings::getDefault();
        $class = '';
        if ($dbcfg->highlight_order_rows == 'Y') {
            if ($values['figure'] == 'O') {
                $class .= ' info';
            } elseif ($values['figure'] != 'Y') {
                $class .= ' danger';
            }
        }

        return $class;
    }

    public function renderFigure($values, $column)
    {
        $value = $this->renderCell($values, $column);

        if (!isset($this->figure)) {
            $this->figure = [
                'Y' => translate('figureVisible', 'products'),
                'N' => translate('figureHidden', 'products'),
                'O' => translate('figureSaleEnd', 'products'),
            ];
        }

        return $this->figure[$value] ?? '';
    }

    public function getQuery()
    {
        /** @var \KupShop\ElninoBundle\Query\QueryBuilder $qb */
        $qb = sqlQueryBuilder()
                    ->select('pos.id', 'pos.id ID', 'p.figure as figure', 'pv.title pv_title', 's.name', 'pos.code', 'pos.ean',
                        'DATE_FORMAT(pos.last_sync, "'.$GLOBALS['dbcfg']['date_format'].' '.$GLOBALS['dbcfg']['time_format'].'") as last_sync',
                        'p.id as p_id', 'v.vat', 'COALESCE(p.code) AS product_code', 'p.ean product_ean')
                    ->from('products_of_suppliers', 'pos')
                    ->leftJoin('pos', 'suppliers', 's', 'pos.id_supplier=s.id')
                    ->leftJoin('pos', 'products', 'p', 'pos.id_product=p.id')
                    ->leftJoin('pos', 'products_variations', 'pv', 'pos.id_variation=pv.id')
                    ->leftJoin('p', 'vats', 'v', 'v.id=p.vat')
                    ->where(1);

        extract($_REQUEST, EXTR_SKIP | EXTR_REFS);

        // ###########
        if (!empty($IDs)) {
            $qb->andWhere('(pos.id=:idsParam1 OR pos.code LIKE :idsParam2)')
                ->setParameter('idsParam1', "{$IDs}")
                ->setParameter('idsParam2', "%{$IDs}");
        }
        if (!empty($EAN)) {
            $qb->andWhere(\Query\Operator::like(['pos.ean' => "%{$EAN}%"]));
        }
        // ###########
        if (!empty($supplier)) {
            $qb->andWhere(\Query\Operator::equals(['pos.id_supplier' => $supplier]));
            unset($fields, $name);
        }
        // ###########
        if (!empty($producer)) {
            $qb->andWhere(\Query\Operator::equals(['p.producer' => $producer]));
            unset($fields, $name);
        }
        // ###########
        if (!empty($productId)) {
            $variationId = getVal('variationId');
            $qb->andWhere(\Query\Operator::equals(['pos.id_product' => $productId]));
            if ($variationId > 0) {
                $qb->andWhere(\Query\Operator::equals(['pos.id_variation' => intval($variationId)]));
            }
        } elseif (!empty($productId_text)) {
            $qb->andWhere('p.title LIKE :p_title_like')->setParameter('p_title_like', '%'.$productId_text.'%');
        }
        if (!empty($figure)) {
            $qb->andWhere(Invert::checkInvert(\Query\Operator::inStringArray($figure, 'p.figure'), isset($figure_invert)));
        }
        // ###########
        if (!empty($error)) {
            $qb->andWhere('(pos.id_variation IS NULL AND (SELECT COUNT(*) FROM products_variations WHERE pos.id_product=products_variations.id_product) > 0)');
            unset($fields, $name);
        }

        return $qb;
    }
}
