<?php

namespace App\Services\APIs\RestaurantService;

use App\Models\IamPrincipal;
use App\Models\admin\ManageVoucherModel;
use App\Models\admin\Mana;
use App\Models\ManageRestaurant;
use App\Models\IamPrincipalRestaurantRole;

use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Hash;
use Throwable;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RestaurantApi_Service
{

    public function getRestProfileDetail($restIamId)
    {
        try {
            // Fetch user details
            $userDetail = IamPrincipal::select('id', 'first_name', 'last_name', 'email_address', 'phone_number', 'date_of_birth', 'profile_photo')
                ->findOrFail($restIamId);

            // Set profile photo
            if ($userDetail->profile_photo) {
                $userDetail->profile_photo = ListingImageUrl('profile_image', $userDetail->profile_photo);
            } else {
                $userDetail->profile_photo = asset('public/assets/img/blankProfile.png');
            }

            // Find restaurant roles associated with the user
            $restaurantRoles = IamPrincipalRestaurantRole::select('id', 'principal_xid', 'restaurant_xid', 'role')
                ->where('principal_xid', $userDetail->id)
                ->get();

            // $restaurantDetails = [];

            foreach ($restaurantRoles as $restaurantRole) {
                $restaurant = ManageRestaurant::select('id', 'name', 'description', 'restaurant_id', 'address', 'image', 'bio', 'try_on_1', 'phone_number', 'try_on_2', 'try_on_3', 'try_on_4', 'exclusion', 'latitude', 'longtitude', 'is_active', 'created_by', 'modified_by', 'deleted_at', 'created_at', 'updated_at')
                    ->where('id', $restaurantRole->restaurant_xid)
                    ->where('is_active', 1)
                    ->first();

                if ($restaurant) {
                    $restaurant->image = ListingImageUrl('restaurant_images', $restaurant->image);
                    $restaurant->description = strip_tags($restaurant->description);

                    // $restaurantDetails[] = $restaurant;
                }
            }

            // Construct response
            $response = [
                'user_detail' => $userDetail,
                'restaurant_details' => $restaurant,
            ];

            // Return JSON response with success message
            return jsonResponseWithSuccessMessageApi(__('auth.User_details_fetch'), $response, 200);
        } catch (Exception $ex) {
            // Log error and return error response
            Log::error('Restaurant Get data service failed : ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }




    public function updateRestaurantDetail($restIamId, $request)
    {
        try {
            DB::beginTransaction();
            $data = IamPrincipal::findOrFail($restIamId);
            if (!$data) {
                DB::rollBack();
                return jsonResponseWithErrorMessageApi(__('auth.user_not_found'), 404);
            }
            $restaurantRoles = IamPrincipalRestaurantRole::select('id', 'principal_xid', 'restaurant_xid', 'role')->where('principal_xid', $restIamId)->get();
            if ($restaurantRoles->isEmpty()) {
                DB::rollBack();
                return jsonResponseWithErrorMessageApi(__('auth.restaurant_data_not_found'), 404);
            }
            $restaurantRole = $restaurantRoles->first();
            $restaurant = ManageRestaurant::findOrFail($restaurantRole->restaurant_xid);
            if (!$restaurant) {
                DB::rollBack();
                return jsonResponseWithErrorMessageApi(__('error_message.restaurant_data_not_found'), 404);
            }

            $restaurant->update([
                'name' => $request['name'],
                'address' => $request['address'],
                'bio' => $request['bio'],
                'phone_number' => $request['phone_number'],
                'try_on_1' => $request['try_on_1'],
                'try_on_2' => $request['try_on_2'],
                'try_on_3' => $request['try_on_3'],
                'try_on_4' => $request['try_on_4'],

            ]);
            $restaurant->description = strip_tags($restaurant->description);

            DB::commit();
            return jsonResponseWithSuccessMessageApi(__('auth.data_updated_successfully'), $restaurant, 200);
        } catch (Exception $ex) {
            DB::rollBack();
            Log::error('Restaurant update profile service failed : ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }


    public function updateRestProfileDetail($restIamId, $request)
    {
        try {
            DB::beginTransaction();
            $data = IamPrincipal::select('id', 'first_name', 'last_name', 'email_address', 'phone_number', 'date_of_birth')->findOrFail($restIamId);
            if (!$data) {
                DB::rollBack();
                return jsonResponseWithErrorMessage(__('error_message.user_details_not_found'), 404);
            }

            if ($request->has('image')) {
                $image = $request->image;
                $tnormalImage = saveSingleImageWithoutCrop($image, 'profile_image', null);
                $data->update(['profile_photo' => $tnormalImage]);
                DB::commit();
            }
            if ($request->has('first_name')) {
                $data->first_name = $request->first_name;
                $data->save();
                DB::commit();
            }
            if ($request->has('last_name')) {
                $data->last_name = $request->last_name;
                $data->save();
                DB::commit();
            }
            if ($request->has('date_of_birth')) {
                $data->date_of_birth = $request->date_of_birth;
                $data->save();
                DB::commit();
            }
            if ($request->has('phone_number')) {
                $data->phone_number = $request->phone_number;
                $data->save();
                DB::commit();
            }

            if ($request->has('email_address')) {
                $email = $request->input('email_address');
                if ($email !== $data->email_address) {
                    $existingUser = IamPrincipal::where('email_address', $email)
                        ->where('id', '!=', $restIamId)
                        ->whereNull('deleted_at')
                        ->where('principal_type_xid', 4)
                        ->exists();

                    if ($existingUser) {
                        DB::rollBack();
                        return jsonResponseWithErrorMessageApi(__('auth.email_already_exist'), 400);
                    }
                }
            }
            // $data->update([
            //     'first_name' => $request['first_name'],
            //     'last_name' => $request['last_name'],
            //     'email_address' => $request['email_address'],
            //     'phone_number' => $request['phone_number'],
            //     'date_of_birth' => $request['date_of_birth'],
            // ]);
            $data->save();
            DB::commit();
            return jsonResponseWithSuccessMessageApi(__('auth.data_updated_successfully'), $data, 200);
        } catch (Exception $ex) {
            DB::rollBack();

            Log::error('Restaurant update profile service failed : ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }

    public function resetRestPassword($restIamId, $request)
    {
        try {
            DB::beginTransaction();
            $user = IamPrincipal::findOrFail($restIamId);
            if (!Hash::check($request->current_password, $user->password)) {
                DB::rollBack();
                return jsonResponseWithErrorMessageApi(__('auth.invalid_current_passsword'), 403);
            } else {
                $user->update([
                    'password' => Hash::make($request->new_password)
                ]);
                DB::commit();
                return jsonResponseWithSuccessMessageApi(__('auth.password_updated_successfully'), $user);
            }
        } catch (Exception $ex) {
            DB::rollBack();
            Log::error('Update password service failed : ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }
}
