<?php

namespace KupShop\PreordersBundle\Admin\lists;

use KupShop\AdminBundle\AdminList\BaseList;
use Query\Operator as Op;
use Query\QueryBuilder;

class PreordersDatesList extends BaseList
{
    protected ?string $tableAlias = 'pd';

    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Číslo' => ['field' => 'id', 'spec' => 'pd.id'],
            'Název předobjednávky' => ['field' => 'name', 'spec' => 'po.name'],
            'Popis' => ['field' => 'description', 'spec' => 'pd.description', 'render' => 'renderHTML'],
            'Datum otevření' => ['field' => 'date_start', 'spec' => 'pd.date_start', 'render' => 'renderDate'],
            'Datum skrytí' => ['field' => 'date_end', 'spec' => 'pd.date_end', 'render' => 'renderDate'],
            'Datum expedice' => ['field' => 'date_shipment', 'spec' => 'pd.date_shipment'],
            'Cena zbylého zboží' => ['field' => 'price_remaining', 'spec' => 'totals.price_remaining', 'render' => 'renderPrice'],
        ],
    ];

    public function getQuery()
    {
        $qb = sqlQueryBuilder()
            ->from('preorders_dates', 'pd')
            ->leftJoin('pd', 'preorders', 'po', 'pd.id_preorder = po.id');

        $totals = sqlQueryBuilder()
            ->select(
                'pi.id_preorder_date AS id',
                'SUM(pi.piece_price * currencies.rate * (pi.pieces - pi.pieces_sent)) AS price_remaining',
            )
            ->from('preorders_items', 'pi')
            ->leftJoin('pi', 'currencies', 'currencies', 'pi.currency = currencies.id')
            ->groupBy('pi.id_preorder_date');

        $qb->leftJoinSubQuery('pd', $totals, 'totals', 'totals.id = pd.id');

        return $this->getFilterQueryParams($qb);
    }

    public function getFilterQueryParams(QueryBuilder $qb): QueryBuilder
    {
        if ($ids = getVal('id_preorder_date')) {
            $qb->andWhere(Op::inIntArray($ids, 'pd.id_preorder_date'));
        }

        if ($ids = getVal('id_preorder')) {
            $qb->andWhere(Op::inIntArray($ids, 'pd.id_preorder'));
        }

        return $qb;
    }
}

return PreordersDatesList::class;
