<?php

namespace Mnv\Modules\User;

use Mnv\Core\Config;
use Mnv\Core\Locale\I18N;
use Mnv\Core\Auth\Errors\AuthError;
use Mnv\Core\Auth\Exceptions\InvalidEmailException;
use Mnv\Core\Auth\Exceptions\InvalidPasswordException;
use Mnv\Core\Auth\Exceptions\TooManyRequestsException;
use Mnv\Core\Auth\Exceptions\UnknownUsernameException;
use Mnv\Core\Auth\Exceptions\ValidatePasswordException;
use Mnv\Core\Auth\Exceptions\EmailNotVerifiedException;
use Mnv\Core\Auth\Exceptions\AttemptCancelledException;
use Mnv\Core\Auth\Exceptions\DuplicateUsernameException;
use Mnv\Core\Auth\Exceptions\AmbiguousUsernameException;
use Mnv\Core\Auth\Exceptions\UserAlreadyExistsException;
use Mnv\Models\Users\UserTypes;


class Login extends User implements UserInterface
{

    public function __construct() {
        parent::__construct();
    }

    public function auth($user)
    {
        global $userAuth;

        if (!empty($user)) {
            if (isset($user['loginName'])) {
                $rememberDuration = (isset($user['remember']) && $user['remember'] == 1) ? (int)(60 * 60 * 24 * 365.25) : null;
                try {
                    if (isset($user['loginName'])) {
                        $userAuth->loginWithUsername($user['loginName'], $user['password'], $rememberDuration);
                        $this->response = array('status' => 200, 'color' => 'green',
                            'message' => I18N::locale("Добро пожаловать!", "Endi siz tizimga kirishingiz mumkin!", "Now you can authorize!")
                        );
                    } else {
                        $this->response = array('status' => 403, 'color' => 'red',
                            'message' => I18N::locale('Требуется ввести номер телефона', "Elektron pochta manzili yoki foydalanuvchi nomi talab qilinadi", 'Either email address or username required')
                        );
                    }

                    if ($userAuth->checkUser() && $userAuth->id()) {
                        $this->response = array('status' => 200, 'color' => 'green',
                            'message' => I18N::locale('Добро пожаловать!', 'Xush kelibsiz!', 'Welcome!')
                        );
                    }
                } catch (InvalidEmailException $e) {
                    $this->response = array('status' => 403, 'color' => 'red',
                        'message' => I18N::locale('Неправильный email адрес', "Noto'g'ri elektron pochta manzili", 'Wrong email address')
                    );
                } catch (UnknownUsernameException $e) {
                    $this->response = array('status' => 403, 'color' => 'red',
                        'message' => I18N::locale("Пользователь с таким номером телефона не зарегистрирован", "Ushbu telefon raqamiga ega foydalanuvchi ro'yxatdan o'tmagan", 'The user with this phone number is not registered')
                    );
                } catch (AmbiguousUsernameException $e) {
                    $this->response = array('status' => 403, 'color' => 'red',
                        'message' => I18N::locale("неоднозначное имя пользователя", "noaniq foydalanuvchi nomi", "ambiguous username")
                    );
                    return 'ambiguous username';
                } catch (InvalidPasswordException $e) {
                    $this->response = array(
                        'status' => 403, 'color' => 'red',
                        'message' => I18N::locale("Вы ввели не правильный пароль", "Siz noto'g'ri parolni kiritdingiz", 'You entered the wrong password')
                    );
                } catch (EmailNotVerifiedException $e) {
                    $this->response = array(
                        'status' => 403,
                        'color' => 'red',
                        'message' => I18N::locale('Email не подтвержден', 'Email tasdiqlanmagan', 'Email not verified')
                    );
                }
                    //                    catch (EmailNotPaidException $e) {
                    //                        $userObj = connect()->table('users')->select('userId, firstName, lastName, email, phone')->where('email', '=', $user['email'])->get();
                    //                        $orderObj = connect()->table('shop_orders')->select('id, userId, amount, userPhone, userName, userEmail')->where('userId', '=', $userObj->userId)->get();
                    //                        $this->response =  array(
                    //                            'status'=> 403,
                    //                            'code'   => 1,
                    //                            'color'=> 'red',
                    //                            'message'=> Language\SiteLanguage::langMessage("Не была призведена оплата", "Ne byla prizvedena oplata", "Payment has not been made"),
                    //                            'userId' => $userObj->userId,
                    //                            'orderId' => $orderObj->id
                    //                        );
                    //                    }
                catch (TooManyRequestsException $e) {
                    $this->response = array('status' => 403, 'color' => 'red',
                        'message' => I18N::locale("Слишком много запросов", "Juda ko'p so'rovlar", 'Too many requests')
                    );
                } catch (AuthError $e) {
                    $this->response = array('status' => 403, 'color' => 'red',
                        'message' => I18N::locale("Ошибка авторизации", "Avtorizatsiya xatosi", "Authorisation Error")
                    );
                } catch (AttemptCancelledException $e) {
                    $this->response = array('status' => 403, 'color' => 'red',
                        'message' => I18N::locale('Попытка отменена', 'Попытка отменена', 'Попытка отменена')
                    );
                }
            } else {
                $this->response =  array('status'=> 403, 'color'=> 'red',
                    'message'=> I18N::locale("Не верно настроенные данные обработки авторизации!", "Yuborilgan ma'lumotlar bo'sh!", "Sent data is empty!")
                );
            }
        } else {
            $this->response =  array('status'=> 403, 'color'=> 'red',
                'message'=> I18N::locale("Отправленные данные пусты!", "Yuborilgan ma'lumotlar bo'sh!", "Sent data is empty!")
            );
        }
    }

    public function registration($user)
    {
        global $userAuth;

        if (!empty($user)) {
            if (!empty($user['loginName'])) {
                try {
                    $callback = null;

                    $userAuth->registerWithUniqueUsername('loginName', $user, UserTypes::CUSTOMER, null, (int)Config::getValue('twoFactorAuth'), $callback);

                    $this->response = array('status' => 200, 'color'=> 'green',
                        'message' => I18N::locale('Добро пожаловать!', 'Xush kelibsiz!', 'Welcome!'),
                    );
                }  catch (InvalidEmailException $e) {
                    $this->response =  array('status'=> 403, 'color'=> 'red',
                        'message'=> I18N::locale('Неверный адрес электронной почты', 'Yaroqsiz elektron pochta manzili', 'Invalid email address')
                    );
                }
                catch (ValidatePasswordException $e) {
                    $this->response = array('status' => 403, 'color'=> 'red',
                        'message' => I18N::locale("Пароль не должен быть пустым или кол-во символов не должно быть меньше 3", "Siz noto'g'ri parolni kiritdingiz", 'You entered the wrong password')
                    );
                }
                catch (InvalidPasswordException $e) {
                    $this->response =  array('status'=> 403, 'color'=> 'red',
                        'message'=> I18N::locale("Неправильный пароль", "Yaroqsiz parol", "Invalid password")
                    );
                } catch (UserAlreadyExistsException $e) {
                    $this->response =  array('status'=> 403, 'color'=> 'red',
                        'message'=> I18N::locale('Пользователь уже существует', 'Foydalanuvchi allaqachon mavjud', 'User already exists')
                    );
                } catch (DuplicateUsernameException $e) {
                    $this->response =  array('status'=> 403, 'color'=> 'red',
                        'message'=> I18N::locale('Пользователь с таком логином уже существует', 'Bu loginga ega foydalanuvchi allaqachon mavjud', 'User with this login already exists')
                    );
                } catch (TooManyRequestsException $e) {
                    $this->response =  array('status'=> 403, 'color'=> 'red',
                        'message'=> I18N::locale('Слишком много запросов', 'Juda koʻp soʻrovlar', 'Too many requests')
                    );
                } catch (AuthError $e) {
                    $this->response =  array('status'=> 403, 'color'=> 'red', 'message'=> $e->getMessage());
                }
            } else {
                $this->response =  array('status'=> 403, 'color'=> 'red',
                    'message'=> I18N::locale('Поле email не должно быть пустым!', 'Elektron pochta maydoni bo\'sh bo\'lmasligi kerak!', 'The email field must not be empty!')
                );
            }
        } else {
            $this->response = array('status' => 403, 'color'=> 'red',
                'message'=> I18N::locale('Отправленные данные пусты!', 'Yuborilgan maʼlumotlar boʻsh!', 'Sent data is empty!')
            );
        }
    }
}