<?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\Models\Users\UserFactory;
use Mnv\Models\Users\Exceptions\NoUserException;
use Mnv\Models\Users\Exceptions\NotUpdateUserException;
use Mnv\Models\Users\UserTypes;

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

    protected $subscribe;
    protected $accessLevels;
    protected $image;


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

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

        $this->smarty->assign('subscribes', lang('users:subscribes'));
        $this->smarty->assign('genders', lang('users:genders'));
        /** statuses */
        $this->smarty->assign('statuses', lang('users:statuses'));
        $this->smarty->assign('subscribes', array_slice(lang('users:subscribes'), 0));

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

        if ($this->action == 'add' || $this->action == 'edit') {
//            try {
                $siteUser->edit(UserTypes::CUSTOMER);
//                print_r($siteUser->user);
                if (isset($siteUser->user)) $siteUser->user['password'] = '';
//            } catch (NoUserException $e) {
//                $this->errors['user_not_found'] = true;
//            }
        } else if ($this->action == 'save' || $this->action == 'apply') {

            $siteUser->user['userType'] = UserTypes::CUSTOMER;
            $siteUser->user['verified'] = ($siteUser->user['status'] == 3) ? 0 : 1;
            if (empty($siteUser->user['loginName'])) $this->errors['login'] = true;
            if (!empty($siteUser->user['loginName']) && @!preg_match('^[0-9A-Za-z_]+$^', $siteUser->user['loginName'])) $this->errors['login_correct'] = true;

            if ($loginName = $siteUser->checkLogin($siteUser->user['loginName'])) {
                if ($loginName == $siteUser->user['loginName']) {
                    $this->errors['loginName'] = true;
                } else {
                    $siteUser->user['loginName'] = $loginName;
                }
            }

//                if (empty($users->user['fullName'])) $this->errors['firstName'] = true;
            if (empty($siteUser->user['firstName'])) $this->errors['firstName'] = true;
            if (empty($siteUser->user['lastName'])) $this->errors['lastName'] = true;

//            if (empty($siteUser->user['phone'])) $this->errors['phone'] = true;
            // if (!empty($siteUser->user['phone']) && @!preg_match('/^[0-9]{7,15}+$/', $siteUser->user['phone'])) $this->errors['phone_correct'] = true;

//            if (!empty($siteUser->user['phone']) && (
//                preg_match( '/\d?(\s?|-?|\+?|\.?)((\(\d{1,4}\))|(\d{1,3})|\s?)(\s?|-?|\.?)((\(\d{1,3}\))|(\d{1,3})|\s?)(\s?|-?|\.?)((\(\d{1,3}\))|(\d{1,3})|\s?)(\s?|-?|\.?)\d{3}(-|\.|\s)\d{4}/', $siteUser->user['phone'] )
//                || preg_match('/([0-9]{8,13})/', str_replace(' ', '', $siteUser->user->phone))
//                || ( preg_match('/^\+?\d+$/', $siteUser->user['phone']) && strlen($siteUser->user['phone']) >= 8 && strlen($siteUser->user['phone']) <= 13 ) )) $this->errors['phone_correct'] = true;
//

            if (empty($siteUser->user['email'])) {
                $this->errors['email1'] = true;
            } else if (!ValidateEmail::fromString($siteUser->user['email'])) {
                $this->errors['email_correct'] = true;
            }


            if ($email = $siteUser->checkEmailUser($siteUser->user['email'])) {
                if ($email == $siteUser->user['email']) {
                    $this->errors['email2'] = true;
                } else {
                    $siteUser->user['email'] = $email;
                }
            }

            if (empty($siteUser->userId) && empty($siteUser->user['password'])) $this->errors['password'] = true;

            if (!empty($image['fileId'])) $images['fileId'] = $image['fileId'];

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

//            try {
                $siteUser->edit(UserTypes::CUSTOMER);
                if (isset($siteUser->user)) $siteUser->user['password'] = '';
//            } catch (NoUserException $e) {
//                $this->errors['user_not_found'] = true;
//            }

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

        } else if ($this->action == 'deleteImage') {
            $result = $siteUser->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('user', $siteUser->user);

        /* Вывод сообщений или ошибок */
        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/user.tpl');
        }

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

    }


}




