<?php

namespace Mehrab\User\Http\Controllers\Auth;

use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\URL;
use Mehrab\RolePermission\Models\Permission;
use Mehrab\RolePermission\Models\Role;
use Mehrab\User\Helpers\SmsForgotPasswordMethod;
use Mehrab\User\Helpers\SmsVerifyMethod;
use App\Http\Controllers\Controller;
use Mehrab\User\Http\Requests\Auth\check_code_request;
use Mehrab\User\Http\Requests\Auth\check_exists_and_status_request;
use Mehrab\User\Http\Requests\Auth\forgot_password_check_code_request;
use Mehrab\User\Http\Requests\Auth\forgot_password_send_request;
use Mehrab\User\Http\Requests\Auth\login_request;
use Mehrab\User\Http\Requests\Auth\register_request;
use Mehrab\User\Http\Requests\Auth\sendLoginCodeRequest;
use Mehrab\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use SanjabVerify\Support\Facades\Verify;

class AuthController extends Controller
{

    public function __construct()
    {
        $middlewares=['logout','check_login'];
        if(isset(\request()->affiliate)){
            $middlewares[]="index";
        }
        $this->middleware('guest')->except($middlewares);
    }

    public function index()
    {

        $affiliate=false;
        if(isset(\request()->affiliate)){
            if(\auth()->check()){
                if(auth()->user()->hasRole(\Mamad\RolePermissions\Models\Role::ROLE_AFFILIATE)){
                    return redirect()->route("affiliate.index");
                }
                Auth::logout();
            }
              $affiliate=true;
        }
        return view('User::Front.auth',compact('affiliate'));
    }

    public function check_exists_and_status(check_exists_and_status_request $request)
    {
        $mobile = $request->mobile;

        $user = User::query()
            ->verifiedMobile($mobile)
            ->first();

        //in mpa component use session for auth forms placeholder but in spa component return mobile to json format
//        session()->put('mobile_session', $mobile);

        if ($user && $user instanceof User) {
            return response()->json([
                'message' => 'before registered and active account',
            ],'200');
        } else {
            return response()->json([
                'message' => 'not registered or not active account',
            ],'200');
        }

    }

    public function register(register_request $request)
    {
        $mobile = $request->mobile;

        $user = User::query()
            ->VerifiedMobile($mobile)
            ->first();

        if ($user && $user instanceof User) {
            return 'before registered and active account';
        } else {

            $userExistsButNotVerified = User::query()
                ->notVerifiedMobile($mobile)
                ->first();

            if ($userExistsButNotVerified &&
                $userExistsButNotVerified instanceof User
            ) {
                $userExistsButNotVerified->update([
                    'password' => Hash::make($request->password),
                ]);
                $status = 'registered before but not active';

            } else {
                $user=User::query()->create([
                    'mobile' => $mobile,
                    'password' => Hash::make($request->password),
                ]);
                if(isset($request->affiliate) && $request->affiliate=="true" && $user->hasPermissionTo(Permission::PERMISSION_USER)){
                    $user->syncRoles(\Mamad\RolePermissions\Models\Role::ROLE_AFFILIATE);
                }
                $status = 'never registered but now register first time';
            }

            $result = Verify::request($mobile, SmsVerifyMethod::class);

        }
        if ($result['success'] == 200) {
            return response()->json([
                'status' => 'send code successfully',
                'message' => 'کد با موفقیت ارسال شد'
            ],200);
        } else {
            return response()->json([
                'status' => 'error to send code',
                'message' => $result
            ],400);
        }

    }
    public function send_login_code(sendLoginCodeRequest $request)
    {
        $mobile = $request->mobile;

        $user = User::query()
            ->VerifiedMobile($mobile)
            ->first();

        if ($user && $user instanceof User) {
            $result = Verify::request($mobile, SmsVerifyMethod::class);
        }
        if ($result['success'] == 200) {
            return response()->json([
                'status' => 'send code successfully',
                'message' => 'کد با موفقیت ارسال شد'
            ],200);
        } else {
            return response()->json([
                'status' => 'error to send code',
                'message' => $result
            ],400);
        }

    }

    public function check_code(check_code_request $request)
    {
        $mobile = $request->mobile;

        $user = User::query()
            ->VerifiedMobile($mobile)
            ->first();

        if ($user && $user instanceof User) {
            return response()->json([
                'status' => 'failed',
                'message' => 'قبلا ثبت نام کرده اید'
            ],400);
        } else {

            $userExistsButNotVerified = User::query()
                ->notVerifiedMobile($mobile)
                ->first();

            if ($userExistsButNotVerified && $userExistsButNotVerified instanceof User) {

                $result = Verify::verify($mobile, $request->code);
                $status = 'working on verify code';
            } else {
                $result['success'] = false;
            }

            if ($result &&
                $result['success'] == true &&
                $userExistsButNotVerified &&
                $userExistsButNotVerified instanceof User
            ) {

                $userExistsButNotVerified->update([
                    'mobile_verified_at' => time(),
                ]);

                Auth::loginUsingId($userExistsButNotVerified->id);
//                Auth::login($userExistsButNotVerified);
//                Auth::logoutOtherDevices($user->password);
                Auth::user()->assignRole(Role::ROLE_USER);

                return response()->json([
                    'status' => 'success',
                    'message' => $result['message'],
                    'url' => URL::previous(),
                    'address' => null
                ],200);

            } else {
                return response()->json([
                    'status' => 'failed',
                    'message' => 'کد وارد شده صحیح نیست'
                ],400);
            }
        }
    }

    public function forgot_password_send(forgot_password_send_request $request)
    {
        $mobile = $request->mobile;

        $user = User::query()->VerifiedMobile($mobile)
            ->first();

        if ($user && $user instanceof User) {

            $result = Verify::request($mobile, SmsForgotPasswordMethod::class);

            if ($result['success'] == 200) {
                return response()->json([
                    'status' => 'success',
                    'message' => $result['message']
                ],200);
            } else {
                return response()->json([
                    'status' => 'failed',
                    'message' => $result['message']
                ],400);
            }

        } else {
            return response('before registered but account never active',400);
        }

    }

    public function forgot_password_check_code(forgot_password_check_code_request $request)
    {
        $mobile = $request->mobile;

        $user = User::query()->verifiedMobile($mobile)->first();

        if ($user && $user instanceof User) {

            if (Cache::get($mobile . 'forgetPass') == $request->code) {

                $user->update([
                    'password' => bcrypt($request->password),
                ]);

                Auth::login($user, true);

                Cache::forget($mobile . 'forgetPass');

                Auth::logoutOtherDevices($request->password);

                if (!$user->hasRole(Role::ROLE_USER)){ $url = route("admin.dashboard"); } else { $url = URL::previous();}

                return response()->json([
                    'status' => 'success',
                    'message' => 'رمز عبور تغییر یافت',
                    'url' => $url,
                    'address' => $user->address
                ],200);
            } else {
                return response()->json([
                    'status' => 'failed',
                    'message' => 'اطلاعات ورودی صحیح نیست'
                ],400);
            }
        } else {
            return response()->json([
                'status' => 'failed',
                'message' => 'دسترسی به این بخش ندارید'
            ],400);
        }

    }

    public function login_user(login_request $request)
    {
        $mobile = $request->mobile;

        $user = User::query()
            ->verifiedMobile($mobile)
            ->first();

        if (
            $user &&
            $user instanceof User
        ) {
            if(isset($request['password']) && !empty($request['password'])){
                $login = auth()->attempt([
                    'mobile' => $request['mobile'],
                    'password' => $request['password'],
                ]);
                if ($login){
                    Auth::login($user);


                    if (!$user->hasRole(\Mamad\RolePermissions\Models\Role::ROLE_USER)){ $url = route("admin.dashboard"); } else { $url = URL::previous();}


                    return response()->json([
                        'status' => 'success',
                        'message' => 'logged in',
                        'url' => $url,
                        'address' => $user->address
                    ],200);
                }else{
                    return response()->json([
                        'status' => 'failed',
                        'message' => 'the information entered is incorrect'
                    ],400);
                }
            } else{
                $result = Verify::verify($mobile, $request->code);
                if ($result["success"]==true){
                    Auth::login($user);


                    if (!$user->hasRole(Role::ROLE_USER)){ $url = route("admin.dashboard"); } else { $url = URL::previous();}

                    if(isset($request->affiliate) && $request->affiliate=="true" && $user->hasPermissionTo(Permission::PERMISSION_USER)){
                        $user->syncRoles(\Mamad\RolePermissions\Models\Role::ROLE_AFFILIATE);
                        $url = route("affiliate.index");

                    }

                    return response()->json([
                        'status' => 'success',
                        'message' => 'وارد شدید',
                        'url' => $url,
                        'address' => $user->address
                    ],200);
                }else{
                    return response()->json([
                        'status' => 'failed',
                        'message' => $result["message"]
                    ],400);
                }
            }


        }
    }

    public function logout()
    {
         Auth::logout() ;
        return redirect()->route('home') ;

    }

}
