<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Jobs\CodeVerificationJob;
use App\User;
use App\Verification;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class ResetPasswordController extends Controller
{

    protected $view = 'web.members.password.';
    /**
     * Show forget password form way
     * @return Factory|View
     */
    public function forgetPasswordForm()
    {
        $title = strip_tags(__('users.forget_password'));
        return view($this->view.'forget_password_form', compact('title'));
    }

    /**
     * Check forget password way whether by phone or email
     * @param Request $request
     * @return array|bool|JsonResponse
     */
    public function sendForgetPasswordCode(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'email' => 'required|email|exists:users,email'
        ], [
            'email.exists' => __('auth.failed')
        ], [
            'email' => __('users.email')
        ]);
        if ($validation->fails()){
            return response()->json(['errors' => $validation->errors()->first()]);
        }

        $generateCode = $this->generateCode($request->email);

        if ($generateCode['errors']){
            return $generateCode;
        }

        session(['forgetPasswordEmail' => $request->email]);
        return response()->json(['url' => route('user.typeForgetPasswordCode')]);
    }

    public function typeForgetPasswordCode()
    {
        if (!session('forgetPasswordEmail')){
            return redirect()->route('home');
        }

        return view($this->view.'type_forget_password_code_form');
    }

    /**
     * Check code verification for new register or reset password
     * @param Request $request
     * @return JsonResponse
     */
    public function codeVerification(Request $request)
    {
        if (getCurrentLocale() == 'ar'){
            $code = array_reverse($request->code);
        } else {
            $code = $request->code;
        }
        $code = implode('',  $code);
        if (mb_strlen($code) < 4){
            return response()->json(['errors' => __('members.enter_full_code')]);
        }

        $verification = Verification::where('code', $code)->where('email', session('forgetPasswordEmail'))->first();
        if ($verification){
            session()->put(['code' => $code]);
            return response()->json(['url' => route('user.newPasswordForm')]);
        }
        return response()->json(['errors' => __('members.invalid_code')]);
    }

    /**
     * Show type new password form
     * @return Factory|View
     */
    public function newPasswordForm()
    {
        if (!session('forgetPasswordEmail')){
            return redirect()->route('home');
        }
        return view($this->view.'new_password_form');
    }

    /**
     * Reset password
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function resetPassword(Request $request)
    {
        $validation = Validator::make($request->all(),
            ['password' => 'required|confirmed',], //regex:/^(?=.*[a-zA-Z0-9])[a-zA-Z\d]{6,}$/
            ['password.regex' => __('users.password_regex')],
            ['password' => __('users.password')]);

        if ($validation->fails()){
            return response()->json(['errors' => $validation->errors()->first()]);
        }

        $code = session('code');
        $code = Verification::where('code', $code)->where('email', session('forgetPasswordEmail'))->first();

        if (!$code){
            return response()->json(['errors' => __('members.not_allowed_to_change_password')]);
        }


//        $user = $code->user()->withTrashed()->first();
        $user = $code->user()->where('status', 1)->first();

        if($user){
            $password = bcrypt($request->password);
            $user->update(['password' => $password]);
            $code->delete();
            Auth::login($user);
            session()->forget(['code', 'forgetPasswordEmail']);
            return response()->json(['url' => route('home')]);
        } else {
            session()->forget(['code', 'forgetPasswordEmail']);
            return response()->json(['errors' => __('members.account_disabled_by_admin')]);
        }
    }

    /**
     * Generate code
     * @param $email
     * @return array|bool
     */
    protected function generateCode($email)
    {
        $registerRoute = preg_match('/register/', Route::getCurrentRoute()->uri);

        if ($registerRoute){
            $type = 'register';
        } else {
            $type = 'password';
        }

        $user = User::where('status', 1)->where('email', $email)->first();

        if (!$user){
            return ['errors' => __('members.account_disabled_by_admin')];
        }

        $code = rand(1111,9999);
        if (count($user->verifications) > 0){
            $user->verifications->first()->delete();
        }

        Verification::create([
            'user_id' => $user->id,
            'email' => $email,
            'type' => $type,
            'code' => $code
        ]);

        $data = [
            'user' => $user->name,
            'email' => $user->email,
            'code' => $code,
        ];

        if ($type == 'register'){
            $data['title'] = 'Account Verification';
            $data['details'] = 'Verify Email';

        } else {
            $data['title'] = 'Forget password';
            $data['details'] = 'Reset password';
        }

        CodeVerificationJob::dispatch($data, 'web.members.emails.verification_email');

//        if ($request['active_way'] == 'phone'){
//            $message = 'عزيز العميل مرحبا بك في منصة عين المبدع، كود التفعيل الخاص بك هو ';
//            $message .= $code;
//            $phone = ltrim($user->phone, 0);
//            $sms = Sms::send($phone, $message);
//            if ($sms){
//                return true;
//            } else {
//                return  false;
//            }
//        }

        return ['errors' => false];
    }

}
