<?php

namespace App\Services\APIs\CustomerAPIs;

use App\Models\IamAppAction;
use App\Models\IamPrincipal;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;
use App\Models\IamPrincipalOtp;
use App\Models\ManageState;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\QueryException;



use Exception;


class AuthServices
{

    public function checkAge($request)
    {
        try {
            $age = $request->input('age');
            if ($age == 'yes') {
                return jsonResponseWithSuccessMessage(__('auth.legally_21'), 200);
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.not_legally_21'), 403);
            }
        } catch (Exception $ex) {
            Log::error('Check age service failed : ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }

    public function viewstates()
    {
        try {
            $data = ManageState::select('id', 'name')->where('is_active', 1)->get()->toArray();
            return $data;
        } catch (Exception $ex) {
            Log::error('List sate Get service failed : ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }


    public function register($request)
    {
        try {
            DB::beginTransaction();

            do {
                $referral_code = \Str::random(10);
            } while (IamPrincipal::where('referral_code', $referral_code)->exists());

            $user = IamPrincipal::create([
                'one_signal_player_id' => $request->one_signal_player_id,
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'email_address' => $request->email_address,
                'password' => Hash::make($request->password),
                'principal_type_xid' => 3, // 3 for customer
                'principal_source_xid' => 2, // 2 for mobile
                'date_of_birth' => $request->date_of_birth,
                'phone_number' => $request->phone_number,
                'state_xid' => $request->state_xid,
                'referral_code' => $referral_code,
            ]);

            DB::commit();

            $token = auth()->login($user);

            $response = [
                'iam_principal_xid' => $user->id,
                'access_token' => $token,
                'token_type' => 'bearer',
            ];
            return jsonResponseWithSuccessMessage(__('auth.Customer_user_created'), $response, 200);
        } catch (QueryException $e) {
            DB::rollBack();
            Log::error('Customer Registration Failed ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 403);
        }
    }






    public function login($request)
    {
        try {
            $credentials = [
                'email_address' => $request->email_address,
                'password' => $request->password,
            ];

            $isDelete = IamPrincipal::where('email_address', $request->email_address)->where('principal_type_xid', 3)->where('deleted_by_admin', 1)->onlyTrashed()->first();
            if ($isDelete) {
                return jsonResponseWithErrorMessageApi(__('auth.deleted_user_by_admin'), 403);
            }
            $isExistEmail = IamPrincipal::where('email_address', $request->email_address)->where('principal_type_xid', 3)->whereNull('deleted_at')->first();
            if ($isExistEmail == null) {
                return jsonResponseWithErrorMessageApi(__('auth.incorrect_email'), 403);
            }
            if ($isExistEmail && !(Hash::check($request->password, $isExistEmail->password))) {
                Log::error('Entered Password is wrong.');
                return jsonResponseWithErrorMessageApi(__('auth.incorrect_password'), 403);
            }

            if (!$token = auth()->login($isExistEmail)) {
                Log::error('Customer Login Failed');
                return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 403);
            }

            $isExistEmail->one_signal_player_id = $request->one_signal_player_id;
            $isExistEmail->save();
            $response = [
                'iam_principal_xid' => $isExistEmail->id,
                'access_token' => $token,
            ];

            return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $response, 200);
        } catch (QueryException $e) {
            Log::error('Customer Login Failed ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 403);
        }
    }


    public function forgotPassword($request)
    {
        try {
            DB::beginTransaction();

            $user = IamPrincipal::where('email_address', $request->email_address)->where('principal_type_xid', 3)->whereNull('deleted_at')->first();
            if ($user == null) {
                Log::error('Email not exist');
                return jsonResponseWithErrorMessageApi(__('auth.incorrect_email'), 403);
            }

            $otp = generateOTP();

            IamPrincipalOTP::updateOrCreate(
                ['principal_xid' => $user->id],
                [
                    'otp_code' => $otp,
                    'otp_purpose' => 'forgot password',
                    'valid_till' => Carbon::now()->addMinutes(2),
                    'is_used' => 0,
                ]
            );

            $mail = Mail::send(
                'frontend.Mail.customer_forgot_password_mail',
                [
                    'user' => $user,
                    'otp_code' => $otp,
                    'valid_till' => Carbon::now()->addMinutes(2)
                ],
                function ($message) use ($user) {
                    $message->to($user->email_address);
                    $message->subject('One-Time Passcode Enclosed');
                }
            );


            DB::commit();
            Log::info('Customer Forgot Password otp sent successfully');

            $response = [
                'iam_principal_xid' => $user->id,
            ];


            return jsonResponseWithSuccessMessageApi(__('auth.otp_sent_successfully'), $response, 200);
        } catch (QueryException $e) {
            DB::rollBack();

            Log::error('Customer Forgot password Failed ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 403);
        }
    }


    public function verifyOTPForgotPassword($request)
    {
        try {
            DB::beginTransaction();
            $User = IamPrincipal::where('email_address', $request->email_address)->where('principal_type_xid', 3)->whereNull('deleted_at')->first();

            $iamPrincipal = IamPrincipalOTP::where('principal_xid', $User->id)->first();

            if (!$iamPrincipal) {
                Log::error('User not exist');
                return jsonResponseWithErrorMessageApi(__('auth.failed_to_verify_otp'), 403);
            }

            if ($iamPrincipal->otp_code !== $request->otp) {
                Log::error('Customer entered invalid otp');
                return jsonResponseWithErrorMessageApi(__('auth.invalid_otp'), 403);
            }

            if (Carbon::now()->gt($iamPrincipal->valid_till)) {

                Log::error('Customer otp Exipred');
                return jsonResponseWithErrorMessageApi(__('auth.otp_expired'), 403);
            }

            if ($iamPrincipal->is_used === 1) {
                Log::error('Customer otp Already used');
                return jsonResponseWithErrorMessageApi(__('auth.otp_already_used'), 403);
            }

            $iamPrincipal->is_used = 1;
            $iamPrincipal->save();
            DB::commit();
            $response = [
                'iam_principal_xid' => $User->id
            ];
            Log::info('Customer OTP verified successfully');
            return jsonResponseWithSuccessMessageApi(__('auth.otp_verified'), $response, 200);
        } catch (QueryException $e) {
            DB::rollBack();
            Log::error('Customer verify otp Failed ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 403);
        }
    }



    public function changePassword($request)
    {
        try {
            DB::beginTransaction();
            $User = IamPrincipal::find($request->iam_principal_xid);
            $User->password = Hash::make($request->password);
            $User->save();
            DB::commit();
            return jsonResponseWithSuccessMessageApi(__('auth.password_updated_successfully'));
        } catch (QueryException $e) {
            DB::rollBack();
            Log::error('Customer change password Failed ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 403);
        }
    }


    public function resendOtp($request)
    {
        try {
            DB::beginTransaction();
            $iamPrincipal = IamPrincipalOTP::where('principal_xid', $request->iam_principal_xid)->first();
            $user = IamPrincipal::where('id', $request->iam_principal_xid)->first();

            if (!$iamPrincipal) {
                return response()->json('OTP not found for this user.', 203);
            }

            $allowedResendInterval = Carbon::now()->subMinutes(2);

            if ($iamPrincipal->updated_at >= $allowedResendInterval) {

                return jsonResponseWithErrorMessageApi(__('auth.try_resend_otp'), 429);
            }

            $otp = generateOTP();

            $iamPrincipal->principal_xid = $request->iam_principal_xid;
            $iamPrincipal->otp_code = $otp;
            $iamPrincipal->otp_purpose = $request->otp_purpose;
            $iamPrincipal->valid_till = Carbon::now()->addMinutes(2);
            $iamPrincipal->is_used = 0;
            $iamPrincipal->save();



            $mail = Mail::send(
                'frontend.Mail.customer_forgot_password_mail',
                [
                    'user' => $user,
                    'otp_code' => $otp,
                    'valid_till' => Carbon::now()->addMinutes(2)
                ],
                function ($message) use ($user) {
                    $message->to($user->email_address);
                    $message->subject('Forgot Password Mail Page');
                }
            );


            DB::commit();

            $response = [
                'iam_principal_xid' => $iamPrincipal->principal_xid,
                'email_address' => $user->email_address

            ];

            return jsonResponseWithSuccessMessageApi(__('auth.otp_resend_sent_successfully'), $response, 200);
        } catch (QueryException $e) {
            DB::rollBack();
            Log::error('Resend otp Failed ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 403);
        }
    }

    public function searchState($request)
    {
        try {
            $searchQuery = $request->input('search_data');

            $query = ManageState::select('id', 'name')->where('is_active', 1);

            if ($searchQuery) {
                $query->where(function ($q) use ($searchQuery) {
                    $q->where('name', 'like', '%' . $searchQuery . '%');
                });
            }
            $restaurants = $query->get();
            return jsonResponseWithSuccessMessageApi(__('auth.data_fetched_successfully'), $restaurants, 200);
        } catch (\Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage());
            return response()->json(__('something_went_wrong'), 500);
        }
    }
}
