<?php

namespace KupShop\ReclamationsBundle\Query;

use KupShop\ReclamationsBundle\Util\ReclamationsUtil;
use Query\QueryBuilder;

class Reclamations
{
    public static function joinOrders()
    {
        return function (QueryBuilder $qb) {
            $qb->leftJoin('r', 'order_items', 'oi', 'oi.id = r.id_item')
                ->leftJoin('oi', 'orders', 'o', 'o.id = oi.id_order');
        };
    }

    public static function getReturnablePiecesSpec()
    {
        return function (QueryBuilder $qb) {
            // pocet kusu v objednavce - pocet kusu v nevyrizenych reklamacich - pocet kusu ve vratkach
            $returnable_pieces = sqlQueryBuilder()
                ->from('reclamations', 'r')
                ->andWhere('r.id_item = oi.id AND r.status != '.ReclamationsUtil::STATUS_HANDLED);

            if (findModule(\Modules::RETURNS)) {
                $in_returns = sqlQueryBuilder()->select('COALESCE(SUM(ri.pieces), 0)')
                    ->from('return_items', 'ri')->andWhere('oi.id = ri.id_item');
                $returnable_pieces->addSubselect($in_returns, 'pieces', 'oi.pieces - COALESCE(SUM(r.pieces), 0) - {}');
            } else {
                $returnable_pieces->addSelect('oi.pieces - COALESCE(SUM(r.pieces), 0)');
            }

            $qb->addSubselect($returnable_pieces, 'returnable_pieces');
        };
    }
}
