<?php

namespace Mnv\Models\Users;

use Mnv\Core\Config;
use Mnv\Core\Test\Logger;
use Mnv\Models\Users\Exceptions\NoUserException;
use Mnv\Models\Users\Exceptions\EmptyUserIdException;
use Mnv\Models\Users\Exceptions\UserNotDeletedException;
use Mnv\Models\Users\Exceptions\NotUserApproveException;
use Mnv\Models\Users\Exceptions\CannotBeRemovedDeveloperException;
use Mnv\Models\Users\Exceptions\CannotBeRemovedAdministratorException;

/**
 * Class Managers
 */
class AdminUser extends AbstractUser
{

    /** @var int $totalUsers кол-во контента данного менеджером  */
    public int $totalContents = 0;

    /**
     * Редактирование
     * @throws NoUserException
     */
    public function edit(?string $userType)
    {
        if (!empty($this->userId)) {
            $this->get($userType);
            if (!empty($this->user)) {
                $this->user['registered'] = gmdate('Y-m-d H:i', $this->user['registered']);
                $this->user['last_login'] = gmdate('Y-m-d H:i', $this->user['last_login']);

                $this->getFiles();
                $this->user['accessLevelName'] = connect()->table('user_group')->select('groupName')->where('groupId', $this->user['accessLevel'])->getValue();

                $this->totalContents = (int)connect()->table('articles')->count('*', 'count')->where('addedBy', $this->user['userId'])->getValue();

                $this->user['notice'] = $this->notice();

            } else {
                throw new NoUserException();
            }
        }
    }

    private function notice(): string
    {
        if ($res = connect()->table('notice')->where($this->primaryKey, $this->user['userId'])->get()) {
            return htmlspecialchars( $res->notice, ENT_QUOTES, Config::getValue('charset') );
        }

        return '';
    }


    public function prepare(array $data, int $managerId): bool
    {

        $data['modifiedBy']   = $managerId;
        $data['modifiedOn']   = gmdate('Y-m-d H:i:s');

        if (empty($this->userId)) {

            $data['password']      = \password_hash($data['password'], \PASSWORD_DEFAULT);
            $data['addedBy']       = $managerId;
            $data['addedOn']       = gmdate('Y-m-d H:i:s');
            $data['registered']    = \time();
            $data['last_login']    = \time();
            $data['verified']      = 1;

            if ($this->insert($data)) {
                Logger::init()->info("Добавлен новый менеджер «" . $data['fullName'] . "» ", $managerId)->save();
                return true;
            }
        } else {

            if (!empty($data['newPassword'])) {
                $data['password'] = \password_hash($data['newPassword'], \PASSWORD_DEFAULT);
            }
            unset($data['newPassword']);

            if ($this->update($data)) {
                Logger::init()->info("Менеджер «" . $data['fullName'] . "» отредактирован", $managerId)->save();
                return true;
            }
        }

        return false;
    }
//    /**
//     * Создание нового менеджера
//     *
//     * @param array $user
//     * @param int $managerId
//     * @return bool
//     */
//    public function add(array $user, int $managerId): bool
//    {
//        $user['password']      = \password_hash($user['password'], \PASSWORD_DEFAULT);
//        $user['addedBy']       = $managerId;
//        $user['addedOn']       = gmdate('Y-m-d H:i:s');
//        $user['modifiedBy']    = $managerId;
//        $user['modifiedOn']    = gmdate('Y-m-d H:i:s');
//        $user['registered']    = \time();
//        $user['last_login']    = \time();
//        $user['verified']      = 1;
//
//        if ($this->insertUser($user)) {
//            return true;
//        }
//
//        return false;
//    }
//
//    /**
//     * Обновление менеджера
//     *
//     * @param array $user
//     * @param int $managerId
//     * @return bool
//     * @throws NotUpdateUserException
//     */
//    public function update(array $user, int $managerId): bool
//    {
//        if (!empty($this->userId)) {
//
//            $user['modifiedBy']    = $managerId;
//            $user['modifiedOn']    = gmdate('Y-m-d H:i:s');
//
//            if (!empty($user['newPassword'])) {
//                $user['password'] = \password_hash($user['newPassword'], \PASSWORD_DEFAULT);
//            } else {
//                unset($user['newPassword']);
//            }
//            $user['receiveEmails'] = !empty($user['receiveEmails']) ? 1 : 0;
//
//            if ($this->updateUser($user)) {
//
//                $this->get($user['userType']);
//                $this->user['image'] = $this->getFile($this->user['fileId']);
//                $this->user['accessLevelName'] = lang('managers:accessRole:' . $this->user['accessLevel']);
//
//                return true;
//            }
//
//            throw new NotUpdateUserException();
//        }
//        return false;
//    }

    /**
     * Права доступа / Access rights
     *
     * @param $accessLevelId
     * @return array
     */
    public function accessRights($accessLevelId): array
    {
        $permission = json_decode(file_read(GLOBAL_ROOT."/admin/menu/menu.json"), true);
        $result = array();

        foreach ($permission as $key => $item) {
            if (!in_array($accessLevelId, $item['accessLevel']))  continue;
            $result[$key] = $item;
            $child = array();
            foreach ($result[$key]['children'] as $childrenKey => $children) {
                if (!in_array($accessLevelId, $children['accessLevel'])) continue;
                $child[$childrenKey] = $children;
            }
            unset( $result[$key]['children']);

            $result[$key]['children'] = $child;
        }

        return $result;
    }


    /**
     * Удаление пользователя
     *
     * @throws NoUserException
     * @throws EmptyUserIdException
     * @throws UserNotDeletedException
     * @throws CannotBeRemovedDeveloperException
     * @throws CannotBeRemovedAdministratorException
     */
    public function remove(?string $userType)
    {
        if (!empty($this->userId)) {
            $this->get($userType);
            if (!empty($this->user)) {
                if ( $this->user['userType'] == UserTypes::DEVELOPER ) {
                    if ( !$this->getUserByRole(UserTypes::DEVELOPER) ) {
                        throw new CannotBeRemovedDeveloperException();
                    }
                } else if ( $this->user['userType'] == UserTypes::ADMIN ) {
                    if ( !$this->getUserByRole(UserTypes::ADMIN) ) {
                        throw new CannotBeRemovedAdministratorException();
                    }
                }
                if ( !$this->removeUser() ) {
                    throw new UserNotDeletedException();
                }
            } else {
                throw new NoUserException();
            }
        } else {
            throw new EmptyUserIdException();
        }
    }

    /**
     * Обновление статуса
     *
     * @throws NoUserException
     * @throws EmptyUserIdException
     * @throws NotUserApproveException
     */
    public function approve()
    {
        if (!empty($this->userId)) {
            $this->get();
            if (!empty($this->user)) {
                if (!$this->approveUser()) {
                    throw new NotUserApproveException();
                }
            }else {
                throw new NoUserException();
            }
        } else {
            throw new EmptyUserIdException();
        }
    }






}