<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;
use Mnv\Core\Test\Logger;
use Mnv\Core\Validations\ValidateEmail;
use Mnv\Core\Validations\Exceptions\InvalidEmailException;

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\NotUpdateUserException;

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

    /**
     * Вывод всех пользователей
     */
    public function fetch()
    {
        $adminUser = UserFactory::adminUser();

        $this->smarty->assign('activeItem', 'managers');
        $this->smarty->assign('title', lang('managers:title'));

        $this->smarty->assign('statuses', lang('managers:statuses'));
        $this->smarty->assign('groups', UserGroups::selectGroup(UserTypes::ADMIN));

        $adminUser->user    = $this->request->get('manager','');
        $adminUser->userId  = (int) $this->request->get('id','');
        $image              = $this->request->get('image', '');
        $imageId            = (int) $this->request->get('imageId');


        if ($this->action == 'add' || $this->action == 'edit') {

            try {
                $adminUser->edit(UserTypes::ADMIN);
            } catch (NoUserException $e) {
                $this->errors['user_not_found'] = true;
            }

        }

        /** сохранение данных */
        else if ($this->action == 'save' || $this->action == 'apply') {

            if (empty($adminUser->user['accessLevel'])) $this->errors['access_level_empty'] = true;
            if (empty($adminUser->user['status'])) $this->errors['status_empty'] = true;
            $adminUser->user['userType'] =  UserTypes::ADMIN;

            /** loginName */
            if (!empty($adminUser->user['loginName'])) {
                $adminUser->user['loginName'] = str_replace(" ", '', $adminUser->user['loginName']);
                if (empty($adminUser->user['loginName']) || preg_match('/[^a-zA-Z0-9]/', $adminUser->user['loginName'])) $this->errors['loginName'] = true;
            } else {
                $this->errors['login_empty'] = true;
            }

            /** проверяем существование loginName */
            if ($fileName = $adminUser->checkExistenceLoginName($adminUser->user['loginName'])) {
                if ($fileName == $adminUser->user['loginName']) {
                    $this->errors['login_exists'] = true;
                } else {
                    $adminUser->user['loginName'] = $fileName;
                }
            }

            /** fullName */
            $adminUser->user['fullName']  = trim($adminUser->user['fullName']);
            if (empty($adminUser->user['fullName']) || preg_match('/[^[а-яА-ЯёЁa-zA-Z0-9]+$]/', $adminUser->user['fullName'])) {
                $this->errors['fullName'] = true;
            }

            /** email */
            if (!empty($adminUser->user['email'])) {
                try {
                    ValidateEmail::fromString($adminUser->user['email']);
                } catch (InvalidEmailException | \InvalidArgumentException $error) {
                    $this->errors['invalid_email'] = true;
                }
            } else {
                $adminUser->user['email'] = null;
            }
            $adminUser->user['verified'] = ($adminUser->user['status'] == 3) ? 0 : 1;
            $adminUser->user['receiveEmails'] = !empty($adminUser->user['receiveEmails']) ? 1 : 0;

            /** password */
            if (empty($adminUser->userId) && empty($adminUser->user['password'])) $this->errors['password'] = true;
            /** fileId */
//            if (!empty($image['fileId'])) $adminUser->user['fileId'] = $image['fileId'];
            if (!empty($image['fileId'])) $images['fileId'] = $image['fileId'];

//            $adminUser->getOldDataUser($adminUser->userId);
//            if (empty($adminUser->oldUser)) {
//                $this->errors['user_not_found'] = true;
//
//                if (($adminUser->user['userType'] != UserTypes::ADMIN) && ($adminUser->oldUser['userType'] == UserTypes::ADMIN) && $adminUser->accessLevelRole($adminUser->user, UserTypes::ADMIN)) {
//                    $this->errors['no_more_admins'] = true;
//                }
//                if (($adminUser->user['userType'] != UserTypes::DEVELOPER) && ($adminUser->oldUser['userType'] == UserTypes::DEVELOPER) && !$adminUser->accessLevelRole($adminUser->user, UserTypes::DEVELOPER)) {
//                    $this->errors['no_more_developers'] = true;
//                }
//            }

            if (empty($this->errors)) {
                if ($adminUser->prepare($adminUser->user, $this->manager['userId'])) {
                    if (!empty($images['fileId'])) $adminUser->general($adminUser->userId, $images);
                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }

//                if (empty($adminUser->userId)) {
//
//                    if ($adminUser->add($adminUser->user, $this->manager['userId'])) {
//                        if (!empty($images['fileId'])) $adminUser->general($adminUser->userId, $images);
//                        Logger::init()->info("Добавлен новый менеджер «" . $adminUser->user['fullName'] . "» ", $this->manager['userId'])->save();
//                        $this->messages['saved'] = true;
//                    } else {
//                        $this->errors['not_saved'] = true;
//                    }
//
//                } else {
//
//                    $adminUser->getOldDataUser($adminUser->userId);
//                    if (empty($adminUser->oldUser)) {
//                        $this->errors['user_not_found'] = true;
//                    }
//
//                    if (($adminUser->user['userType'] != UserTypes::ADMIN) && ($adminUser->oldUser['userType'] == UserTypes::ADMIN) && $adminUser->accessLevelRole($adminUser->user, UserTypes::ADMIN)) {
//                        $this->errors['no_more_admins'] = true;
//                    }
//                    if (($adminUser->user['userType'] != UserTypes::DEVELOPER) && ($adminUser->oldUser['userType'] == UserTypes::DEVELOPER) && !$adminUser->accessLevelRole($adminUser->user, UserTypes::DEVELOPER)) {
//                        $this->errors['no_more_developers'] = true;
//                    }
//
//
//                    if (empty($this->errors)) {
//                        try {
//                            $adminUser->update($adminUser->user, $this->manager['userId']);
//                            if (!empty($images['fileId'])) $adminUser->general($adminUser->userId, $images);
//                            Logger::init()->info("Менеджер «" . $adminUser->user['fullName'] . "» отредактирован", $this->manager['userId'])->save();
//                            $this->messages['saved'] = true;
//                        } catch (NotUpdateUserException $e) {
//                            $this->errors['not_saved'] = true;
//                        }
//                    }
//                }


                try {
                    $adminUser->edit(UserTypes::ADMIN);
                } catch (NoUserException $e) {
                    $this->errors['user_not_found'] = true;
                }
                if (empty($this->errors) && $this->action == 'save') {
                    redirect($this->adminUrl . "/managers?" . $this->buildQueryString(['page'      => $this->page]));
                }
            }

            try {
                $adminUser->edit(UserTypes::ADMIN);
            } catch (NoUserException $e) {
                $this->errors['user_not_found'] = true;
            }

        }
         else if ($this->action == 'deleteImage') {

             $result = $adminUser->removeUserImage($imageId)
                 ? array('status' => 200, 'message' => lang('javascript:deletingImage'), 'type' => 'success')
                 : array('status' => 500, 'message' => lang('javascript:deletingImageError'), '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();
        }


        $this->smarty->assign('totalUsers', $adminUser->totalContents);
        $this->smarty->assign('manager', $adminUser->user);
        $this->smarty->assign('action', $this->action);


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

        if ($this->permissions('managers')) {
            return $this->smarty->fetch('views/users/manager.tpl');
        }

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


}
