<?php


namespace App\Services\APIs\CustomerAPIs;

use Illuminate\Support\Facades\DB;
use App\Models\CustomerFavouriteRestaurant;
use App\Models\IamPrincipal;
use App\Models\IamPrincipalRestaurantRole;
use App\Models\ManageRestaurant;
use App\Models\RedeemRestaurant;
use App\Helpers\onesignalhelper;
use Exception;
use Illuminate\Support\Facades\Log;



class RestaurantApiServices
{
    public function getCoordinates($customerIamId)
    {
        try {
            $restaurants = ManageRestaurant::with('operatingHours')->select(
                'id',
                'name',
                'image',
                'address',
                'short_id',
                'latitude',
                'longtitude'
            )
                ->where('is_active', '1')
                ->get()
                ->toArray();

            foreach ($restaurants as &$restaurant) {
                $restaurant['image'] = ListingImageUrl('restaurant_images', $restaurant['image']);

                $isFavourite = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId)
                    ->where('restaurant_xid', $restaurant['id'])
                    ->exists();
                $restaurant['is_favourite'] = $isFavourite;
            }

            return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $restaurants, 200);
        } catch (Exception $ex) {
            Log::error('Restaurant Get service failed : ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }

    public function addToFavourite($customerIamId, $request)
    {
        try {
            DB::beginTransaction();

            $restaurant = ManageRestaurant::where('short_id', $request->id)->where('is_active', '1')->first();
            if (!$restaurant) {
                return jsonResponseWithErrorMessage(__('auth.restaurant_data_not_found'), 404);
            }

            $existingFavourite = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId)
                ->where('restaurant_xid', $restaurant->id)
                ->first();

            if ($existingFavourite) {
                return jsonResponseWithErrorMessage(__('auth.restaurant_already_favourite'), 409);
            }

            $favRestaurant = new CustomerFavouriteRestaurant();
            $favRestaurant->principal_xid = $customerIamId;
            $favRestaurant->restaurant_xid = $restaurant->id;
            $favRestaurant->save();

            DB::commit();

            return jsonResponseWithSuccessMessage(__('auth.data_updated_successfully'), 200);
        } catch (\Exception $ex) {
            DB::rollBack();
            Log::error('Favourite Restaurant service failed: ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }



    public function listFavRestaurant($customerIamId)
    {
        try {
            $list = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId)->get()->toArray();
            $customerFavouriteRestaurants = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId)
                ->pluck('restaurant_xid')
                ->toArray();

            $restaurants = ManageRestaurant::with('operatingHours')->where('is_active', '1')->whereIn('id', $customerFavouriteRestaurants)->get();

            foreach ($restaurants as &$res) {
                $res['image'] = ListingImageUrl('restaurant_images', $res['image']);
            }

            return jsonResponseWithSuccessMessage(__('auth.data_updated_successfully'), $restaurants, 200);
        } catch (Exception $ex) {
            Log::error('List of Favourite Restaurant service failed : ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }


    public function DetailRestaurant($customerIamId, $id)
    {
        try {
            $rest = ManageRestaurant::with('operatingHours')->select('id', 'short_id', 'name', 'description', 'restaurant_id', 'address', 'image', 'bio', 'try_on_1', 'try_on_2', 'try_on_3', 'try_on_4', 'exclusion', 'latitude', 'longtitude')->where('short_id', $id)->where('is_active', '1')->first();

            if ($rest) {
                $rest->image = ListingImageUrl('restaurant_images', $rest->image);

                $isFavourite = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId)
                    ->where('restaurant_xid', $rest->id)
                    ->exists();
                $rest->is_favourite = $isFavourite;

                $redeem = RedeemRestaurant::where('iam_principal_xid', $customerIamId)
                    ->where('manage_restaurants_xid', $rest->id)
                    ->where('is_redeem', "1")
                    ->first();

                if ($redeem) {
                    $rest->is_Redeemed = true;
                    $rest->redeem_date = \Carbon\Carbon::parse($redeem->redeem_date)->addHours(4)->toDateTimeString();
                } else {
                    $rest->is_Redeemed = false;
                    $rest->redeem_date = null;
                }
            }

            if (!$rest) {
                return jsonResponseWithErrorMessage(__('auth.restaurant_data_not_found'), 404);
            }

            return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $rest, 200);
        } catch (Exception $e) {
            Log::error("Error fetching restaurant data: " . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }

    public function removeFromFavourite($customerIamId, $request)
    {
        try {
            DB::beginTransaction();

            $restaurant = ManageRestaurant::where('short_id', $request->id)->where('is_active', '1')->first();
            if (!$restaurant) {
                return jsonResponseWithErrorMessage(__('auth.restaurant_data_not_found'), 404);
            }

            $existingFavourite = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId)
                ->where('restaurant_xid', $restaurant->id)
                ->first();
            if (!$existingFavourite) {
                return jsonResponseWithErrorMessage(__('auth.data_not_found'), 404);
            }
            if ($existingFavourite) {
                $existingFavourite->delete();
            }
            DB::commit();

            return jsonResponseWithSuccessMessage(__('auth.data_updated_successfully'), 200);
        } catch (\Exception $ex) {
            DB::rollBack();
            Log::error('Favourite Restaurant service failed: ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }


    public function searchFromFavourite($customerIamId, $request)
    {
        try {
            $customerFavouriteRestaurants = CustomerFavouriteRestaurant::where('principal_xid', $customerIamId)
                ->pluck('restaurant_xid')
                ->toArray();

            $restaurantsQuery = ManageRestaurant::with('operatingHours')
                ->where('is_active', '1')
                ->whereIn('id', $customerFavouriteRestaurants);

            $searchData = $request->input('search_data');

            if (!empty($searchData)) {
                $restaurantsQuery->where(function ($query) use ($searchData) {
                    $query->where('name', 'like', "%$searchData%")
                        ->orWhere('description', 'like', "%$searchData%")
                        ->orWhere('address', 'like', "%$searchData%");
                });
            }

            $restaurants = $restaurantsQuery->get();
            foreach ($restaurants as &$res) {
                $res['image'] = ListingImageUrl('restaurant_images', $res['image']);
            }


            return jsonResponseWithSuccessMessageApi(__('auth.restaurant_search'), $restaurants, 200);
        } catch (Exception $ex) {
            Log::error('Search from favourite restaurant service failed: ' . $ex->getMessage());
            return response()->json([
                'message' => __('auth.something_went_wrong')
            ], 500);
        }
    }


    public function redeemRestaurant($customerIamId, $request)
{
    try {
        $restaurantId = $request->id;

        $restaurant = ManageRestaurant::with('operatingHours')->where('short_id', $restaurantId)->first();

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

        // Check if the restaurant has already been redeemed
        $restaurantExist = RedeemRestaurant::where('manage_restaurants_xid', $restaurant->id)->where('iam_principal_xid', $customerIamId)
            ->where('is_redeem', 1)
            ->first();

        if ($restaurantExist) {
            return jsonResponseWithErrorMessageApi(__('auth.restaurant_already_redeemed'), 400);
        }

        // Check if there's an existing entry for the restaurant and update it
        $restexist = RedeemRestaurant::where('manage_restaurants_xid', $restaurant->id)->where('iam_principal_xid', $customerIamId)->first();
        if ($restexist) {
            $restexist->is_redeem = 1;
            $restexist->redeem_date = now();
            $restexist->is_redeemption_undone = 0;
            $restexist->redeemption_undone_date = null;
            $restexist->save();
            return jsonResponseWithSuccessMessageApi(__('success.restaurant_redeem'), $restexist, 200);
        }

        // Create a new redeem entry if it doesn't exist
        $redeemRestaurant = new RedeemRestaurant();
        $redeemRestaurant->iam_principal_xid = $customerIamId;
        $redeemRestaurant->manage_restaurants_xid = $restaurant->id;
        $redeemRestaurant->is_redeem = 1; // Redeem restaurant
        $redeemRestaurant->redeem_date = now();
        $redeemRestaurant->is_redeemption_undone = 0;
        $redeemRestaurant->redeemption_undone_date = null;
        $redeemRestaurant->save();



        $imagePath = ListingImageUrl('restaurant_images', $restaurant->image);

        $customerTitle = "Your Redemption was successful for " . $restaurant->name;
        $customerMessage = $restaurant->name . " Voucher Redeemed Successfully";
        $customerContentType = 'Voucher_Redemption';
        $customerImageUrl = $imagePath;

        $customerData = IamPrincipal::where('id', $customerIamId)->where('notification_status', 1)->where('principal_type_xid', 3)->first();
        $restaurants = IamPrincipalRestaurantRole::select('id', 'principal_xid')->where('restaurant_xid', $restaurant->id)->get();

        foreach ($restaurants as $restaurant) {
            $restUser = IamPrincipal::where('id', $restaurant->principal_xid)->where('notification_status', 1)->where('principal_type_xid', 4)->first();

            if ($restUser) {
                $restImagePath = ListingImageUrl('restaurant_images', $restaurant->image);
                $restTitle = "New redemption for " . $restaurant->name;
                $restMessage = $restaurant->name . " new voucher Redeemed Successfully";
                $restContent_type = 'Voucher_Redemption';
                $restImageUrl = $restImagePath;

                // Sending notification to restaurant
                $pushNotificationToRestaurant = onesignalhelper::restSendNotificationApi(
                    $restUser->one_signal_player_id,
                    $restTitle,
                    $restMessage,
                    $restContent_type,
                    $restImageUrl,
                    $id = null
                );
                onesignalhelper::StoreNotificationDetails($restUser->id, $restContent_type, $restTitle, $restImageUrl);
            }
        }

        if ($customerData) {
            // Sending notification to customer
            $pushNotificationToCustomer = onesignalhelper::sendNotificationApi(
                $customerData->one_signal_player_id,
                $customerTitle,
                $customerMessage,
                $customerContentType,
                $customerImageUrl,
                $id = null
            );

            onesignalhelper::StoreNotificationDetails($customerData->id, $customerContentType, $customerTitle, $customerImageUrl);
        }
        return jsonResponseWithSuccessMessageApi(__('success.restaurant_redeem'), $redeemRestaurant, 200);
    } catch (Exception $ex) {
        Log::error('Restaurant Redeem service failed: ' . $ex->getMessage());
        return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
    }
}

}
