<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}

use Mnv\Core\AdminMnv;

use Mnv\Models\Reviews;

/**
 * Class ProductReviewsAdmin
 * @package Mnv\Admin\Controllers
 */
class ProductReviewsAdmin extends AdminMnv
{

    public $order;
    public $where = array();
    public $join = array();

    public function fetch()
    {

        $dateSelector = new StatsDateSelector(false, 'commentDateSelector');

//        $comment = new Comments(
//            getRequestVar('id', ''),
//            getRequestVar('comment','', true)
//        );
        $comment = new Reviews($this->request);

        $this->smarty->assign('activeItem','comments');
        $this->smarty->assign('title', lang('comments:title'));
        /** statuses */
        $this->smarty->assign('statuses', lang('comments:statuses'));

        if (($this->action === 'bulk') && $comment->bulk($comment->bulk)) {
            $this->messages['bulk_save'] = true;
        }

        /** фильтровать контент */
        $comment->filter = array_filter([
            'dateStart'     => $dateSelector->dateStart,
            'dateEnd'       => $dateSelector->dateEnd,
            'status'        => $this->status,
            'query'         => $this->query,
        ]);

        /* показывать комментарии только из разрешенных разделов */
        $comments = collect($comment->all($this->limit, $this->page))->map(function ($item) {
            $item['statusName']  = lang('comments:statuses:' . $item['status']);
            $item['addedOn'] = adjustTime($item['addedOn'], false, 'd.m.Y');
            $item['product'] = connect('products')->select('productId, title, url')->where('productId', $item['productId'])->get('array');
//            $productIds[$item['productId']] = $item['productId'];
//            if (!empty($productIds)) {
//                if ($products = connect('products')->select('productId, title, url')->in('productId', array_keys($productIds))->indexKey('productId')->getAllIndexes('array')) {
//                    $item['products'] = $products[$item['productId']];
//                }
//            }

            return $item;
        })->all();

        $comment->total();
        $pages = getPageNums($comment->total, $this->page, $this->limit, 0, 4, 4, 0);
        $this->smarty->assign('totalComments', $comment->total);
        $this->smarty->assign('comments', $comments);
        $this->smarty->assign('pageNums', $pages);


        if (!empty($this->errors)) {
            $this->smarty->assign('errors', $this->errors);
        }
        if (!empty($this->messages)) {
            $this->smarty->assign('messages', $this->messages);
        }

        if ($this->permissions('reviews')) {
            return $this->smarty->fetch('views/comments/reviews.tpl');
        }

        $this->smarty->assign('title', 'Access Denied');
        return $this->smarty->fetch('accessIsDenied.tpl');

    }

}