<?php

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

use App\Http\Controllers\Controller;
use App\Models\IamPrincipal;
use Exception;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use App\Services\APIs\CustomerAPIs\CustomerApiServices;
use Carbon\Carbon;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;

class CustomerControllerApi extends Controller
{
    protected $CustomerApiServices;

    public function __construct(CustomerApiServices $CustomerApiServices)
    {
        $this->CustomerApiServices = $CustomerApiServices;
    }

    /**
     * Created By : sayli Raut
     * Created at : 27 May 2024
     * Use : To get user profile detail.
     */
    public function getUserProfileDetail()
    {
        try {
            $token = readHeaderToken();

            if ($token) {
                $customerIamId = $token['sub'];
                $response = $this->CustomerApiServices->getUserProfileDetailService($customerIamId);
                return jsonResponseWithSuccessMessageApi(__('auth.data_fetched_successfully'), $response, 200);
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.user_deleted'), 409);
            }
        } catch (Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }


    /**
     * Created By : Sayli Raut
     * Created at : 27 May 2024
     * Use : To update user profile detail.
     */
    public function updateUserProfileDetail(Request $request)
    {
        try {
            $token = readHeaderToken();
            $email = $request->input('email_address');
            $existingEmails = IamPrincipal::where('email_address', $email)
                ->whereNull('deleted_at')
                ->get();

            if ($token) {
                $customerIamId = $token['sub'];
                $validator = Validator::make($request->all(), [
                    '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.');
                            }
                        },
                    ],
                    'email_address' => 'required|email',
                    'first_name' => 'required|string|min:2|max:100',
                    'last_name' => 'required|string|min:2|max:100',
                    'phone_number' => 'required|min:10|numeric',
                ]);

                if ($validator->fails()) {
                    return jsonResponseWithErrorMessage($validator->errors()->first(), 400);
                }

                $response = $this->CustomerApiServices->updateUserProfileDetailService($customerIamId, $request);
                return response()->json(['status' => 'success', 'message' => 'User profile updated successfully']);
            }
        } catch (\Exception $e) {
            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }


    /**
     * Created By : sayli Raut
     * Created at : 27 May 2024
     * Use : Reset Customer password .
     */
    public function resetUserPassword(Request $request)
    {
        try {
            $token = readHeaderToken();
            if ($token) {
                $customerIamId = $token['sub'];
                $validator = Validator::make($request->all(), [
                    'current_password' => 'required',
                    'new_password' => 'required|string|min:6',
                    'confirm_password' => 'required|same:new_password',
                ]);

                if ($validator->fails()) {
                    return jsonResponseWithErrorMessageApi($validator->errors()->first(), 400);
                }

                return $this->CustomerApiServices->resetUserPassword($customerIamId, $request);
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.user_deleted'), 409);
            }
        } catch (Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }

    /**
     * Created By : Sayli Raut
     * Created at : 27 May 2024
     * Use : Logout Customer Account .
     */


    public function customerLogout(Request $request)
    {
        try {
            $jwtToken = $request->header('access-token');
            if ($jwtToken) {
                $iamPrincipalId = $request->user()->id;
                $user = IamPrincipal::find($iamPrincipalId);
                $user->one_signal_player_id = null;
                $user->save();

                JWTAuth::invalidate($jwtToken);

                Session::forget('vendorToken');

                return jsonResponseWithSuccessMessageApi(__('auth.logout'), 200);
            } else {
                return jsonResponseWithErrorMessage(__('auth.invalid_token'), 401);
            }
        } catch (Exception $e) {
            Log::error('Account Logout failed: ' . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }


    /**
     * Created By : sayli Raut
     * Created at : 25 January 2024
     * Use : Delete Customer Account .
     */
    public function destroyAccount(Request $request)
    {
        try {
            $token = readHeaderToken();

            if ($token) {
                $iamPrincipalId = $token['sub'];
                $deleteUser = IamPrincipal::find($iamPrincipalId);
                $deleteUser->one_signal_player_id = null;
                $deleteUser->save();

                if (!$deleteUser) {
                    return jsonResponseWithErrorMessageApi(__('auth.user_not_found'), 404);
                }

                $deleteUser->delete();

                return jsonResponseWithSuccessMessageApi(__('auth.delete_user'), 200);
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.user_deleted'), 409);
            }
        } catch (\Exception $e) {
            Log::error('Account deletion failed: ' . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }
}
