<?php


namespace Mnv\Modules\User;

use Mnv\Core\Config;
use Mnv\Core\Feedback;
use Mnv\Core\Filesystem\FilesystemManager;
use Mnv\Core\Locale\I18N;
use Mnv\Core\Auth\Errors\AuthError;
use Mnv\Core\Auth\Exceptions\NotLoggedInException;
use Mnv\Core\Auth\Exceptions\InvalidPasswordException;
use Mnv\Core\Auth\Exceptions\TooManyRequestsException;


use Mnv\Core\Uploads\Uploader;
use Mnv\Modules\Payment\Click\Form\ClickGenerationForm;
use Mnv\Modules\Payment\Payme\Form\PayMeGenerationForm;
use Mnv\Modules\Payment\Apelsin\Form\ApelsinGenerationForm;

use PHPMailer\PHPMailer\PHPMailer;

class User
{

    public $response;
    public $htmlMail = false;
    public $errors = false;

    public function __construct() { }

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

        if (!empty($user)) {
            try {
                $userAuth->changeUserInfo($user);
                $this->response =  array(
                    'status'=> 200, 'type'=> 'success',
                    'message'=> I18N::locale("Ваши данные успешно изменены", "Password has been changed", "Password has been changed")
                );
            }  catch (NotLoggedInException $e) {
                $this->response =  array(
                    'status'=> 403, 'type'=> 'error',
                    'message'=> I18N::locale("Not logged in", "Not logged in", "Not logged in")
                );
            } catch (TooManyRequestsException $e) {
                $this->response =  [
                    'status'=> 403, 'type'=> 'error',
                    'message'=> I18N::locale("Слишком много запросов!", "Too many requests!", "Too many requests!")
                ];
            }
        } else {
            $this->response =  array(
                'status'=> 403, 'type'=> 'error',
                'message'=> I18N::locale("Отправленные данные пусты!", "Yuborilgan ma'lumotlar bo'sh!", "Sent data is empty!")
            );
        }
    }

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

        if (!empty($user) && !empty($user['oldPassword']) && !empty($user['newPassword'])) {
            try {
                $userAuth->changePassword($user['oldPassword'], $user['newPassword']);
                $this->response =  array('status'=> 200, 'type'=> 'success', 'redirect' => SITE_URL . '/user/',
                    'message'=> I18N::locale("Пароль успешно изменен", "Parol muvaffaqiyatli almashtirildi", "Password changed successfully")
                );
            }
            catch (NotLoggedInException $e) {
                $this->response =  array('status'=> 403, 'type'=> 'error',
                    'message'=> I18N::locale("Для того чтоб менять пароль необходимо авторизоваться", "Parolni o'zgartirish uchun siz tizimga kirishingiz kerak.", "In order to change the password, you must log in.")
                );
            }
            catch (InvalidPasswordException $e) {
                $this->response =  array('status'=> 403, 'type'=> 'error',
                    'message'=> I18N::locale("Неверный старый пароль", "Noto'g'ri eski parol", "Invalid old password")
                );
            }
            catch (TooManyRequestsException $e) {
                $this->response =  array('status'=> 403, 'type'=> 'error',
                    'message'=> I18N::locale("Слишком много запросов!", "Too many requests!", "Too many requests!")
                );
            } catch (AuthError $e) {
            }
        } else {
            $this->response =  array('status'=> 403, 'type'=> 'error',
                'message'=> I18N::locale("Отправленные данные пусты!", "Yuborilgan ma'lumotlar bo'sh!", "Sent data is empty!")
            );
        }
    }

    /** TODO: доработать */
    public function changePhoto()
    {
        global $userAuth;

        $filesystem = new FilesystemManager('/uploads', 'users');
//        $filesystem = new FilesystemManager('/uploads', 'users/'. $userAuth->id());

        if (!$filesystem->isDirectory($filesystem->realPath)) {
            if ($filesystem->makeDirectory($filesystem->realPath )) {
                /** directory large */
                $filesystem->makeDirectory($filesystem->realPath . '/large');
                /** directory medium */
                $filesystem->makeDirectory($filesystem->realPath . '/medium');
                /** directory small */
                $filesystem->makeDirectory($filesystem->realPath . '/small');
            }
        }
        if ($file = connect('user_images')->select('imageId, fileId')->where('userId', $userAuth->id())->get('array')) {
            if ($filesystem->deleteFiles([$file['fileId']])) {
                connect('user_images')->where('imageId', $file['imageId'])->where('userId', $userAuth->id())->delete();
                $this->response = array('status' => 200, 'message' => 'file deleted');
            } else {
                $this->response = array('status' => 500, 'message' => 'file not deleted');
            }
        }

        $link = '';
        $upload = new Uploader('', $filesystem->realPath, $filesystem->path, $userAuth->id());
        if ($upload->validate()) {
            if ($upload->upload()) {
                if (!empty($upload->response['fileId'])) {
                   connect('user_images')->insert(['userId' => $userAuth->id(), 'fileId' => $upload->response['fileId']]);
                    $link = $upload->getFileUrl($upload->response['fileId']);
                }
                $filesystem->response =  array('status'=> 200, 'type'=> 'success', 'message'=> I18N::locale("Изображение добавлено!", "Rasm qo'shildi!", "Image added!"), 'link' => GLOBAL_URL . $link);
            } else  {
                $filesystem->response = array('status' => 500, 'type'=> 'error', 'message' => I18N::locale("Изображение не добавлено попробуйте снова!", "Rasm qo'shilmagan yana urinib ko'ring!", "Image not added try again!"));
            }
        }

        response()->json($filesystem->response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => Config::getValue('charset')], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
        exit();
    }


    public function paymentAccount($user)
    {

        $feedback = new Feedback();
//        $feedback->telegram(Config::getValue('telegram_send'));
        if (!empty($user)) {
            if ($userObj = connect()->table('shop_orders')->select('id, packageId, userId, amount, userName, userFirstName, userLastName, userPhone, userEmail')->where('id', '=', $user['order_id'])->get()) {
                if ($userObj->userId == $user['userId']) {
                    if(connect()->table('shop_orders')->where('id', '=', $user['order_id'])->update(['payMethod' => $user['payment_method']])) {

                        $package = connect()->table('sections')->select('fileName')->where('sectionId', '=', $userObj->packageId)->get();

                        // TODO: платежные системы
                        $this->response['note'][] = 'Оплата за участие';
                        $this->response['status'] = 200;
                        $this->response['color'] = 'green';

                        if ($user['payment_method'] == 'payme') {
                            $payme = new PayMeGenerationForm();
                            $this->response['form'] = $payme->form($userObj->id, (int)$userObj->amount, $this->response['note']);
                        } else if ($user['payment_method'] == 'click') {
                            $click = new ClickGenerationForm();
                            $this->response['form'] = $click->form($userObj->id, $userObj->amount, $this->response['note'], $userObj->userPhone, $userObj->userEmail);
                        } else if ($user['payment_method'] == 'apelsin') {
                            $apelsin = new ApelsinGenerationForm();
                            $this->response['form'] = $apelsin->form($userObj->id, (int)$userObj->amount, $userObj->userId);
                        }
                        if ($getUser = connect()->table('users')->select('userId, fullName, phone, email, code')->where('userId', $userObj->userId)->get() ) {

                            $htmlBody = "<p> $getUser->fullName <br/> Поздравляем Вас с успешной регистрацией на сайте ". SITE_URL .
                                "<br/> Рады видеть Вас в сообществе. <br/>" .
                                "<br/> <b>Ваш логин</b>: " . $getUser->email . " <br/>" .
                                "<br/> <b>Ваш пароль</b>: " . $getUser->code . " <br/>" .
                                "<br/> Если возникнут какие-то вопросы, обращайтесь к нам по номеру " .Config::getValue('phone') . "или по почте " .Config::getValue('email') . ". <br>" .
                                "<br/> Команда Ishu.</p>";

                            // todo: отправку на почту
                            if (empty($feedback->errors) && $feedback->send($getUser->email, "", 'Регистрация на сайте', $htmlBody)) {
                                $this->response['answer'] = array('code' => 1, 'message' => $userObj->userName, 'type'=> 'success');
                            } else {
                                $this->response['answer'] = array('code' => 0, 'message' => $feedback->errors, 'type'=> 'error');
                            }
                        }
                    }
                }
            } else {
                $this->response = array('status' => 403, 'color'=> 'red',
                    'message'=> I18N::locale("Нет такого пользователя", "Yuborilgan ma'lumotlar bo'sh!", "Sent data is empty!")
                );
            }
        }
    }


    public function logout()
    {
        global $userAuth;

        $userAuth->logOutUser();
        if (!$userAuth->isLoggedIn()) {
            $this->response = array('status' => 200, 'type'=> 'success', 'message' => I18N::locale("До встречи!", "Ko'rishguncha!", "See you!"));
        }
    }

    /**
     * Отправка письма PHPMailer (smtp)
     *
     * @param $to
     * @param $companyName
     * @param $subject
     * @param $htmlBody
     * @param false $is_html
     * @return bool|string
     * @throws \Exception
     */
    public function sendToEmail($to, $companyName, $subject, $htmlBody, $is_html = false)
    {
        $mail = new PHPMailer();
        $mail->CharSet    = Config::getValue('charset');
        $mail->SMTPDebug  = 0;
        $mail->setFrom(Config::getValue('smtp_user'), $companyName);

        if (Config::getValue('mail_transport')) {
            $mail->isSMTP();
            $mail->SMTPAuth   = true;
            $mail->Timeout  = 10;
            $mail->Host       = Config::getValue('smtp_server');
            $mail->Port       = Config::getValue('smtp_port');
            $mail->SMTPSecure = Config::getValue('smtp_secure');
            $mail->SMTPKeepAlive = true;
            $mail->Username   = Config::getValue('smtp_user');
            $mail->Password   = Config::getValue('smtp_pass');

        } else {
            $mail->From   = Config::getValue('smtp_user');
            $mail->Sender = Config::getValue('smtp_user');
        }

        $mail->XMailer = "LS CMS";

        if ( $is_html ) {
            $mail->isHTML();
            $this->htmlMail = true;
        }

        $mail->addReplyTo(Config::getValue('smtp_user'));
        $mail->addAddress($to, $companyName);


        $mail->Subject = $subject;
        if ($this->htmlMail) {
            $mail->msgHTML($htmlBody);
        } else {
            $mail->Body = $htmlBody;
        }

        if(!$mail->send()) {
            $this->errors = $mail->ErrorInfo;
            $mail->clearAllRecipients();
            $mail->clearAttachments();
            return false;
        } else {
            $mail->clearAllRecipients();
            $mail->clearAttachments();
            return true;
        }
    }

    /**
     * Скрыть несколько симоволов в email
     * @param $email
     * @param int $minLength
     * @param int $maxLength
     * @param string $mask
     * @return string
     */
    public function maskEmail($email, $minLength = 3, $maxLength = 10, $mask = "***") {
        $atPos = strrpos($email, "@");
        $name = substr($email, 0, $atPos);
        $len = strlen($name);
        $domain = substr($email, $atPos);

        if (($len / 2) < $maxLength) $maxLength = ($len / 2);

        $shortenedEmail = (($len > $minLength) ? substr($name, 0, $maxLength) : "");
        return  "{$shortenedEmail}{$mask}{$domain}";
    }



//    function addAttachment($mail, $path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') {
//        $mail->addAttachment($path, $name, $encoding, $type, $disposition );
//    }
}