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

function smarty_function_fetch_reviews($params, &$smarty){

	$assign    = fetch_getParam('assign', $params, 'reviews');
    $count_rating  = fetch_getParam('count_rating', $params, '');
	$fields    = fetch_getParam('fields', $params, '*');
	$status    = fetch_getParam('status', $params, 'approved');
	$orderBy   = fetch_getParam('orderBy', $params, 'addedOn ASC');
	$limit     = (int) fetch_getParam('limit', $params, 300);
    $productId = (int) fetch_getParam('productId', $params);
	$answerId  = (int) fetch_getParam('answerId', $params, 0);

	if(empty($assign)){
		$smarty->_trigger_fatal_error('fetch_comments: "assign" must not be empty');
		return;
	}
	
	/* conditions */
	if(!empty($status)) connect()->where('status', $status);
	if(!empty($productId)) connect()->where('productId',  $productId);
//	connect()->where('answerId', '=', $answerId);

    $array = array('1', '2', '3', '4', '5');
    $counters = [];
    if ($comments =  connect('product_comments')->select($fields)->orderBy($orderBy)->limit($limit)->getAll('array')) {

        foreach ($comments as $comment) {
            $comment['rating'] = (int)$comment['rating'];

            if (!isset($counters[$comment['rating']])) $counters[$comment['rating']] = 0;

            if (!in_array($comment['rating'], $array)) {
                $counters[$comment['rating']] = 0;
            } else {
                $counters[$comment['rating']]++;
            }
        }

//        print_r($counters);
//        print_r($comments);

    } else {
        $comments = null;
    }


	$smarty->assign($assign, $comments);
	$smarty->assign($count_rating, $counters);

	return null;
}
?>