<?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 ManagerDeveloper
 * @package Mnv\Admin\Controllers
 */
class ManagerDeveloper extends AdminMnv
{

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

        $this->smarty->assign('activeItem', 'developers');
        $this->smarty->assign('title', "Разработчики");

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

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


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

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

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

            /** 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;
            }

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

            $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'];

            if (!empty($adminUser->userId)) {
                $adminUser->getOldDataUser($adminUser->userId);
                if (empty($adminUser->oldUser)) $this->errors['user_not_found'] = true;
            }

            if (!empty($adminUser->user['userType'])) {
                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::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;
//                        }
//                    }
            }

//            var_dump($adminUser->userId);

            $adminUser->edit(UserTypes::DEVELOPER);


            if (empty($this->errors) && $this->action == 'save') {
                redirect($this->adminUrl . "/developers?" . $this->buildQueryString(['page' => $this->page]));
            }

        }
         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->manager['userType'] == UserTypes::DEVELOPER) {
            return $this->smarty->fetch('views/users/developer.tpl');
        }

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


}
