<?php

function smarty_function_get_positions($params, &$smarty)
{
    $positions = sqlQueryBuilder()->select('wpos.*')
        ->from('warehouse_positions', 'wpos')
        ->groupBy('wpos.id')
        ->setMaxResults(3);

    $id_order_item = getVal('id_item', $params);
    $location = getVal('id_location', $params);
    if ($id_order_item) {
        $positions->join('wpos', 'warehouse_products', 'wp', 'wp.id_position = wpos.id')
            ->join('wp', 'order_items', 'oi', 'oi.id_product = wp.id_product AND oi.id_variation IS NULL OR oi.id_variation = wp.id_variation')
            ->andWhere(\Query\Operator::equals(['oi.id' => $id_order_item]));
    } elseif ($location) {
        $positions->andWhere(\Query\Operator::equals(['wpos.id_location' => $location]))
            ->orderBy('RAND()');
    } else {
        $positions->orderBy('RAND()');
    }

    if (getVal('only_empty', $params)) {
        $positions
            ->leftJoin('wpos', 'warehouse_products', 'wprod', 'wpos.id = wprod.id_position')
            ->andHaving('COUNT(wprod.id_product) = 0');
    }

    $positions = $positions->execute()->fetchAll();

    $assign = getVal('assign', $params);
    if (!empty($assign)) {
        $smarty->assign($assign, $positions);
    } else {
        return $positions;
    }
}
