<?php

namespace App\Http\Controllers\Admin\APIs\Customer_API;

use App\Http\Controllers\Controller;
use App\Services\APIs\CustomerAPIs\AuthServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use App\Models\IamPrincipalOtp;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\QueryException;
use App\Models\IamPrincipal;
use App\Models\ManageState;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;


class AuthController extends Controller
{

    protected $AuthServices;
    public function __construct(AuthServices $AuthServices)
    {
        $this->AuthServices = $AuthServices;
    }
    /**
     * Created By : sayli Raut
     * Created at : 24 May 2024
     * Use : To check customer age.
     */
    public function checkAge(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'age' => 'required|string'
            ]);

            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Login validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }

            return $this->AuthServices->checkAge($request);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Something went wrong.'], 500);
        }
    }

    /**
     * Created By : sayli Raut
     * Created at : 24 May 2024
     * Use : State Details.
     */
    public function viewstates()
    {
        try {
            $response = $this->AuthServices->viewstates();
            return jsonResponseWithSuccessMessageApi(__('success.data_fetched_successfully'), $response, 200);
        } catch (\Exception $e) {
            Log::error('FAW get data controller function failed: ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }

    /**
     * Created By : sayli Raut
     * Created at : 24 May 2024
     * Use : Customer Registration.
     */
    public function register(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'first_name' => 'required|string|min:2|max:100',
                'last_name' => 'required|string|min:2|max:100',
                'email_address' => [
                    'required',
                    'string',
                    'email',
                    'max:100',
                    Rule::unique('iam_principal')->where(function ($query) {
                        return $query->where('principal_type_xid', 3)->whereNull('deleted_at');
                    }),
                ],

                'password' => 'required|string|min:6',
                'confirm_password' => 'required|same:password',
                'date_of_birth' => [
                    'required',
                    'date',
                    function ($attribute, $value, $fail) {
                        $dob = Carbon::parse($value);
                        $age = $dob->age;
                        if ($age < 21) {
                            $fail('You must be at least 21 years old.');
                        }
                    },
                ],
                'phone_number' => 'required|min:10',
                // 'address_line1' => 'required|max:50',
                'state_xid' => 'required',

            ]);


            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Customer validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }
            return $this->AuthServices->register($request);
        } catch (QueryException $e) {
            Log::error('Customer Registration Failed ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 403);
        }
    }

    /**
     * Created By : sayli Raut
     * Created at : 24 May 2024
     * Use : Customer login.
     */
    public function login(Request $request)
    {

        try {
            $validator = Validator::make($request->all(), [
                'email_address' => 'required|string|email',
                'password' => 'required|string|min:6',
            ]);

            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Login validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }

            return $this->AuthServices->login($request);
        } catch (QueryException $e) {

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

    /**
     * Created By : sayli Raut
     * Created at : 24 May 2024
     * Use : forgot password.
     */
    public function forgotPassword(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'email_address' => [
                    'required',
                    'string',
                    'email',
                    function ($attribute, $value, $fail) {
                        $existingUser = IamPrincipal::where('email_address', $value)->where('principal_type_xid', 3)->whereNull('deleted_at')->exists();
                        if (!$existingUser) {
                            $fail('The selected email address is invalid.');
                        }
                    },
                ],
            ]);

            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Forgot password validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }
            return $this->AuthServices->forgotPassword($request);
        } catch (Exception $e) {
            Log::error('Customer Forgot Password OTP function failed: ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }


    /**
     * Created By : sayli Raut
     * Created at : 24 May 2024
     * Use : OTP verification.
     */
    public function verifyOTPForgotPassword(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'email_address' => [
                    'required',
                    'string',
                    'email',
                    function ($attribute, $value, $fail) {
                        $existingUser = IamPrincipal::where('email_address', $value)->where('principal_type_xid', 3)->whereNull('deleted_at')->exists();
                        if (!$existingUser) {
                            $fail('The selected email address is invalid.');
                        }
                    },
                ],
                'otp' => 'required',
            ]);

            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Forgot password validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }
            return $this->AuthServices->verifyOTPForgotPassword($request);
        } catch (Exception $e) {
            DB::rollBack();
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }

    /**
     * Created By : sayli Raut
     * Created at : 24 May 2024
     * Use : Change Password.
     */
    public function changePassword(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'iam_principal_xid' => 'required|exists:iam_principal,id',
                'password' => 'required|confirmed',
            ]);
            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Forgot password validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }
            return $this->AuthServices->changePassword($request);
        } catch (Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage());
            return response()->json(__('something_went_wrong'), 500);
        }
    }

    /**
     * Created By : sayli Raut
     * Created at : 24 May 2024
     * Use :  Resend OTP .
     */
    public function resendOtp(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'iam_principal_xid' => 'required|exists:iam_principal,id',
                'otp_purpose' => 'required'
            ]);

            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Forgot password validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }
            return $this->AuthServices->resendOtp($request);
        } catch (Exception $e) {

            DB::rollBack();
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage());
            return response()->json(__('something_went_wrong'), 500);
        }
    }

      /**
     * Created By : Sayli Raut
     * Created at : 19 June 2024
     * Use : Search State.
     */
    public function searchState(Request $request)
    {
        try {
            return $this->AuthServices->searchState($request);
        } catch (\Exception $ex) {
            Log::error("Login API Failed: " . $ex->getMessage());
            return jsonResponseWithErrorMessage(__('error_message.something_went_wrong'), 500);
        }
    }

}
