<?php

namespace KupShop\WarehouseBundle\Admin\lists;

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\KupShopBundle\Util\ArrayUtil;
use KupShop\KupShopBundle\Util\HtmlBuilder\HTML;
use Query\Operator;

class WarehouseProductsList extends BaseList
{
    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Produkt' => ['field' => 'p_title', 'size' => 2, 'type' => 'product', 'type_id' => 'id_product'],
            'Varianta' => ['field' => 'pv_title', 'size' => 1],
            'EAN' => ['field' => 'ean'],
            'Kód' => ['field' => 'code'],
            'Pozice' => ['field' => 'pos_title', 'type' => 'positions', 'type_id' => 'id_position', 'visible' => 'N'],
            'Počet kusů' => ['field' => 'pieces', 'size' => 0.5],
            'Inventura' => ['field' => 'inventory_date', 'size' => 1, 'render' => 'renderDate'],
            'date_stock_in' => ['translate' => true, 'field' => 'date_stock_in', 'spec' => 'p.date_stock_in', 'render' => 'renderDate', 'visible' => 'N', 'fieldType' => BaseList::TYPE_DATE],
            'Nadzásoba' => ['field' => 'over_supply', 'render' => 'renderOverSupply'],
            'Smazat' => ['field' => '', 'size' => 0.5, 'render' => 'renderDelete'],
        ],
    ];

    protected $template = 'list/warehouse_products.tpl';

    public function renderDelete($values)
    {
        $url = $this->getListUrl().'&delete[id_product]='.$values['id_product'].'&delete[id_variation]='.$values['id_variation'].'&delete[id_position]='.$values['id_position'];

        if (findModule(\Modules::PRODUCTS_BATCHES)) {
            $url .= "&delete[id_product_batch]={$values['id_product_batch']}";
        }

        return findRight('WAR_PROD_DEL') ? HTML::create('a')
            ->attr('href', $url)
            ->attr('onclick', 'return confirm(\'Opravdu smazat?\')')
            ->tag('i')
                ->class('glyphicon glyphicon-remove')
                ->end() : null;
    }

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

        if (getVal('products')) {
            $tableDef['fields']['Pozice']['visible'] = 'Y';
            $tableDef['fields']['EAN']['visible'] = 'N';
            $tableDef['fields']['Kód']['visible'] = 'N';
        }

        if (findModule(\Modules::PRODUCTS_BATCHES)) {
            $fields = $tableDef['fields'];
            ArrayUtil::insertIntoArray($fields, 'Smazat', [
                'Šarže' => [
                    'field' => 'batch',
                    'render' => 'renderBatch',
                    'spec' => function ($qb) {
                        $qb->addSelect('pb.code as batch, pb.id as id_batch, pb.date_expiry')
                            ->leftJoin('wp', 'products_batches', 'pb', 'pb.id=wp.id_product_batch');
                    }, ],
            ]);

            $tableDef['fields'] = $fields;
        }

        return $tableDef;
    }

    public function renderOverSupply($values)
    {
        $ret = HTML::create('input')
            ->attr('type', 'checkbox')
            ->attr('name', 'over_supply')
            ->attr('value', 1)
            ->attr('data-id-position', $values['id_position'])
            ->attr('data-id-product', $values['id_product'])
            ->attr('data-id-variation', $values['id_variation']);

        if ($values['over_supply'] == 'Y') {
            $ret->attr('checked', 1);
        }

        return $ret;
    }

    public function renderBatch($values)
    {
        return HTML::create('a')
            ->attr('href', "javascript:nw('productsBatches', '{$values['id_batch']}')")
            ->text($values['batch'].' ('.$this->renderDate($values, ['field' => 'date_expiry']).')');
    }

    private function getListUrl()
    {
        $url = '?s=list.php&type=warehouseProducts';
        if (getVal('location')) {
            $url .= '&location='.getVal('location');
        }

        return $url;
    }

    public function getQuery()
    {
        if ($delete = getVal('delete')) {
            if (!empty($delete['id_product']) && !empty($delete['id_position'])) {
                if (empty($delete['id_variation'])) {
                    $delete['id_variation'] = null;
                }
                if (findModule(\Modules::PRODUCTS_BATCHES)) {
                    if (empty($delete['id_product_batch'])) {
                        $delete['id_product_batch'] = null;
                    }
                }

                $info = sqlQueryBuilder()
                    ->select('wpos.code as position, p.title, wp.pieces as pieces')
                    ->from('warehouse_products', 'wp')
                    ->leftJoin('wp', 'warehouse_positions', 'wpos', 'wpos.id = wp.id_position')
                    ->leftJoin('wp', 'products', 'p', 'p.id = wp.id_product')
                    ->where(Operator::equalsNullable($delete))
                    ->execute()->fetch();

                if ($info) {
                    writeDownActivity('Smazán produkt z pozice: '.$info['title'].' na pozici '.$info['position'].
                        ' - celkem '.$info['pieces'].' ks');
                    $this->deleteSQL('warehouse_products', $delete);
                }

                redirect($this->getListUrl());
            }
        }

        $qb = sqlQueryBuilder()
            ->select('wp.id_product, wp.id_variation, wp.id_position, wpos.code as pos_title, p.title as p_title, pv.title as pv_title, 
            COALESCE(pv.ean, p.ean) as ean, COALESCE(pv.code, p.code) as code, wp.pieces, wp.over_supply, wp.inventory_date')
            ->from('warehouse_products', 'wp')
            ->leftJoin('wp', 'warehouse_positions', 'wpos', 'wpos.id=wp.id_position')
            ->leftJoin('wp', 'products', 'p', 'p.id=wp.id_product')
            ->leftJoin('wp', 'products_variations', 'pv', 'pv.id=wp.id_variation');

        if (getVal('location')) {
            $qb->andWhere(\Query\Operator::like(['wpos.id' => getVal('location')]));
        }

        if (findModule(\Modules::PRODUCTS_BATCHES)) {
            $qb->addSelect('wp.id_product_batch');
        }

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

        return $qb;
    }
}

return WarehouseProductsList::class;
