<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Str;
use App\Models\User;
use Carbon\Carbon;
use Session;

class AuthController extends Controller
{
    //To User Register...
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'mobile' => 'required',
            'password' => 'required',
            'classname_id' => 'required',
            'gender' => 'required',
        ]);

        if ($validator->fails()) {
        	return response(['errors'=>$validator->errors()->all()], 422);
        }

        $data = $request->all();
        $data['verify_code'] = rand(100000, 999999);
        $data['verify_expires_at'] = Carbon::now()->addMinutes(10);

        if(!User::where('mobile', $request->mobile)->first()){
            if($request->password == $request->password_confirmation){
                $data['password'] = Hash::make($request->password);
                if($newUser = User::create($data)){
                    $userRole = Role::where('name', 'user')->pluck('id');
                    $newUser->assignRole($userRole);

                    $user = User::where('mobile', $request->mobile)->with(['classData'])->first();
                    $accessToken = $user->createToken('Testpaper2022')->accessToken;

                    /*mobile send SMS*/
                    $contact = $request->mobile;
                    $text = 'Congratulations! Your Login OTP code is: '. $user->verify_code.' Send By WB SOFTWARES.Please do NOT share your OTP or PIN with others.';
                    $this->sendSMS($contact,$text);

                    /*user id Session*/
                    $id=$user->id;
                    Session::put('user_id',$id);
                
                    $data = [
                        'message' => 'রেজিস্ট্রেশন সফল হইয়েছে, দয়া করে নাম্বারটি ভেরিফাই করুন.',
                        'access_token' => $accessToken,
                        'userData' => $user,
                    ];
            
                    return response()->json($data);
                }else{
                    return response()->json([
                        'message'   =>  'দুঃখিত, কোনো একটি সমস্যা হইছে.!'
                    ], 500);
                }
            }
            else{
                return response()->json([
                    'message'   =>  'পাসওয়ার্ড এবং কন্ফার্ম পাসওয়ার্ড ম্যাচিং হয় নি.!'
                ], 500);
            }
        }else{
            return response()->json([
                'message'   =>  'নাম্বারটি অলরেডি ব্যবহার হয়ে গেছে.!'
            ], 500);
        }
    }

    //To User Login...
    public function login(Request $request)
    {
        $request->validate([
            'mobile' => 'required',
            'password' => 'required',
        ]);

        $user = User::where('mobile', $request->mobile)->first();
        if ($user) {
            if (Hash::check($request->password, $user->password)) {
                if($user->status == 1){
                    //To get role data...
                    $singleRoleData = Role::where('name', $user->role)->first();
                    $rolePermissionIds = DB::table("role_has_permissions")->where("role_has_permissions.role_id",$singleRoleData->id)
                        ->pluck('role_has_permissions.permission_id')
                        ->toArray();
                    $userPermissionData = Permission::whereIn('id', $rolePermissionIds)->get();

                    $accessToken = $user->createToken('SkinCare2023')->accessToken;
                    $data = [
                        'message' => 'Login successfully',
                        'access_token' => $accessToken,
                        'userData' => $user,
                        'userPermissionData' => $userPermissionData,
                    ];
                    return response()->json($data);
                }else{
                    return response()->json([
                        'message'   =>  'Sorry, You are not verified.!'
                    ], 500);
                }
                
            }else {
                return response()->json([
                    'message'   =>  'Sorry, Password not matching.!'
                ], 500);
            }
        }
        else {
            return response()->json([
                'message'   =>  'Sorry You are not registered.!'
            ], 500);
        }
    }

    //To Reset Password...
    public function resetPassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => ['required'],
        ]);

        if ($validator->fails()) {
        	return response(['errors'=>$validator->errors()->all()], 422);
        }

        $data = $request->all();
        $data['verify_code'] = rand(100000, 999999);
        $data['verify_expires_at'] = Carbon::now()->addMinutes(10);

        $mobileNumber = $request->mobile;
        $text = 'Congratulations! Your Login OTP code is: '.$data['verify_code'].' Send By WB SOFTWARES.Please do NOT share your OTP or PIN with others.';
        $this->sendSMS($mobileNumber,$text);

        $userData = User::where('mobile', $request->mobile)->first();
        if(isset($userData)){
            if($userData->update($data)){
                return response()->json([
                    'message'   =>  'OTP has sent to your mobile, Please verify your mobile.',
                    'verifyOtp'   =>  $userData->verify_code,
                    'mobile'   =>  $userData->mobile
                ], 201);
            }else{
                return response()->json([
                    'message'   =>  'The opt has been sent not again!.'
                ], 500);
            }
        }else{
            return response()->json([
                'message'   =>  'Sorry, You are not registered.!'
            ], 500);
        }
        
    }

    //To password update...
    public function updatePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => ['required'],
            'password' => ['required', 'confirmed']
        ]);

        if ($validator->fails()) {
        	return response(['errors'=>$validator->errors()->all()], 422);
        }

        $data = $request->all();
        if($request->password == $request->password_confirmation){
            $data['password'] = Hash::make($request->password);

            $user = User::where('mobile', $request->mobile)->first();
            if($user->update($data)){
                $data = [
                    'message' => 'Your password changed successfully, Please Login now.',
                    'userData' => $user,
                ];
        
                return response()->json($data);
            }else{
                return response()->json([
                    'message'   =>  'Sorry, Password not matching.!'
                ], 500);
            }
        }
        else{
            return response()->json([
				'message'   =>  'Sorry, Something is wrong.!'
			], 500);
        }
    }


    //To logout...
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return response()->json([
            'success' => true,
            'message' => 'Logout successfully done.'
        ]);
    }


    //To verify....
    public function verifyOtp(Request $request)
    {
        $verify_code_mas = User::where('verify_code', $request->verify_code)->first();

        if($verify_code_mas ){
            if( $verify_code_mas->verify_expires_at < (Carbon::now())){

                $verify_code_mas->verify_code = null;
                $verify_code_mas->verify_expires_at = null;
                $verify_code_mas->save();
              
                return response()->json([
                    'message'   =>  'OTP verfication timeout, Please resend OTP.!'
                ], 500);
            
            }else{

                $verify_code_mas->verify_code = null;
                $verify_code_mas->verify_expires_at = null;
                $verify_code_mas->status = 1;
                $verify_code_mas->save();
                return response()->json([
                    'message'   =>  'You are now verified, Please login.',
                ], 201);
            }
           
        }
         return response()->json([
                'message'   =>  'Sorry, OTP not matching.!'
            ], 500);
       
    }

    //To again resend otp...
    public function resendOtp(Request $request)
    {
        $user = User::where('mobile', $request->mobile)->first();
        $user->verify_code = rand(100000, 999999);
        $user->verify_expires_at = Carbon::now()->addMinutes(10);
        $user->save();

        /*mobile send SMS*/
        $text = 'Congratulations! Your Verify Opt. '. $user->verify_code;
        $this->sendSMS($user->mobile,$text);

        if($user){
            return response()->json([
                'message'   =>  'OTP has sent to you, Please verify.',
                'data'   =>  $user
            ], 201);
        }else{
            return response()->json([
                'message'   =>  'Sorry, You are not registered.!'
            ], 500);
        }

    }

    //To Send Verify SMS...
    public function sendSMS($contact, $text)
    {
    	$url = "https://mimsms.com.bd/smsAPI";
		$data = [
            "sendsms"=>"",
		    "apikey" => "XQn6pUiIdnzhNdcTviqiqdlCflEFaORu",
		    "apitoken" => "vNd71691398017",
		    "type" => "sms",
		    "from" => "8809601004746",
		    "to" => $contact,
		    "text" => $text,
		    "route" => 0,
		 ];

		 $ch = curl_init();
		 curl_setopt($ch, CURLOPT_URL, $url);
		 curl_setopt($ch, CURLOPT_POST, 1);
		 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		 $response = curl_exec($ch);
		 curl_close($ch);

		// Instead of returning the raw response, you can just return a success message or any other desired output
        if ($response === 'SUCCESS') {
            return response()->json(['message' => 'SMS sent successfully']);
        } else {
            return response()->json(['message' => 'Failed to send SMS'], 500);
        }
    }

    protected function guard()
    {
        return Auth::guard();
    }
}
