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

use Mnv\Core\Utilities\Cookie\Session;

function smarty_function_fetch_products($params, &$smarty) {
	global $fetchedProducts;

	$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');
	$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);

	$query         = fetch_getParam('query', $params, NULL);
	$match         = fetch_getParam('match', $params, 'any');
	$order         = fetch_getParam('order', $params, NULL);
	$orderBy       = fetch_getParam('orderBy', $params, $order);
	$grouping      = (boolean) fetch_getParam('grouping', $params, false);
	$section       = fetch_getParam('section', $params);
    $productId     = fetch_getParam('productId', $params);
	$page          = (int) fetch_getParam('page', $params);
	$skip          = fetch_getParam('skip', $params, NULL);
	$noSubsections = (boolean) fetch_getParam('noSubsections', $params, false);

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

    $special        = fetch_getParam('special', $params, '');


    $brand          = fetch_getParam('brand', $params, '');
    $category       = fetch_getParam('category', $params, '');

	$minPrice 		= (int) fetch_getParam('minPrice', $params, '');
	$maxPrice 		= (int) fetch_getParam('maxPrice', $params, '');
	
	$assignPagination = fetch_getParam('assignPagination', $params);
	$path             = fetch_getParam('path', $params);
	$seFriendly       = (boolean) fetch_getParam('seFriendly', $params);
	$pnFirst          = (int) fetch_getParam('pnFirst', $params, 0);
	$pnBefore         = (int) fetch_getParam('pnBefore', $params, 4);
	$pnAfter          = (int) fetch_getParam('pnAfter', $params, 4);
	$pnLast           = (int) fetch_getParam('pnLast', $params, 0);
	
	if (empty($assign)) {
		$smarty->_trigger_fatal_error('fetch_products: "assign" must not be empty');
		return;
	}

    /** conditions */
	if (empty($path)) $path = array();


	if (Session::has('sort')) {
        $orderBy = Session::get('sort');
    }
    if (!empty($category)) $section = $category;

    /** calculate product popularity product fields */
    if (!empty($orderBy) && $orderBy == 'popularity') $orderBy = 'popularityLast7days';
    fetch_products_calculatePopularity($orderBy);

    filterProducts($status, $isFeatured, $productId, $special, $brand, $orderBy, $query, $minPrice, $maxPrice);
    /** conditions */
//    fetch_products_addFilterConditions($alcohol, $color, $sugar, $year, $mill, $typeAlc);

    /** query conditions */
    if (!is_null($query) && is_array($path)) $path[] = "query=".urlencode($query);
    fetch_articles_addQueryConditions($query, $match, $fields, $orderBy);
    /** add section conditions */

    fetch_articles_addSectionConditions($section, $noSubsections);

    /** skipping articles */
    fetch_products_addSkipConditions($skip);
    /** checking article fields */
    fetch_products_filterFields($fields);

	if ($page < 1) $page = 1;

	$products = connect('products')->select($fields)->pagination($perPage, $page)->indexkey('productId')->getAll('array');
//	print_r(connect()->getQuery());
    if ($products) {
        $products = prepareProducts($products, $sectionInfo, $parentsInfo, $image, $imageType);
        foreach ($products as $productId => $product) {
            if (isset($product['productId'])) {
                $products[$productId]['features'] = getProductFeatureValues($product['productId']);
//                if (isset($product['brand'])) {
//                    $products[$productId]['brand'] = getProductBrand($product['brand']);
//                }
            }
        }
    }
    
    if ($grouping == true) {
        $products = groupBy($products, 'brand');
    }

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

	/** saving fetched articles for SKIP ability */
	if(empty($fetchedProducts[$assign])) {
        $fetchedProducts[$assign] = array();
    }
	if(!empty($products)) {
        foreach ($products as $product) {
            $fetchedProducts[$assign][] = $product['productId'];
        }
    }

    /** Pagination */
	if (!empty($assignPagination)) {

        /** calculate article popularity article fields */
        fetch_articles_calculatePopularity($orderBy);

        filterProducts($status, $isFeatured, $productId, $special, $brand, $orderBy, $query, $minPrice, $maxPrice);
        /** conditions */
//        fetch_articles_addFilterConditions($alcohol, $color, $sugar, $year, $mill, $typeAlc);

        /** query conditions */
        if (!is_null($query) && is_array($path)) $path[] = "query=".urlencode($query);
        fetch_articles_addQueryConditions($query, $match, $fields, $orderBy);
        /** add section conditions */
//        if (empty($category)) $section = $category;
        fetch_articles_addSectionConditions($section, $noSubsections);

        /** skipping articles */
        fetch_articles_addSkipConditions($skip);
        /** checking article fields */
        fetch_articles_filterFields($fields);

//        $total = connect('products')->countDistinct('productId')->getValue();
//        print_r(connect()->getQuery());
//        print_r($total);
        /** page numbering */
//		if (is_array($path)) {
//			$path = SITE_URL.'/'.basename($_SERVER['PHP_SELF']).'?'.(!empty($path) ? implode('&', $path).'&' : '');
//			$seFriendly = false;
//		}
//		$pagination = getPageNums($total, $page, $perPage, $pnFirst, $pnBefore, $pnAfter, $pnLast, $path, $seFriendly);
//		$smarty->assign($assignPagination, $pagination);

        $total = connect('products')->select('productId')->count('*', 'total')->get('array');
//        print_r(connect()->getQuery());
        if (is_array($path)) {
            $path = SITE_URL.'/'.basename($_SERVER['PHP_SELF']).'?'.(!empty($path) ? implode('&', $path).'&' : '');
            $seFriendly = false;
        }
        $pagination = getPageNums($total['total'], $page, $perPage, $pnFirst, $pnBefore, $pnAfter, $pnLast, $path, $seFriendly);
//        print_r($pagination);
        $smarty->assign($assignPagination, $pagination);

	}
	
	return null;
}

function filterProducts($status, $isFeatured, $productId, $special, $brand, $orderBy, $query, $minPrice, $maxPrice)
{

    /** conditions */
    connect()->where('publishedOn','<=', gmdate('Y-m-d H:i:s'));
    if (!empty($status))    connect()->where('status', $status);
    if (!empty($brand))    connect()->in('brand', $brand);
    if (!empty($special))   connect()->where('special', $special);
    if (!empty($productId)) connect()->where('productId', '!=', $productId);
    if (!empty($minPrice) && !empty($maxPrice)) connect()->between('price', $minPrice, $maxPrice);
    if (!is_null($isFeatured)) connect()->where('isFeatured','=',$isFeatured ? 1 : 0);

    if (empty($orderBy)) {
        connect()->orderBy(is_null($query) ? 'publishedOn DESC' : 'publishedOn DESC');
    } else {
        if ($orderBy == 'popularity') {
            connect()->orderBy('popularityLast7days DESC');
        } else if ($orderBy == 'asc') {
            connect()->orderBy('price ASC');
        } else if ($orderBy == 'desc') {
            connect()->orderBy('price DESC');
        } else if ($orderBy == 'rating') {
            connect()->orderBy('rating DESC');
        } else {
            connect()->orderBy($orderBy);
        }
    }
}

function groupBy($array, $key): array
{
    $return = array();
    if (!empty($array)) {
        foreach ($array as $val) {
            $return[$val->$key][] = $val;
        }
    }
    return $return;
}

?>