<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Core\Validations\ValidateEmail;
use Mnv\Models\Users\UserFactory;
use Mnv\Models\Users\Exceptions\NoUserException;
use Mnv\Models\Users\UserTypes;

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

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

        /* Заголовок, название подключаемого шаблона */
        $this->smarty->assign('activeItem','subscribers');
        $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));

//        print_r($this->action);
//        $request = $this->request->only(array('id', 'user', 'action'));
//        print_r($request);
//        print_r($request['action']);

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

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

//          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;
            } elseif (! 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($this->errors)) {
                if ($siteUser->prepare($siteUser->user)) {
                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }
            }

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

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

        $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('subscribers')) {
            return $this->smarty->fetch('views/users/subscriber.tpl');
        }

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

    }


}




