<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Core\SortTable;
use Mnv\Models\Users\UserTypes;
use Mnv\Models\Users\UserGroups;
use Mnv\Models\Users\UserFactory;
use Mnv\Models\Users\Exceptions\NoUserException;
use Mnv\Models\Users\Exceptions\EmptyUserIdException;
use Mnv\Models\Users\Exceptions\UserNotDeletedException;
use Mnv\Models\Users\Exceptions\CannotBeRemovedDeveloperException;
use Mnv\Models\Users\Exceptions\CannotBeRemovedAdministratorException;

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

    public function fetch()
    {
        $adminUser = UserFactory::developerUser();
        $adminUser->sortTableId = $this->module;

        /** Заголовок, название подключаемого шаблона */
        $this->smarty->assign('activeItem', 'developers');
        $this->smarty->assign('title', "Разработчики");

        /** Получаемые параметры $_GET / $_POST */
        $adminUser->userId  = (int) $this->request->get('id','');
        $adminUser->sortBy       = $this->request->get('sortBy', '');
        $adminUser->sortOrder    = $this->request->get('sortOrder', '');

        if ($this->action == 'remove') {
            try {
                $adminUser->remove(UserTypes::DEVELOPER);
                response()->make("deleteSuccess('" . $adminUser->userId . "');", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            } catch (CannotBeRemovedDeveloperException $e) {
                response()->make("notDeleteDeveloper();", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            } catch (CannotBeRemovedAdministratorException $e) {
                response()->make("notDeleteAdministrator();", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            } catch (EmptyUserIdException | NoUserException $e) {
                response()->make("userNotFound();", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            } catch (UserNotDeletedException $e) {
                response()->make("deleteError();", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            }
            exit();
        }
        /** Сортировать таблицу */
        else if ($this->action === 'sort_table') {
            SortTable::init()->setSort($adminUser->sortTableId, $adminUser->sortBy, $adminUser->sortOrder);
            $result = array('status' => 200, 'table' => $adminUser->sortTableId, 'sortBy' => $adminUser->sortBy, 'sortOrder' => $adminUser->sortOrder);

            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 === 'clear_sort_table') {
            SortTable::init()->clearSort($adminUser->sortTableId);
            $result = array('status' => 200, 'table' => $adminUser->sortTableId);

            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();
        }


        $adminUser->filter = array_filter([
            'status'        => $this->status,
            'query'         => $this->query,
            'userType'      =>  UserTypes::DEVELOPER,
        ]);

        /** получение всех менеджеров */
        $users = collect($adminUser->all('userId ASC', $this->limit, $this->page))->map(function ($item) use ($adminUser) {
            $item['statusName'] = lang('managers:statuses:' . $item['status']);
            $item['accessLevelName'] = UserGroups::accessLevelName($item['accessLevel']);
            $item['registered'] = langDate(adjustTime(gmdate('Y-m-d H:i', $item['registered']), false, 'Y-m-d H:i'));
            $item['last_login'] = langDate(adjustTime(gmdate('Y-m-d H:i', $item['last_login']), false, 'Y-m-d H:i'));
            $item['image'] = $adminUser->getFile($item['userId']);

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

        /** получение кол-во менеджеров */
        $adminUser->total();
        $pages = getPageNums($adminUser->total, $this->page, $this->limit, 0, 4, 4, 0);

        $this->smarty->assign('pageNums', $pages);
        $this->smarty->assign('managers', $users);



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

        /** Права доступа к данному шаблону */
        if ($this->manager['userType'] == UserTypes::DEVELOPER) {
            return $this->smarty->fetch('views/users/developers.tpl');
        }

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

    }

}









