<?php

namespace KupShop\CatalogBundle\Query;

use Query\Operator;
use Query\Operator as Op;
use Query\QueryBuilder;

class ProductsTypes
{
    public static function joinAlsoBought($id_products, $limit = null)
    {
        return function (QueryBuilder $qb) use ($id_products, $limit) {
            $ordersWithProductsQb = sqlQueryBuilder()->select('id_order')->from('order_items')
                ->where('total_price > 0')
                ->andWhere(Operator::inIntArray($id_products, 'id_product'))
                ->orderBy('id', 'DESC')
                // TODO: TMP "fix" to speed-up cart rendering during black-friday, REVERT ME!
                ->setMaxResults(10);

            $alsoBoughtProductsQb = sqlQueryBuilder()
                ->select('oi.id_product', 'COUNT(oi.id_product) cnt')
                ->from('order_items', 'oi')
                ->join('oi', 'ordersWithProducts', 'oil', 'oil.id_order = oi.id_order')
                ->andWhere(Op::not(Op::inIntArray($id_products, 'oi.id_product')))
                ->andWhere('oi.total_price > 0') // excluding gifts & returns
                ->groupBy('oi.id_product')
                ->orderBy('cnt', 'DESC');

            if ($limit) {
                $alsoBoughtProductsQb->setMaxResults($limit);
            }

            $qb->withExpression('ordersWithProducts', $ordersWithProductsQb)
               ->withExpression('alsoBoughtProducts', $alsoBoughtProductsQb)
               ->join('p', 'alsoBoughtProducts', 'ic', 'ic.id_product = p.id');
        };
    }
}
