<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\Users\UserGroups;

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

    /**
     * Вывод всех пользователей
     */
    public function fetch()
    {

        $userGroup = new UserGroups($this->request);

        $this->smarty->assign('activeItem', 'managergroups');
        $this->smarty->assign('title', "Группы пользователей");

        $this->smarty->assign('statuses', array_slice(lang('general:statuses'), 1, 2));
        $this->smarty->assign('permission', $this->accessRights());

        if ($this->action == 'remove') {
            $result = $userGroup->remove()
                ? array('status' => 200, 'message' => 'Группа удалена', 'type' => 'success')
                : array('status' => 403, 'message' => 'Группа не удалена', 'type' => 'error');

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }
        else if ($this->action == 'status') {
            $result = $userGroup->status()
                ? array('data' => true, 'status' => $userGroup->status, 'type' => 'success')
                : array('data' => false, 'status' => $userGroup->status, 'type' => 'error');

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }


        $groups = collect($userGroup->all($this->limit, $userGroup->total, $this->manager['userType']))->map(function ($item) use ($userGroup) {
            $item['statusName']    = lang('sections:statuses:' . $item['status']);
            $item['countUsers']    = $userGroup->getCountGroupUsers($item['groupId']);
            $item['dateChange']    = langDate(adjustTime($item['modifiedOn'], false, 'd.m.Y H:i'));

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

        $this->smarty->assign('groups', $groups);

        /** pagination */
        $userGroup->total($this->manager['userType']);
        $pages = getPageNums($userGroup->total, $this->page, $this->limit, 0, 4, 4, 0);
        $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('managergroups')) {
            return $this->smarty->fetch('views/users/groups.tpl');
        }

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


}
