<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TblUserAuthenticate;
use App\Models\TblSubContractor;
use App\Mail\ForgotPassword;
use Illuminate\Support\Facades\Http;
use Auth;
use Mail;
use DB;

class AuthController extends Controller
{
    function login(Request $request)
    {
        $requestPostJson= json_decode(json_encode($request ->getContent()));
        $payload =[
            'P_OPERATION_NAME' => 'AUTHENTICATE_USER',
            'P_JSON'=>$requestPostJson,
        ];
        $login_response = DB::select("call USP_POST_USER_AUTHENTICATE_ACTIVITY(:P_OPERATION_NAME, :P_JSON, @ERRNO,@ERRMSG)", $payload);
        //return $login_response;
        if(!empty($login_response)){
            $login_response_decoded = json_decode($login_response[0]->JSON_VALUE, true);
            if($login_response_decoded['status'] == 'true'){
                $user_details = TblUserAuthenticate::where('USER_SYS_ID', $login_response_decoded['USER_SYS_ID'])->first();
                //return $user_details;
                $token = $user_details->createToken('lekauto')-> accessToken;
                //return $token;
                $response_data = [
                    'Token' => $token,
                    'UserId' => $login_response_decoded['USER_SYS_ID'],
                    'FirstName' => $login_response_decoded['FIRST_NAME'],
                    'status' => $login_response_decoded['status'],
                    'response' => $login_response_decoded['response'],
                    'InitialLogin' => $login_response_decoded['INITIAL_LOGIN'],
                    'TempLogin' => $login_response_decoded['TEMP_LOGIN'],
                    'SystemRoleId' => $login_response_decoded['SYSTEM_ROLE_ID'],
                    'SystemRoleCode' => null,
                    'SystemRoleName' => $login_response_decoded['SYSTEM_ROLE_NAME'],
                    'MobileNo' => $login_response_decoded['MOBILE_NO'],
                    'Secret_Id' => $login_response_decoded['SECRET_ID'],
                    'Hrms_Emp_Sys_Id' => $login_response_decoded['HRMS_EMP_SYS_ID'],
                    //'USER_NRIC_NUMBER' => $login_response_decoded['USER_NRIC_NUMBER'],
                    'OrgId' => $login_response_decoded['ORGANISATION_SYS_ID'],
                    
                    
                    
                    
                    
                ];
                return $response_data;
            }else{
                return $login_response_decoded;
            }
        }else{
            $response_data = [
                'status' => 'false',
                'response' => 'opps!! something went wrong',
            ];
            return $response_data;
        }
    }
//api-post-authenticate-user
   //post authenticate user
   function PostAuthenticateUser(Request $request) 
   {
       $requestPostJson= json_decode(json_encode($request ->getContent()));
       //CALL USP_POST_USER_AUTHENTICATE_ACTIVITY('AUTHENTICATE_USER', '[{"USER_NAME":"admin@sixthsense.com","PASSWORD":"Abc@1234"}]',@ERRNO,@ERRMSG);

       $payload =[
           'P_OPERATION_NAME' => 'AUTHENTICATE_USER',
           'P_JSON'=>$requestPostJson,
       ];
       $response = DB::select("call USP_POST_USER_AUTHENTICATE_ACTIVITY(:P_OPERATION_NAME, :P_JSON, @ERRNO,@ERRMSG)", $payload);
       if(!empty($response))
       {
           $response_decoded = json_decode($response[0]->JSON_VALUE, true);
           return $response_decoded;
       }
       else
       {
           $response_data = [ 'status' => 'false', 'response' => 'opps!! something went wrong',];
           return $response_data;
       }
   }

   function subContractorLogin(Request $request)
    {
        $requestPostJson= json_decode(json_encode($request ->getContent()));
        $payload =[
            'P_OPERATION_NAME' => 'AUTHENTICATE_SUB_CONTRACTOR',
            'P_JSON'=>$requestPostJson,
        ];
        $login_response = DB::select("call USP_POST_SUB_CONTRACTOR_AUTHENTICATE_ACTIVITY(:P_OPERATION_NAME, :P_JSON, @ERRNO,@ERRMSG)", $payload);
        // return $login_response;
        if(!empty($login_response)){
            $login_response_decoded = json_decode($login_response[0]->JSON_VALUE, true);
            if($login_response_decoded['status'] == 'true'){
                $user_details = TblSubContractor::where('SUB_CONTRACTOR_SYS_ID', $login_response_decoded['SUB_CONTRACTOR_SYS_ID'])->first();
                $token = $user_details->createToken('lekauto')-> accessToken;
                $response_data = [
                    'Token' => $token,
                    'Uen' => $login_response_decoded['UEN'],
                    'Rebate' => $login_response_decoded['REBATE'],
                    'status' => $login_response_decoded['status'],
                    'Address' => $login_response_decoded['ADDRESS'],
                    'Country' => $login_response_decoded['COUNTRY'],
                    'response' => $login_response_decoded['response'],
                    'PostCode' => $login_response_decoded['POST_CODE'],
                    'UserName' => $login_response_decoded['USER_NAME'],
                    'IsCreated' => $login_response_decoded['IS_CREATED'],
                    'CompanyName' => $login_response_decoded['COMPANY_NAME'],
                    'UserId' => $login_response_decoded['SUB_CONTRACTOR_SYS_ID'],
                    'FirstName' => $login_response_decoded['COMPANY_NAME'],
                    //'status' => $login_response_decoded['status'],
                    //'response' => $login_response_decoded['response']
                    
                    
                ];
                return $response_data;
            }else{
                return $login_response_decoded;
            }
        }else{
            $response_data = [
                'status' => 'false',
                'response' => 'opps!! something went wrong',
            ];
            return $response_data;
        }
    }
   //api-post-authenticate-sub-contractor
   //post authenticate sub contractor
   function PostAuthenticateSubContractor(Request $request)
    {
        //CALL USP_POST_SUB_CONTRACTOR_AUTHENTICATE_ACTIVITY('AUTHENTICATE_SUB_CONTRACTOR', '[{"USER_NAME":"tonytan@yopmail.com","PASSWORD":"12345"}]',@ERRNO,@ERRMSG);
        $requestPostJson= json_decode(json_encode($request ->getContent()));
        $payload =[
            'P_OPERATION_NAME' => 'AUTHENTICATE_SUB_CONTRACTOR',
            'P_JSON'=>$requestPostJson,
        ];
        $login_response = DB::select("call USP_POST_SUB_CONTRACTOR_AUTHENTICATE_ACTIVITY(:P_OPERATION_NAME, :P_JSON, @ERRNO,@ERRMSG)", $payload);
        //return $login_response;
        if(!empty($login_response)){
           
            $login_response_decoded = json_decode($login_response[0]->JSON_VALUE, true);
            if($login_response_decoded['status'] == 'true'){
                $user_details = TblUserAuthenticate::where('USER_SYS_ID', $login_response_decoded['SUB_CONTRACTOR_SYS_ID'])->first();
                //return $user_details;
                $token = $user_details->createToken('lekauto')-> accessToken;
                //return $token;
                $response_data = [
                    'Token' => $token,
                    'Uen' => $login_response_decoded['UEN'],
                    'Rebate' => $login_response_decoded['REBATE'],
                    'status' => $login_response_decoded['status'],
                    'Address' => $login_response_decoded['ADDRESS'],
                    'Country' => $login_response_decoded['COUNTRY'],
                    'response' => $login_response_decoded['response'],
                    'PostCode' => $login_response_decoded['POST_CODE'],
                    'UserName' => $login_response_decoded['USER_NAME'],
                    'IsCreated' => $login_response_decoded['IS_CREATED'],
                    'CompanyName' => $login_response_decoded['COMPANY_NAME'],
                    'SubContractorSysId' => $login_response_decoded['SUB_CONTRACTOR_SYS_ID'],
                    
                    
                   
                        
                ];
                return $response_data;
            }else{
                return $login_response_decoded;
            }
        }else{
            $response_data = [
                'status' => 'false',
                'response' => 'opps!! something went wrong',
            ];
            return $response_data;
        }
    }
    
   //api-post-change-password
    //Change Password app
    function PostChangePassword(Request $request)
    {
        $requestPostJson= json_decode(json_encode($request ->getContent()));
        //CALL USP_POST_USER_AUTHENTICATE_ACTIVITY('CHANGE_PASSWORD', '[{"ITEM":"USER_CHANGE_PASSWORD","USER_SYS_ID":"127","REPEAT_PASS":"0000000","NEW_PASSWORD":"80129358"}]',@ERRNO,@ERRMSG);
        $payload =[
            'P_OPERATION_NAME' => 'CHANGE_PASSWORD',
            'P_JSON'=>$requestPostJson,
        ];
        $response = DB::select("call USP_POST_USER_AUTHENTICATE_ACTIVITY(:P_OPERATION_NAME, :P_JSON, @ERRNO,@ERRMSG)", $payload);
        if(!empty($response)){
            $response_decoded = json_decode($response[0]->JSON_VALUE, true);
            return $response_decoded;
        }
        else{
            $response_data = [
                'status' => 'false',
                'response' => 'opps!! something went wrong',
            ];
            return $response_data;
        }
    }


    public function subContractorForgotPassword(Request $request)
    {
        $mailPayload =[
            'P_OPERATION_NAME' => 'VIEW_EMAIL_CONFIG_DETAILS',
            'P_ITEM' => 'MAIL_CONFIG',
            'P_TEMPLATE' => 'FORGOT_PASSWORD',
            'P_JSON'=>'{"USER_SYS_ID":'.$request->USER_SYS_ID.'}'
        ];
        $mailResponse = DB::select("call USP_GET_MAIL_TEMPLATE_ACTIVITY(:P_OPERATION_NAME, :P_ITEM, :P_TEMPLATE, :P_JSON, @ERRNO,@ERRMSG)", $mailPayload);
        $mailResponseDecoded = json_decode($mailResponse[0]->JSON_VALUE, true);
        $emailData = $mailResponseDecoded['response'][0];
        if ($emailData) {
            $email = trim($emailData["TO_EMAIL"]);
            Mail::to($email)->queue(new ForgotPassword($emailData));
        }
        return [ 'status' => 'true', 'response' => 'Mail sent successfully.',];
    }

    public function mapDirections(Request $request)
    {
        $request->validate([
            'origin' => 'required|string',
            'destination' => 'required|string',
        ]);
        $apiKey = config('services.google_maps.api_key');
        $response = Http::get('https://maps.googleapis.com/maps/api/directions/json', [
            'origin' => $request->origin,
            'destination' => $request->destination,
            'mode' => 'travelMode',
            'key' => $apiKey,
        ]);

        if ($response->successful()) {
            $directions = $response->json();
            return response()->json($directions);
        } else {
            return response()->json(['error' => 'Unable to fetch directions'], 500);
        }
        return $request;
    }
    //api-post-user-verification
    //user-verification
    function PostUserVerification(Request $request) 
    {
        $requestPostJson= json_decode(json_encode($request ->getContent()));
        // CALL USP_POST_USER_AUTHENTICATE_ACTIVITY('USER_VERIFICATION', '[{"ITEM":"EMAIL_VERIFICATION","USER_NAME":"Xiaoqi@9creation.com.sg"}]',@ERRNO,@ERRMSG);
        $payload =[
            'P_OPERATION_NAME' => 'USER_VERIFICATION',
            'P_JSON'=>$requestPostJson,
        ];
        $response = DB::select("call USP_POST_USER_AUTHENTICATE_ACTIVITY(:P_OPERATION_NAME, :P_JSON, @ERRNO,@ERRMSG)", $payload);
        if(!empty($response))
        {
            $response_decoded = json_decode($response[0]->JSON_VALUE, true);
            if($response_decoded['status'] == 'true'){
                if($request[0]['ITEM'] == 'EMAIL_VERIFICATION'){
                    $userSysIdData = $response_decoded['USER_SYS_ID'];
                    if ($userSysIdData) {
                        $mailPayload =[
                            'P_OPERATION_NAME' => 'VIEW_EMAIL_CONFIG_DETAILS',
                            'P_ITEM' => 'MAIL_CONFIG',
                            'P_TEMPLATE' => 'FORGOT_PASSWORD',
                            'P_JSON'=>'{"USER_SYS_ID":'.$userSysIdData.'}'
                        ];
                        $mailResponse = DB::select("call USP_GET_MAIL_TEMPLATE_ACTIVITY(:P_OPERATION_NAME, :P_ITEM, :P_TEMPLATE, :P_JSON, @ERRNO,@ERRMSG)", $mailPayload);
                        //return $mailResponse;
                        $mailResponseDecoded = json_decode($mailResponse[0]->JSON_VALUE, true);
                        $resStatus = $mailResponseDecoded['status'];
                        if($resStatus == 'true'){
                            $emailData = $mailResponseDecoded['response'][0];
                            if ($emailData) {
                                $email = trim($emailData["TO_EMAIL"]);
                                Mail::to($email)->queue(new ForgotPassword($emailData));
                            }
                        }
                    }
                }
            }
            return $response_decoded;
        }
        else
        {
            $response_data = [ 'status' => 'false', 'response' => 'opps!! something went wrong',];
            return $response_data;
        }
    }

    //api-post-change-password-using-otp
    //change-password-using-otp
    function PostChangePasswordUsingOtp(Request $request) 
    {
        $requestPostJson= json_decode(json_encode($request ->getContent()));
        // CALL USP_POST_USER_AUTHENTICATE_ACTIVITY('CHANGE_PASSWORD_OTP', '[{"USER_SYS_ID":"127","ITEM":"CHANGE_PASSWORD_OTP","NEW_PASSWORD":"Abc@1234"}]',@ERRNO,@ERRMSG);
        $payload =[
            'P_OPERATION_NAME' => 'CHANGE_PASSWORD_OTP',
            'P_JSON'=>$requestPostJson,
        ];
        $response = DB::select("call USP_POST_USER_AUTHENTICATE_ACTIVITY(:P_OPERATION_NAME, :P_JSON, @ERRNO,@ERRMSG)", $payload);
        if(!empty($response))
        {
            $response_decoded = json_decode($response[0]->JSON_VALUE, true);
            return $response_decoded;
        }
        else
        {
            $response_data = [ 'status' => 'false', 'response' => 'opps!! something went wrong',];
            return $response_data;
        }
    }
}
