<?php

use KupShop\AdminBundle\AdminList\BaseList;

class InventoryMissingList extends BaseList
{
    protected $pageDivide = 500;

    protected $tableDef = [
        'id' => 's.id',
        'fields' => [
            'Název produktu' => ['field' => 'title'],
            'EAN|Kód|Pozice' => ['field' => 'notes'],
            'Na webu' => ['field' => 'in_store_web', 'size' => 0.5],
            'Celkem inventura' => ['field' => 'in_store_inventory', 'size' => 0.5],
            'Rozdíl' => ['field' => 'diff', 'size' => 0.5],
            'Rozdíl cena' => ['field' => 'price_diff', 'size' => 0.5],
        ],
    ];

    public function getQuery()
    {
        $qb = sqlQueryBuilder();

        $noteField = '""';
        if (findModule(Modules::PRODUCTS, Modules::SUB_NOTE)) {
            $noteField = 'COALESCE(pv.note, p.note, "")';
        }

        $codeField = 'COALESCE(p.code, "")';
        if (findModule(Modules::PRODUCTS_VARIATIONS, Modules::SUB_CODE)) {
            $codeField = 'COALESCE(pv.code, p.code, "")';
        }

        $qb->select('id', 'title', 'notes', 'in_store_web', 'in_store_inventory', '(in_store_web-in_store_inventory) as diff', '((in_store_web-in_store_inventory)*price) as price_diff')
            ->from('
                (SELECT CONCAT_WS(":", p.id, pv.id) id, CONCAT_WS(" ", p.title, pv.title) title,
                        (COALESCE(pv.in_store, p.in_store)+(
                            SELECT COALESCE(SUM(pieces), 0)
                            FROM `order_items` oi
                            LEFT JOIN `orders` o ON oi.id_order = o.id
                            WHERE o.status IN ('.join(',', getStatuses('notpacked')).') AND ((oi.id_variation = pv.id) OR (pv.id IS NULL AND oi.id_product = p.id))
                      )) as in_store_web,
                      (
                        SELECT COALESCE(SUM(ii.quantity),0)
                        FROM `inventory_items` ii
                        WHERE ((ii.id_variation = pv.id) OR (pv.id IS NULL AND ii.id_product = p.id))
                      ) as in_store_inventory, COALESCE(p.price, pv.price) price, CONCAT_WS(" | ", COALESCE(pv.ean, p.ean, ""), '.$codeField.', '.$noteField.') as notes
                        FROM products p
			            LEFT JOIN products_variations pv ON p.id=pv.id_product
			            HAVING in_store_web<>in_store_inventory) t
            ');

        extract($_GET, EXTR_SKIP | EXTR_REFS);
        // ###########
        if (!empty($IDs)) {
            $qb->andWhere('(s.id=:id OR s.name=:name)')
                ->setParameters([
                    'id' => $IDs,
                    'name' => $IDs,
                ]);
        }
        // ###########
        if (!empty($IDp)) {
            global $dbcfg;

            $qb->leftJoin('s', 'inventory_items', 'si', 'si.id_inventory=s.id')
                ->leftJoin('si', 'products', 'p', 'si.id_product=p.id')
                ->leftJoin('p', 'vats', 'v', 'si.id_product=p.id');

            if (!empty($IDv)) {
                $qb->andWhere(\Query\Operator::equals(['si.id_variation' => $IDv]));
            }
            $column = ['Cena produktu' => ['field' => 'si.price', 'size' => 1.5, 'class' => 'right'],
                'Cena produktu DPH' => ['field' => 'si.price', 'size' => 1.8, 'class' => 'right'], ];
            $this->tableDef = array_merge(array_slice($this->tableDef, 0, 3), $column, array_slice($this->tableDef, 3));

            $fields = $qb->getQueryPart('select');
            $fields = str_replace('ss.name, ', "ss.name, CONCAT(ROUND(si.price), ' {$dbcfg['currency']}'), CONCAT(ROUND(si.price*(1+v.vat/100)), ' {$dbcfg['currency']}'), ", $fields);
            $qb->select($fields);
            $qb->andWhere('si.id_product=:id_product')->setParameter('id_product', $IDp)->groupBy('s.id');
        }
        // ###########
        if (!empty($name)) {
            $qb->andWhere('s.name=:name')->setParameter('name', $name);
        }

        return $qb;
    }
}
