<?php

namespace App\Services\APIs\RestaurantService;

use App\Helpers\onesignalhelper;
use App\Models\admin\ManageVoucherModel;
use App\Models\IamPrincipal;
use App\Models\IamPrincipalRestaurantRole;
use App\Models\ManageRestaurant;
use App\Models\MyPassportVoucher;
use App\Models\RedeemRestaurant;
use Exception;
use Illuminate\Support\Facades\Log;

class RedeemApiService
{
    public function getRedemedData($restIamId)
    {
        try {
            $rest = IamPrincipal::findOrFail($restIamId);
            $data['user_detail'] = IamPrincipal::select('id', 'first_name', 'last_name', 'email_address', 'phone_number', 'date_of_birth')->find($rest->id);

            $restaurantRoles = IamPrincipalRestaurantRole::select('id', 'principal_xid', 'restaurant_xid', 'role')
                ->where('principal_xid', $rest->id)
                ->first();


            $restDetail = RedeemRestaurant::with([
                'customer:id,first_name,last_name,profile_photo',
                'restaurant:id,short_id,image,name'
            ])
                ->select('id', 'iam_principal_xid', 'manage_restaurants_xid', 'redeem_date', 'is_active', 'count')
                ->where('manage_restaurants_xid', $restaurantRoles->restaurant_xid)
                ->where('is_redeem', 1)
                ->get();

            foreach ($restDetail as $detail) {
                if ($detail->customer) {
                    $detail->customer->profile_photo = $detail->customer->profile_photo
                        ? ListingImageUrl('profile_image', $detail->customer->profile_photo)
                        : asset('public/assets/img/blankProfile.png');
                }

                if ($detail->restaurant) {
                    // Check if the image is already a URL
                    if (!filter_var($detail->restaurant->image, FILTER_VALIDATE_URL)) {
                        $detail->restaurant->image = ListingImageUrl('restaurant_images', $detail->restaurant->image);
                    } else {
                        // Fallback if the image is already a URL
                        $detail->restaurant->image = $detail->restaurant->image
                            ? $detail->restaurant->image
                            : asset('public/assets/img/blankProfile.png');
                    }
                }
            }

            $restDetailArray = $restDetail->toArray();



            $restundoresumptionDetail = RedeemRestaurant::with([
                'customer:id,first_name,last_name,profile_photo',
                'restaurant:id,short_id,image,name'
            ])
                ->select('id', 'iam_principal_xid', 'manage_restaurants_xid', 'redeem_date', 'is_active', 'count', 'redeemption_undone_date')
                ->where('manage_restaurants_xid', $restaurantRoles->restaurant_xid)
                ->where('is_redeemption_undone', 1)
                ->get();

            foreach ($restundoresumptionDetail as $detail) {
                if ($detail->customer) {
                    $detail->customer->profile_photo = $detail->customer->profile_photo
                        ? ListingImageUrl('profile_image', $detail->customer->profile_photo)
                        : asset('public/assets/img/blankProfile.png');
                }

                if ($detail->restaurant) {
                    // Check if the image is already a URL
                    if (!filter_var($detail->restaurant->image, FILTER_VALIDATE_URL)) {
                        $detail->restaurant->image = ListingImageUrl('restaurant_images', $detail->restaurant->image);
                    } else {
                        // Fallback if the image is already a URL
                        $detail->restaurant->image = $detail->restaurant->image
                            ? $detail->restaurant->image
                            : asset('public/assets/img/blankProfile.png');
                    }
                }
            }
            $restundoRedumption = $restundoresumptionDetail->toArray();


            $restaurantDetail = [
                'redeemed_vouchers' => $restDetailArray,
                'redemption_undone_vouchers' => $restundoRedumption,
            ];

            return jsonResponseWithSuccessMessageApi(__('auth.User_details_fetch'), $restaurantDetail, 200);
        } catch (Exception $ex) {
            Log::error('Redeem Restaurant Get data service failed: ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }





    public function undoRedemption($restIamId, $request)
    {
        try {
            $voucherDetail = RedeemRestaurant::where('id', $request->voucher_id)->first();
            $rest = ManageRestaurant::where('id', $voucherDetail->manage_restaurants_xid)->first();
            if ($voucherDetail) {
                $voucherDetail->update([
                    'is_redeem' => 0,
                    'redeem_date' => null,
                    'is_redeemption_undone' => 1,
                    'redeemption_undone_date' => now(),

                ]);
                $imagePath = ListingImageUrl('restaurant_images', $rest->image);
                $customerTitle = "Your voucher was successfully undo redemption for " . $rest->name;
                $customerMessage = $rest->name . " Voucher Undo Redemption Successfully";
                $customerContentType = 'Voucher_UndoRedemption';
                $customerImageUrl = $imagePath;
                $customerData = IamPrincipal::where('id', $voucherDetail->iam_principal_xid)->where('notification_status', 1)->where('principal_type_xid', 3)->first();
                if ($customerData) {
                    $pushNotificationToCustomer = onesignalhelper::sendNotificationApi(
                        $customerData->one_signal_player_id,
                        $customerTitle,
                        $customerMessage,
                        $customerContentType,
                        $customerImageUrl,
                        $id = null
                    );

                    onesignalhelper::StoreNotificationDetails($customerData->id, $customerContentType, $customerTitle, $customerImageUrl);
                }
                $restUser = IamPrincipal::where('id', $restIamId)->where('notification_status', 1)->where('principal_type_xid', 4)->first();
                if ($restUser) {
                    $restImagePath = ListingImageUrl('voucher_images', $rest->image);
                    $restTitle = "voucher Undo redemption successful for " . $rest->name;
                    $restMessage = $rest->image . " Voucher Undo Redemption Successfully";
                    $restContentType = 'Voucher_UndoRedemption';
                    $restImageUrl = $restImagePath;

                    $pushNotificationToCustomer = onesignalhelper::restSendNotificationApi(
                        $restUser->one_signal_player_id,
                        $restTitle,
                        $restMessage,
                        $restContentType,
                        $restImageUrl,
                        $id = null
                    );

                    onesignalhelper::StoreNotificationDetails($restUser->id, $restContentType, $restTitle, $restImageUrl);
                }
                return jsonResponseWithSuccessMessageApi(__('auth.data_updated_successfully'), 200);
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.voucher_not_found'), 404);
            }
        } catch (Exception $ex) {
            Log::error('Undo redumption service failed: ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }





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

            $rest = IamPrincipal::findOrFail($restIamId);
            $data['user_detail'] = IamPrincipal::select('id', 'first_name', 'last_name', 'email_address', 'phone_number', 'date_of_birth')->find($rest->id);

            $restaurantRoles = IamPrincipalRestaurantRole::select('id', 'principal_xid', 'restaurant_xid', 'role')
                ->where('principal_xid', $rest->id)
                ->first();

            $query = RedeemRestaurant::with([
                'customer:id,first_name,last_name,profile_photo',
                'restaurant:id,image,name'
            ])
            ->select('id', 'iam_principal_xid', 'manage_restaurants_xid', 'redeem_date', 'is_active', 'count')
            ->where('manage_restaurants_xid', $restaurantRoles->restaurant_xid)
            ->where('is_redeem', 1);

            if ($searchQuery) {
                $query->where(function ($q) use ($searchQuery) {
                    $q->where('id', $searchQuery)
                      ->orWhereHas('customer', function ($q) use ($searchQuery) {
                          $q->where('first_name', 'like', '%' . $searchQuery . '%')
                            ->orWhere('last_name', 'like', '%' . $searchQuery . '%');
                      })
                      ->orWhereDate('redeem_date', $searchQuery);
                });
            }



            $restDetail = $query->get();

            foreach ($restDetail as $detail) {
                if ($detail->customer) {
                    $detail->customer->profile_photo = $detail->customer->profile_photo
                        ? ListingImageUrl('profile_image', $detail->customer->profile_photo)
                        : asset('public/assets/img/blankProfile.png');
                }

                if ($detail->restaurant) {
                    if (!filter_var($detail->restaurant->image, FILTER_VALIDATE_URL)) {
                        $detail->restaurant->image = ListingImageUrl('restaurant_images', $detail->restaurant->image);
                    } else {
                        $detail->restaurant->image = $detail->restaurant->image
                            ? $detail->restaurant->image
                            : asset('public/assets/img/blankProfile.png');
                    }
                }
            }

            $restDetailArray = $restDetail->toArray();

            $queryUndo = RedeemRestaurant::with([
                'customer:id,first_name,last_name,profile_photo',
                'restaurant:id,image,name'
            ])
            ->select('id', 'iam_principal_xid', 'manage_restaurants_xid', 'redeem_date', 'is_active', 'count', 'redeemption_undone_date')
            ->where('manage_restaurants_xid', $restaurantRoles->restaurant_xid)
            ->where('is_redeemption_undone', 1);

            if ($searchQuery) {
                $queryUndo->where(function ($q) use ($searchQuery) {
                    $q->where('id', $searchQuery)
                      ->orWhereHas('customer', function ($q) use ($searchQuery) {
                          $q->where('first_name', 'like', '%' . $searchQuery . '%')
                            ->orWhere('last_name', 'like', '%' . $searchQuery . '%');
                      })
                      ->orWhereDate('redeemption_undone_date', $searchQuery);
                });
            }



            $restundoresumptionDetail = $queryUndo->get();

            foreach ($restundoresumptionDetail as $detail) {
                if ($detail->customer) {
                    $detail->customer->profile_photo = $detail->customer->profile_photo
                        ? ListingImageUrl('profile_image', $detail->customer->profile_photo)
                        : asset('public/assets/img/blankProfile.png');
                }

                if ($detail->restaurant) {
                    if (!filter_var($detail->restaurant->image, FILTER_VALIDATE_URL)) {
                        $detail->restaurant->image = ListingImageUrl('restaurant_images', $detail->restaurant->image);
                    } else {
                        $detail->restaurant->image = $detail->restaurant->image
                            ? $detail->restaurant->image
                            : asset('public/assets/img/blankProfile.png');
                    }
                }
            }
            $restundoRedumption = $restundoresumptionDetail->toArray();

            $restaurantDetail = [
                'redeemed_vouchers' => $restDetailArray,
                'redemption_undone_vouchers' => $restundoRedumption,
            ];

            return jsonResponseWithSuccessMessageApi(__('auth.User_details_fetch'), $restaurantDetail, 200);
        } catch (Exception $ex) {
            Log::error('Search voucher service failed: ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }

}
