<?php
/******************************************************************************/
//                                                                            //
//                             Smarty plugin                                  //
//                            @package Smarty                                 //
//							 @subpackage plugins                              //
//                        http://life-style.uz/                               //
//                   produced by Life Style, life-style.uz                    //
//                                                                            //
/******************************************************************************/


function smarty_function_fetch_product_related($params, &$smarty) {

	$assign        = fetch_getParam('assign', $params, 'products');
	$fields        = fetch_getParam('fields', $params, 'productId, sectionId, publishedOn, title, alias, url, summary, isFeatured, special, brand, price, old_price, sku, ikpu, quantity, counter, rating, votes, stock_status_id');
	$status        = fetch_getParam('status', $params, 'V');
	$limit         = (int) fetch_getParam('limit', $params, 9);
	$perPage       = (int) fetch_getParam('perPage', $params, $limit);
	$isFeatured    = fetch_getParam('isFeatured', $params, NULL);

    $orderBy         = fetch_getParam('order', $params, NULL);
    $productId     = fetch_getParam('productId', $params);
	$page          = (int) fetch_getParam('page', $params);

	$image          = fetch_getParam('image', $params, true);
	$imageType      = fetch_getParam('imageType', $params, 'general'); // general, gallery
	
	$sectionInfo    = fetch_getParam('sectionInfo', $params, true);
	$parentsInfo    = fetch_getParam('parentsInfo', $params, false);


	if (empty($assign)) {
		$smarty->_trigger_fatal_error('fetch_product_related: "assign" must not be empty');
		return;
	}


    /** checking article fields */
    fetch_products_filterFields($fields);

	if ($page < 1) $page = 1;
    $products = [];

    $product_related = connect('product_related')->select('relatedId')->where('productId', $productId)->getAll('array');
    if (!empty($product_related)) {
        $product_related = array_column($product_related, 'relatedId', 'relatedId');

        if (!empty($status)) connect()->where('status', $status);
        if (!is_null($isFeatured)) connect()->where('isFeatured', $isFeatured ? 1 : 0);
        if (!is_null($orderBy)) connect()->orderBy($orderBy);
        if ($products = connect('products')->select($fields)->in('productId', $product_related)->pagination($perPage, $page)->getAll('array')) {
        //	print_r(connect()->getQuery());
            $products = prepareProducts($products, $sectionInfo, $parentsInfo, $image, $imageType);

        }
    }


//     print_r($products);
    $smarty->assign($assign, $products);


	
	return null;
}
