<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\Comments;

/**
 * Class CommentsAdmin
 * @package Mnv\Admin\Controllers
 */
class CommentsAdmin 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 Comments($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');;
            $articleIds[$item['articleId']] = $item['articleId'];
            if (!empty($articleIds)) {
                if ($articles = connect()->table('articles')->select('articleId, title, url')->in('articleId', array_keys($articleIds))->indexKey('articleId')->getAllIndexes('array')) {
                    $item['article'] = $articles[$item['articleId']];
                }
            }
            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('comments')) {
            return $this->smarty->fetch('views/comments/comments.tpl');
        }

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

    }

}