<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;
use Mnv\Core\Test\Logger;

use Mnv\Models\Users\UserTypes;
use Mnv\Models\Users\UserFactory;
use Mnv\Models\Users\Exceptions\NoUserException;
use Mnv\Models\Users\Exceptions\EmptyUserIdException;
use Mnv\Models\Users\Exceptions\NotUserApproveException;
use Mnv\Models\Users\Exceptions\UserNotDeletedException;

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

    public function fetch()
    {
        $siteUser = UserFactory::siteUser();

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

        $this->smarty->assign('statuses', lang('users:statuses'));
        $this->smarty->assign('subscribes', lang('users:subscribes'));

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

        if ($this->action === 'remove') {
            try {
                $siteUser->remove(UserTypes::CUSTOMER);
                Logger::init()->info("Пользователь «ID-" . $siteUser->userId . "» удален.", $this->manager['userId'])->save();
                response()->make("deleteSuccess('" . $siteUser->userId . "');", \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;
        }

        if ($this->action === 'approve') {
            try {
                $siteUser->approve();
                response()->make("approveSuccess('" . $siteUser->userId . "');", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            } catch (EmptyUserIdException | NoUserException $e) {
                response()->make("notFound();", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            } catch (NotUserApproveException $e) {
                response()->make("approveError();", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            }
            exit;
        }

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

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

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

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

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

        /** Права доступа к данному шаблону */
        if ($this->permissions('users')) {
            return $this->smarty->fetch('views/users/users.tpl');
        }

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




