<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Kreait\Firebase\JWT\Error\IdTokenVerificationFailed;
use Kreait\Firebase\JWT\IdTokenVerifier;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use App\Models\PasswordReset;
use Illuminate\Support\Str;
use Auth;
use App\Models\User;
use Hash;
use Log;
use Validator;

class AuthController extends Controller
{

	public function verifytoken(Request $request){
		return response()->json(auth('sanctum')->check());
	}

	// creating a new user
	public function register(Request $request){
		Log::info("enter to register organisation");

		$response = [
			'access_token'=>null,
			'user'=>null,
			'success' => false,
			'message' => '',
		];

		Log::info(json_encode($request));


		if($request['email']!=null && $request['email']!=''){

			// checking Existing User
			$check=User::where('email',$request['email'])->select('id','name','email','mobile_no');

			// checking Mobile No Exists or not
			if(isset($request['mobile_no'])){
				$check=$check->where('mobile_no',$request[ 'mobile_no']);
			}

			$check=$check->first();

			Log::info("register data");
			
			if($check==null){

				$obj['name']=$request['name'];
				$obj['password']=Hash::make($request['password']);
				$obj['c_password']=$request['password'];
				$obj['mobile_no']=$request['mobile_no'];
				$obj['email']=$request['email'];
				
				// Creating User
				$user = User::create($obj);

				// creating Access token  for the user.
				$accessToken = $user->createToken('my-app-token')->plainTextToken;

				//	Getting Created user from DB
				$user = User::where('id',$user['id'])->first();

				// Logged User
				Auth::login($user);

				// Generating Random Token for Email Verification
				$token = Str::random(60);

				// Updating Random Token to user table
				$user['email_token']=$token;
				$user->update();
	
				// Sending Email for Verification
				$data['email'] = $request['email'];
				$data['title'] = "Email Verification";
				$data['body'] = 'Welcome to the Accounting Software';
				$data['link']='https://devs-erp-accounts.vercel.app/verifymail/'.$token;
				Mail::send('mail.verifyMail', ['data' => $data], function ($message) use ($data) {
					$message->to($data['email'])->subject($data['title']);
				});
	
				$response = [
						'access_token'=>$accessToken,
						'user'=>$user,
						'success' => true,
						'message' => 'User Created Successfullly',
				];

			} else {

				// Email and Mobile Not exists
				$response = [
					'access_token'=>null,
					'user'=>$check,
					'success' => false,
					'message' => 'Email and Mobile No. Alreday Exist try login',
				];
			}
		}else{

			// Email is needed
			$response = [
				'access_token'=>null,
				'user'=>null,
				'success' => false,
				'message' => 'Email is needed',
				'redirect'=>''
			];
		}
        return response()->json($response);
    }


	// Function to verify email from email_token
	public function verifyMail(Request $request){

		//validate request data
		$validator = Validator::make($request->all(),[
			'token'=>'required'
		]);

		if ($validator->fails()) { 
			
			return response()->json($validator->errors()->first());

		} else {
			$user= User::where('email_token',$request['token'])->first();

			if($user!=null){
				$user['is_email_verified']=1;
				$user->save();

				$response=[
					'success'=>true,
					'message'=>'Email Verification Successful',
					'user'=>$user
				];

			} else {
				$response=[
					'success'=>false,
					'message'=>'Invalid Token'
				];
			}

			return response()->json($response);
		}
	}

	public function logout(Request $request){
		Auth::logout();
		return redirect('login');
	}
	
	public function loginwithemailpassword(Request $request){
		
		$response = [
			'access_token'=>null,
			'user'=>null,
			'success' => false,
			'message' => '',
			'redirect'=>'Email is needed'
		];
		$user=array();

		Log::info('Login Attempt');
		Log::info($request);

		if($request['email']!=null && $request['password']!=null){
			
			//check user exists in any organisation
			$user = User::where('email',$request['email'])
				// ->whereHas('user_organisation',function($query){
				// 	$query->where('is_disabled',0);
				// })
				->first();
		}
	
		if($user!=null){	
			if(Hash::check($request['password'], $user->password)){

				$accessToken = $user->createToken('my-app-token')->plainTextToken;

				Auth::login($user);
				$user = User::where('id',$user['id'])->first();
				$response = [
					'access_token'=>$accessToken,
					'user'=>$user,
					'success' => true,
					'message' => 'Login Successfull',
				];
				
			} else {
				$response = [
					'user'=>null,
					'success' => false,
					'message' => 'Password Incorrect',
				];
			}
		}else{
			$response = [
				'user'=>null,
				'success' => false,
				'message' => 'User Not exist',
			];
		}
		
		return response()->json($response);
	}

	public function loginwithfirebase(Request $request){
		$response = [
			'access_token'=>null,
			'user'=>null,
			'success' => false,
			'message' => 'Firebase token not found',
		];
		// $companyService = new CompanyService;
		Log::info("Enter in Firebase");
		$projectId = 'kwickloan-app';
		if(!isset($request['firebasetoken'])){
			Log::info("firebase token not found");
			$request1 = json_decode($request->getContent(),true);
			// $response['stage']='stage1';
			// $response['stage1']=$request1;
			if(isset($request1['firebasetoken'])){
				$request = $request1;
			}
		}
		Log::info("login Request data :".json_encode($request));
		if($request['firebasetoken']!=null) {
			Log::info("firebase token found in request");
			Log::info("firebase token:".$request['firebasetoken']);
			$verifier = IdTokenVerifier::createWithProjectId($projectId);
			//try {
			
			$token = $verifier->verifyIdToken($request['firebasetoken']);
			$uuid=$token->payload()['user_id'];
			$mobile=$token->payload()['phone_number'];
			$userMobile = UserMobile::where('firebaseuuid',$uuid)->first();
			$user = null;
			if($userMobile==null){
				//check the mobile no in the database
				Log::info("mobile(firebase) ==null:".$mobile);
				$userMobile = UserMobile::where('mobile',$mobile)
					->whereHas('user',function($query){
						return $query->where('iscustomer',1);
					})->first();
				if($userMobile==null){
					
					$response = [
						'access_token'=>null,
						'user'=>null,
						'success' => false,
						'message' => 'Mobile No. Not Exists',
					];
				} else {
					$userMobile['firebaseuuid']=$uuid;
					$userMobile->update();
					$user = User::where('id',$userMobile['userid'])->first();
					
				}
			} else {
				$user = User::where('id',$userMobile['userid'])->first();
			}
			if($user!=null){
				Auth::login($user);
				$user = User::where('id',$user['id'])->first();
				$accessToken = $user->createToken('my-app-token')->plainTextToken;

				$response = [
					'access_token'=>$accessToken,
					'user'=>$user,
					'success' => true,
					'message' => 'Successfully Login',
				];
			}
			
		}
		return response()->json($response);
	}

	public function changePassword(Request $request)
    {
		//validate request data
		$validator = Validator::make($request->all(),[
			'email'=>'required|email',
			'password'=>'required'
		]);

		if ($validator->fails()) { 
			
			return response()->json($validator->errors()->first());

		} else {
			// $email = $request->email;
			$user=Auth::user();

			if($user!=null){
				
				// dd($password);
				Log::info('New Password '.$request['password']);

				$uq = User::where('id', $user['id'])->first();
				$uq['password']=Hash::make($request['password']);
				$uq['c_password']=$request['password'];
				$uq->save();

				$user = User::where('id', $user['id'])->get();

				return response()->json([
					'status' => '200',
					'message' => 'Password Updated successfully',
					'user' => $user
				]);

			} else {
				return response()->json([
					'status' => '200',
					'message' => 'UnAuthorised Access to change password'
				]);

			}
		}
    
    }

	public function forgotPassword(Request $request){
		//validate request data
		Log::info('Forgot password Enter');
		$validator = Validator::make($request->all(),[
			'email'=>'required'
		]);

		if ($validator->fails()) { 
			Log::info('Validation Error');
			return [
				'success' => false, 
				'message' => $validator->errors()->first()
			];
		} else {

			$user=User::where("email",$request['email'])->first();

			if (!$user) {
				return [
					'success' => false, 
					'message' => 'Email Not Found'
				];
			}

			$email = $user->email;
			// $resetUrl = "reztup.com";
			$token = Str::random(60);
	
			$otp = rand(100000, 999999);
   
			$data['email'] = $email;
			$data['otp'] = $otp;
			$data['title'] = "Email Verification";
			$data['body'] = 'Your OTP is:- ' . $otp;
			Mail::send('mail.verifyOtp', ['data' => $data], function ($message) use ($data) {
				$message->to($data['email'])->subject($data['title']);
			});
	
			DB::table('password_resets')->insert([
				'email' => $user->email,
				'otp' => $otp,
				'token' => $token,
				'created_at' => now()
			]);

			return response()->json([
                'status' => '200',
				'message'=>'OTP Sent to an  Email Successfully'
			]);

		}
	}


	// Verify OTP sent  in email
	public function verifyOtp(Request $request){
        // return $request->all();

		$validator = Validator::make($request->all(), [	
			// 'token' => 'required|string',
			'email' => 'required|email',
			'otp' => 'required|numeric'
		]);

		if ($validator->fails()) { 
			return [
				'success' => false, 
				'message' => $validator->errors()->first()
			];
		} else {

			$otp =  $request->otp;
			$email= $request->email;

			$resetdata = PasswordReset::where('email',$email)->where('otp', $otp)
				->orderBy('id','desc')
				->first();

			if($resetdata!=null){

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

				$accessToken = $user->createToken('my-app-token')->plainTextToken;

				Auth::login($user);

				return response()->json([
					'status' => '200',
					'access_token'=>$accessToken,
					'user'=>$user,
					'success' => true,
					'message' => 'OTP Verified Successfully',
				]);

			}else{
				return response()->json([
					'status' => '404',
					'message' => 'Otp is not valid'
				]);
			}
		}
	}
}
