<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;
use Mnv\Core\SortTable;
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();
        $siteUser->sortTableId = $this->module;

        /** Заголовок, название подключаемого шаблона */
        $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');
        $siteUser->userId       = (int) $this->request->get('id');
        $siteUser->sortBy       = $this->request->get('sortBy', '');
        $siteUser->sortOrder    = $this->request->get('sortOrder', '');

        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;
        }
        /** Сортировать таблицу */
        else if ($this->action === 'sort_table') {
            SortTable::init()->setSort($siteUser->sortTableId, $siteUser->sortBy, $siteUser->sortOrder);
            $result = array('status' => 200, 'table' => $siteUser->sortTableId, 'sortBy' => $siteUser->sortBy, 'sortOrder' => $siteUser->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($siteUser->sortTableId);
            $result = array('status' => 200, 'table' => $siteUser->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();
        }

        $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');
    }
}




