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

function smarty_function_fetch_comments($params, &$smarty){

	$assign    = fetch_getParam('assign', $params, 'comments');
	$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);
	$articleId = (int) fetch_getParam('articleId', $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($articleId)) connect()->where('articleId', '=', $articleId);
//	connect()->where('answerId', '=', $answerId);

    if ($comments =  connect()->table('comments')->select($fields)->orderBy($orderBy)->limit($limit)->getAll('array')) {
//        $comments = buildTreeFromObjects($comments);
        foreach ($comments as $comment) {
            if (!empty($comment['answer'])) {
                $comment['count'] = count($comment['answer']);
            }
        }

//        print_r($comments);

    } else {
        $comments = null;
    }
	$smarty->assign($assign, $comments);

	return null;
}
// for object
function buildTreeFromObjects($items) {

    $answers = [];

    foreach ($items as $item) {
        $answers[$item['answerId']][] = $item;
    }

    foreach ($items as $item) {
        if (isset($answers[$item['commentId']])) {
            $item['answer'] = $answers[$item['commentId']];
        }
    }

    return $answers[0];
}
// or array version
function buildTreeFromArray($items) {

    $answers = [];

    foreach ($items as &$item) {
        $answers[$item['answerId']][] = &$item;
    }
    unset($item);

    foreach ($items as &$item) {
        if (isset($answers[$item['commentId']])) {
            $item['answer'] = $answers[$item['commentId']];
        }
    }

    return $answers[0];
}
?>