Sh3ll
OdayForums


Server : Apache
System : Linux 145.162.205.92.host.secureserver.net 5.14.0-611.45.1.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Apr 1 05:56:53 EDT 2026 x86_64
User : tradze ( 1001)
PHP Version : 8.1.34
Disable Function : NONE
Directory :  /home/tradze/public_html/app/Modules/Schedules/Http/Controllers/Frontend/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/tradze/public_html/app/Modules/Schedules/Http/Controllers/Frontend/BookingsController.php
<?php

namespace App\Modules\Schedules\Http\Controllers\Frontend;

use App\Http\Controllers\SiteController;
use App\Modules\Banners\Repositories\BannersRepo;
use App\Modules\Schedules\Repositories\BookingClass;
use App\Modules\Schedules\Models\TherapistBooking;
use App\Modules\Services\Models\ServiceDuration;
use App\Modules\Services\Models\SalonServiceDuration;
use App\Modules\Services\Models\ServiceType;
use App\Modules\Postcodes\Models\Postcode;
use App\User;
use App\Modules\Schedules\Models\BasketTherapist;
use App\Modules\Schedules\Models\BookingOrder;
use Spatie\Permission\Models\Role;
use Carbon\Carbon;
use GoogleMaps\GoogleMaps;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Modules\Users\Models\UserCoverageArea;
use App\Modules\Users\Models\UserProfile;
use App\Modules\Users\Models\UserServiceDuration;
use App\Modules\Users\Models\UserWorkingDay;
use Illuminate\Support\Facades\Auth;
use App\Modules\Services\Models\SalonCategory;
use App\Modules\Schedules\Models\SalonCart;
use App\Modules\Schedules\Models\SalonContact;
use App\Modules\Notifications\Facades\NotifRepository;
use App\Modules\Users\Models\BookRequest;
use GuzzleHttp\Client;

class BookingsController extends SiteController
{

    /**
     * The book repository instance
     *
     * @var BookingRepository
     */
    protected $book;
    protected $booking_min_requirements = [];
    protected $defaultServiceDuration = null;

    /**
     * Create a new controller instance.
     */
    public function __construct(BannersRepo $banners, BookingClass $book)
    {
        parent::__construct($banners);
        $this->book = $book;
        $booking = Session::get('booking');
        $this->defaultServiceDuration = ServiceDuration::where('is_default', 1)->first();

        if (isset($booking['date'])) {
            $today = date('Y-m-d');
            $sessionDate = $booking['date'];

            if (strtotime($sessionDate) < strtotime($today)) {
                Session::set('booking.date', $today);
            }
        }
        if (!isset($booking['duration']) && $this->defaultServiceDuration) {
            Session::set('booking.duration', $this->defaultServiceDuration->id);
        }
        $this->booking_min_requirements = [
            'massage',
            'postcode',
            'address',
            'duration'
        ];
    }

    public function book_a_massage(Request $request)
    {
        $cart =  \Cart::getContent();
        if (!$cart->isEmpty()) {
            // Cart is not empty
            $itemIds = $cart->keys()->all();
            $itemID =  $itemIds[0];
            $this->book->cancel_cart($itemID);
        }
        $booking = Session::get('booking');

        if ($booking['duration'] == 0) {
            return redirect()->back()->with('errorMassage', 'Please select your duration');
        }
        if ($request->massage) {
            $this->set_massage($request);
        }
        //create data array
        $this->data = [
            'meta_title' => trans("schedules::booking.book_later_meta_title"),
            'meta_description' => trans("schedules::booking.book_later_meta_description"),
            'meta_keywords' => trans("schedules::booking.book_later_meta_keywords"),
            'booking' => $this->session_booking_info(),
            'fp' => $this->get_focal_points(),
            'massage_info' => $this->get_massage_info(),
            'today' => Carbon::today()->format('Y-m-d'),
        ];

        return view('schedules::frontend_new.booking.book_a_massage', $this->data);
    }

    /**
     * Book a massage now page
     */
    public function book_now(Request $request)
    {
        $cart =  \Cart::getContent();
        if (!$cart->isEmpty()) {
            // Cart is not empty
            $itemIds = $cart->keys()->all();
            $itemID =  $itemIds[0];
            $this->book->cancel_cart($itemID);
        }

        $booking = Session::get('booking');

        $results = $this->book->therapistsNow();
        // return $results;
        $addr_longitude = '';
        $addr_latitude = '';
        $address = !empty($booking['address']) ? $booking['address'] : '';
        if (!empty($address)) {
            //Formatted address
            $formattedAddr = str_replace(' ', '+', $address);
            //Send request and receive json data by address
            $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . config("googlemaps.key"));
            $output = json_decode($geocodeFromAddr);
            //Get latitude and longitute from json data
            $addr_longitude = !empty($output->results[0]->geometry->location->lat) ? $output->results[0]->geometry->location->lat : '';
            $addr_latitude = !empty($output->results[0]->geometry->location->lng) ? $output->results[0]->geometry->location->lng : '';
        }

        if ($request->massage) {
            $this->set_massage($request);
            return redirect(route('bookings.book_now'));
        }
        //reset booking keys for massage me now
        if (@$booking['checkArrivalTime'] == false) {
            unset($booking['hour']);
            unset($booking['selected_therapists']);
            $booking['checkArrivalTime'] = true;
            Session::put('booking', $booking);
        }

        //create data array
        $this->data = [
            'meta_title' => trans("schedules::booking.book_later_meta_title"),
            'meta_description' => trans("schedules::booking.book_later_meta_description"),
            'meta_keywords' => trans("schedules::booking.book_later_meta_keywords"),
            'booking' => $this->session_booking_info(),
            'fp' => $this->get_focal_points(),
            'massage_info' => $this->get_massage_info(),
            'today' => Carbon::today()->format('Y-m-d'),
            'user_count' => count($results),
        ];
        // dd($this->data);
        //render page
        return view('schedules::frontend_new.booking.book_now_new', $this->data);
    }

    public function askForBooking(Request $request)
    {
        try {
            $socketBaseUrl = env('SOCKET_BASE_URL');

            // Generate unique req_id using timestamp in milliseconds + random string
            $timestampMs = round(microtime(true) * 1000); // current time in ms
            $randomStr = substr(bin2hex(random_bytes(4)), 0, 8); // 8-char random string
            $reqId = $timestampMs . '_' . $randomStr;

            $booking = Session::get('booking');

            $data['booking'] = $booking;
            $data['to'] = $request->thID;
            $data['clickedFrom'] = $request->clickedFrom;
            $data['from'] = Auth::user()->id;
            $data['customer_name'] = Auth::user()->name;
            $data['customer_avatar'] = Auth::user()->profile['image_url'];
            $data['request_exp_time'] = Carbon::now()->addSeconds(60);
            $data['hour'] = isset($request->hour) ? $request->hour : $booking['hour'];
            $data['req_id'] = $reqId;

            if($data['hour'] == '00:00'){
                $data['hour'] = date('H:i');
            }

            $booking['request_exp_time'] = $data['request_exp_time'];
            //add push notification for booking
            $notif_message = 'You have a booking request from ' . $data['customer_name'] . '.';
            $notif_users = $data['to'];

            $notiData['booking'] = $booking;
            $notiData['reciever'] = $request->thID;
            $notiData['clickedFrom'] = $request->clickedFrom;
            $notiData['sender'] = Auth::user()->id;
            $notiData['customer_name'] = Auth::user()->name;
            $notiData['customer_avatar'] = Auth::user()->profile['image_url'];
            $notiData['request_exp_time'] = Carbon::now()->addSeconds(60);
            $notiData['hour'] = isset($request->hour) ? $request->hour : $booking['hour'];
            $notiData['req_id'] = $reqId;


            NotifRepository::add($notif_users, $notif_message, 'booking-request', 'Booking Request', $notiData);
            $client = new Client();
            $response = $client->post($socketBaseUrl . '/booking/ask-for-booking', [
                'json' => $data
            ]);

            $notiData = [
                'req_id' => $reqId,
                'service_provider' => $request->thID,  // Assuming therapist or provider ID
                'customer_id' => Auth::user()->id,
                'booking' => json_encode($booking),
                'customer_name' => Auth::user()->name,
                'customer_avatar' => Auth::user()->profile['image_url'] ?? null,
                'hour' => $request->hour ?? $booking['hour'] ?? null,
                'date' => $booking['date'],
                'req_expire' => Carbon::now()->addSeconds(60),
                'address' => $booking['address'],
                'status' => 0 //Pending
            ];

            // Create record in DB
            $newRequest = BookRequest::create($notiData);

            return response()->json([
                'success' => true,
                'message' => 'Request sent!',
                'data' => $booking,
                'req_id' => $reqId
            ], 200);
        } catch (\Throwable $th) {
            return response()->json([
                'success' => false,
                'message' => $th->getMessage()
            ], 500);
        }
    }

    public function book_later()
    {
        $cart =  \Cart::getContent();
        if (!$cart->isEmpty()) {
            // Cart is not empty
            $itemIds = $cart->keys()->all();
            $itemID =  $itemIds[0];
            $this->book->cancel_cart($itemID);
        }

        // dd(if(isset($cart) || !empty($cart)));
        $booking = Session::get('booking');
        //reset booking keys for massage me later
        if (isset($booking['checkArrivalTime']) and $booking['checkArrivalTime'] == true) {
            unset($booking['hour']);
            unset($booking['selected_therapists']);
            $booking['checkArrivalTime'] = false;
            Session::put('booking', $booking);
        }

        $all_days = $this->book->available_30_days();
        //create data array
        $this->data = [
            'meta_title' => trans("schedules::booking.book_later_meta_title"),
            'meta_description' => trans("schedules::booking.book_later_meta_description"),
            'meta_keywords' => trans("schedules::booking.book_later_meta_keywords"),
            'booking' => $this->session_booking_info(),
            'fp' => $this->get_focal_points(),
            'massage_info' => $this->get_massage_info(),
            'selected_date' => isset($booking['date']) ? $booking['date'] : date('Y-m-d'),
            'all_days' => $all_days
        ];
        //render page
        return view('schedules::frontend_new.booking.book_later_new', $this->data);
    }

    protected function session_booking_info()
    {
        $booking = Session::get('booking');
        if (!isset($booking['therapists_opt']))
            $booking['therapists_opt'] = null;
        if (!isset($booking['focal_points']))
            $booking['focal_points'] = [];

        return $booking;
    }

    /**
     * Get therapists
     *
     * return array
     */
    public function get_therapists()
    {
        $booking = Session::get('booking');

        $results = $this->book->therapists();

        $this->data['results'] = $results;
        $this->data['selected'] = (array)@$booking['selected_therapists'];
        return response()->json([
            'data' => view('schedules::frontend_new.booking.partial_all_therapists_list', $this->data)->render(),
            'count' => count($results),
        ]);
        return response()->json([
            'data' => view('schedules::frontend_new.booking.partial_all_therapists_list', $this->data),
            'count' => count($results),
        ]);
    }


    // get therapist count

    public function get_therapists_count()
    {
        $booking = Session::get('booking');

        $results = $this->book->salontherapists();

        $this->data['results'] = $results;
        $this->data['selected'] = (array)@$booking['selected_therapists'];
        // dd($results);
        return count($results);
        // dd(!isset($results['unavailable']) && !isset($results['available']));
        // if(!isset($results['unavailable']) && !isset($results['available'])){
        //     return $count = 0;
        // } else {
        //     return $count = 1;
        // }

    }

    /**
     * Get therapists now based on their location, google eta and availabillity
     *
     * return array
     */
    public function get_therapistsnow()
    {
        $booking = Session::get('booking');

        $results = $this->book->therapistsNow();
        // return $results;
        $addr_longitude = '';
        $addr_latitude = '';
        $address = !empty($booking['address']) ? $booking['address'] : '';
        if (!empty($address)) {
            //Formatted address
            $formattedAddr = str_replace(' ', '+', $address);
            //Send request and receive json data by address
            $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . config("googlemaps.key"));
            $output = json_decode($geocodeFromAddr);
            //Get latitude and longitute from json data
            $addr_longitude = !empty($output->results[0]->geometry->location->lat) ? $output->results[0]->geometry->location->lat : '';
            $addr_latitude = !empty($output->results[0]->geometry->location->lng) ? $output->results[0]->geometry->location->lng : '';
        }
        //print_r($results);

        // modified from here
        // $coverage_results = array();
        // if(!empty($results)){
        //     $is_in_polygon = 0;
        //     foreach($results as $th){
        //         $therapist_coverages = UserCoverageArea::where('user_id',$th->id)->get()->toArray();
        //         $therapist_coverages_last = UserCoverageArea::where('user_id',$th->id)->orderBy('id','DESC')->first();
        //         if(!empty($therapist_coverages_last->polygon_no)){
        //             for ($i = 1; $i <= $therapist_coverages_last->polygon_no; $i++) {
        //                 $therapist_coverages = UserCoverageArea::select('lng','lat')->where('user_id',$th->id)->where('polygon_no',$therapist_coverages_last->polygon_no)->get();
        //                 $polygon_lat_lng_Arr  = array();
        //                 foreach ($therapist_coverages as $coverages) {
        //                     $longitude = $coverages->lng;
        //                     $latitude  = $coverages->lat;
        //                     $polygon_lat_lng_Arr[] = $longitude.' '.$latitude;
        //                 }
        //                 $longitude_x = $addr_longitude; // x-coordinate of the point to test
        //                 $latitude_y  = $addr_latitude; // y-coordinate of the point to test
        //                 //$point = $longitude_x.' '.$latitude_y;
        //                 $point = $latitude_y.' '.$longitude_x;
        //                 if (UserCoverageArea::pointInPolygon($point, $polygon_lat_lng_Arr)){
        //                   $is_in_polygon++;
        //                 }
        //             }
        //         }

        //         if(!empty($addr_longitude) && !empty($addr_latitude)){
        //             if($is_in_polygon > 0){
        //                 $is_in_polygon = 0;
        //                 $coverage_results[] = $th;
        //             }
        //         }else{
        //             //$results[] = $th;
        //         }
        //     }
        // }
        // $results               = $coverage_results;
        // end

        $this->data['user_count'] = count($results);
        $this->data['results'] = $results;
        // return $results;
        $this->data['selected'] = (array)@$booking['selected_therapists'];
        $this->data['bookingSession'] = $booking;
        // dd($this->data);
        return view('schedules::frontend_new.booking.partial_therapists_now', $this->data);
    }

    public function get_days()
    {
        $results = $this->book->days();
        return $results;
    }

    /**
     * Get available hours
     * @param null $date
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function get_hours($date = null)
    {
        if (!$date)
            $date = date('Y-m-d');
        $booking = Session::get('booking');

        if (!isset($booking['hour']) || $booking['hour'] == '00:00') {
            $first_hours = $this->book->getAndSetFirstAvailableDayHour();
            $booking = Session::get('booking');
        }

        $hours = $this->book->all_hours($date);

        $this->data['hours'] = $hours;
        $this->data['selectedhour'] = isset($booking['hour']) ? $booking['hour'] : null;

        //return view partial
        return view('schedules::frontend_new.booking.partial_hours', $this->data);
    }

    /**
     * Set postcode
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_postcode(Request $request)
    {
        if (!$request->has('address'))
            return response(['message' => 'The address is required'], 403);

        //get booking from session
        $booking = Session::get('booking');

        //set postcode to session
        // $booking['postcode'] = $postcode->postcode;
        $booking['address'] = $request->address;
        $address = $request->address;

        if (!empty($address)) {
            //Formatted address
            $formattedAddr = str_replace(' ', '+', $address);

            //Send request and receive json data by address
            $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . config('googlemaps.key'));
            $output = json_decode($geocodeFromAddr);
            if (!empty($output)) {
                $addressComponents = $output->results[0]->address_components;
                foreach ($addressComponents as $addrComp) {
                    if ($addrComp->types[0] == 'postal_code') {
                        //Return the zipcode
                        $address_postcode = $addrComp->long_name;
                        $booking['postcode'] = $address_postcode;
                    }
                }
            }
            //Get latitude and longitute from json data
            $addr_longitude = !empty($output->results[0]->geometry->location->lat) ? $output->results[0]->geometry->location->lat : '';
            $addr_latitude = !empty($output->results[0]->geometry->location->lng) ? $output->results[0]->geometry->location->lng : '';
        }
        //    dd($booking);
        Session::put('booking', $booking);

        //return success response
        // return response(['message'=>trans('schedules::booking.message_success_postcode_confirmed')],200);
        return response(['message' => 'Your address is confirmed, please continue with the following steps'], 200);
    }

    /***
     * Get address list
     * @param Request $request
     */
    public function get_address_list($postcode = '')
    {

        //postcode anywhere
        //        $param = [
        //            'find' => 'FindByPartialPostcode', // perform 'find' action calling 'FindByPostcode' web service
        //            'param' => ['postcode'=>$postcode, 'endpoint'=>'json'] // parameters for web service called
        //        ];

        $param = [
            'find' => 'PAInteractiveFind', // perform 'find' action calling 'FindByPostcode' web service
            'param' => ['SearchTerm' => $postcode, 'endpoint' => 'json'] // parameters for web service called
        ];


        $response = \PA::getResponse($param);

        return $response;
    }

    /**
     * Get address details from Postcode Anyware
     *
     * @param Request $request
     * @return string
     */
    public function get_address_details(Request $request)
    {
        $postcode = '';

        $param = [
            'retrieve' => 'RetrieveById', // perform 'find' action calling 'FindByPostcode' web service
            'param' => ['Id' => $request->id, 'endpoint' => 'json'] // parameters for web service called
        ];

        $response = \PA::getResponse($param);
        $result = json_decode($response, true)[0];

        //return postcode
        return $result;
    }

    /**
     * Set massage duration
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_duration(Request $request)
    {
        if (!$request->has('duration'))
            return response(['message' => 'The massage duration is required'], 403);

        $obj = ServiceDuration::find($request->duration);
        if (!$obj)
            return response(['message' => 'The massage duration is required'], 403);
        $booking = (array)Session::get('booking');
        $booking['duration'] = $obj->id;
        unset($booking['hour']);
        Session::put('booking', $booking);
        //return success response
        // dd(Session::get('booking'));
        return response(['message' => Session::get('booking')], 200);
    }

    /**
     * Set massage type
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_massage(Request $request)
    {
        //        if (!$request->has('massage'))
        //            return response(['message'=>'The massage type is required'],403);
        //      
        $obj = ServiceType::where('id', $request->massage)->first();
        //
        //        if (!$obj)
        //            return response(['message'=>'The massage type is required'],403);

        $booking = (array)Session::get('booking');
        $booking['massage'] = $obj ? $obj->id : null;
        Session::put('booking', $booking);

        //return success response
        return response(['message' => 'success'], 200);
    }

    /**
     * Set booking date
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_date(Request $request)
    {
        if (!$request->has('date')) {
            $request->input('date', date('Y-m-d'));
        }

        $date = Carbon::createFromFormat('Y-m-d', $request->date)->startOfDay()->format('Y-m-d');
        $booking = (array)Session::get('booking');
        $booking['date'] = $date;

        Session::put('booking', $booking);

        //return success response
        return response(['message' => 'success'], 200);
    }

    /**
     * Set hour
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */

    public function resetSessionBooking()
    {
        $cdate = "'" . date("Y-m-d H:i:s") . "'";
        $data = DB::table('sessions_basket_therapists')
            ->whereRaw('ABS(TIMESTAMPDIFF(MINUTE, created_at, ' . $cdate . ')) >= 5')
            ->delete();
    }
    public function set_hour(Request $request)
    {
        $this->resetSessionBooking();
        if (!$request->has('hour'))
            return response(['message' => 'The hour is required'], 403);

        $booking = (array)Session::get('booking');
        $booking['hour'] = $request->hour;
        Session::put('booking', $booking);

        //return success response
        return response(['message' => 'success'], 200);
    }

    public function set_therapist_hour(Request $request)
    {
        $this->data['therapist'] = null;
        $this->data['date'] = null;
        $this->data['hour'] = null;

        if ($request->thID) {
            $this->data['therapist'] = $request->thID;
            if ($request->date) {
                $this->data['date'] = $request->date;
                Session::set('therapists_booking_info.' . $request->thID . '.date', $request->date);
            }

            if ($request->hour) {
                $this->data['hour'] = $request->hour;
                Session::set('therapists_booking_info.' . $request->thID . '.hour', $request->hour);
            }
        }

        if ($request->thID && $request->date  && $request->hour) {
            $view = view('schedules::frontend_new.booking.partial_therapist_booking_button', $this->data)->render();
            return response(['partial_button_book_therapist' => $view], 200);
        } else {
            return response(['message' => 'Hour & date is required'], 403);
        }
    }

    public function set_salon_therapist_hour(Request $request)
    {
        $this->data['therapist'] = null;
        $this->data['date'] = null;
        $this->data['hour'] = null;

        if ($request->thID) {
            $this->data['therapist'] = $request->thID;
            if ($request->date) {
                $this->data['date'] = $request->date;
                Session::set('therapists_booking_info.' . $request->thID . '.date', $request->date);
            }

            if ($request->hour) {
                $this->data['hour'] = $request->hour;
                Session::set('therapists_booking_info.' . $request->thID . '.hour', $request->hour);
            }
        }

        if ($request->thID && $request->date  && $request->hour) {
            $view = view('schedules::frontend_new.booking.partial_therapist_salon_booking_button', $this->data)->render();
            return response(['partial_button_book_therapist' => $view], 200);
        } else {
            return response(['message' => 'Hour & date is required'], 403);
        }
    }
    /**
     * Set number of therapists for the booking
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_therapists_no(Request $request)
    {
        $therapistsNo = $request->thNo;

        //ser default therapists no
        if (!$therapistsNo)
            $therapistsNo = "1_th";

        switch ($therapistsNo) {
            case '1_th':
                $therapists = 1;
                $type = '1 therapist';
                break;
            case '2_th':
                $therapists = 2;
                $type = '2 therapists';
                break;
            case '4hands':
                $therapists = 2;
                $type = 'four hands massage';
                break;
        } //end switch

        $booking = (array)session('booking');

        //create booking keys
        $booking['therapists_opt'] = $therapistsNo;
        $booking['therapists'] = $therapists;
        $booking['type'] = $type;

        if (!isset($booking['selected_therapists']))
            $booking['selected_therapists'] = [];

        if (nonEmptyArray($booking['selected_therapists'])) {
            if (count($booking['selected_therapists']) > $therapists) {
                $last = count($booking['selected_therapists']) - 1;
                unset($booking['selected_therapists'][$last]);
            }
        }

        //store in session
        session(['booking' => $booking]);

        if (!isset($booking['date'])) {
            $today = date('Y-m-d');
            Session::set('booking.date', $today);
        }
        $booking = (array)session('booking');
        //return success response
        return response(['message' => 'success', 'date' => $booking['date']], 200);
    }


    /**
     * Set therapist
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_therapist(Request $request)
    {
        $booking = Session::get('booking');


        if (!isset($booking['therapists']) || !isset($booking['therapists_opt']) || !isset($booking['type'])) {
            $booking['therapists'] = 1;
            $booking['therapists_opt'] = "1_th";
            $booking['type'] = "1 therapist";
        }

        if (isset($request->thID)) {
            $booking['provider_id'] = $request->thID;
        }

        //if one of mandatory fields is missing, return empty array results
        $mandatory_fields = ['postcode', 'duration', 'date', 'therapists'];
        foreach ($mandatory_fields as $field) {
            if (!isset($booking[$field]))
                return response(['message' => 'You must select postcode, massage duration, type of massage, date of masage and number of therapists'], 403);
        } //endforeach

        if (!isset($booking['selected_therapists']))
            $booking['selected_therapists'] = [];


        if (in_array($request->thID, $booking['selected_therapists'])) {
            //unmark therapist
            $key = array_search($request->thID, $booking['selected_therapists']);
            if (!is_null($key))
                unset($booking['selected_therapists'][$key]);
        } elseif (count($booking['selected_therapists']) < $booking['therapists']) {
            //mark the therapist as selected
            @$booking['selected_therapists'][] = $request->thID;
        } else {
            //change the last therapist
            $last = count($booking['selected_therapists']) - 1;
            $booking['selected_therapists'][$last] = $request->thID;
        }

        //        session(['booking' => $booking]);
        Session::put('booking', $booking);

        //dd($booking);
        //return success response
        return response(['message' => 'success'], 200);
    }


    /**
     * Set therapist modal
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_therapist_modal(Request $request)
    {
        if ($request->date) {
            Session::set('booking.date', $request->date);
        }

        if ($request->hour) {
            Session::set('booking.hour', $request->hour);
        }
        $booking = Session::get('booking');

        if (!isset($booking['therapists']) || !isset($booking['therapists_opt']) || !isset($booking['type'])) {
            $booking['therapists'] = 1;
            $booking['therapists_opt'] = "1_th";
            $booking['type'] = "1 therapist";
        }

        //if one of mandatory fields is missing, return empty array results
        $mandatory_fields = ['postcode', 'duration', 'date', 'therapists'];
        foreach ($mandatory_fields as $field) {
            if (!isset($booking[$field]))
                return response(['message' => 'You must select postcode, massage duration, type of massage, date of masage and number of therapists'], 403);
        } //endforeach

        if (!isset($booking['selected_therapists']))
            $booking['selected_therapists'] = [];


        if (in_array($request->thID, $booking['selected_therapists'])) {
            //unmark therapist
            $key = array_search($request->thID, $booking['selected_therapists']);
            if (!is_null($key))
                unset($booking['selected_therapists'][$key]);
        } elseif (count($booking['selected_therapists']) < $booking['therapists']) {
            //mark the therapist as selected
            @$booking['selected_therapists'][] = $request->thID;
        } else {
            //change the last therapist
            $last = count($booking['selected_therapists']) - 1;
            $booking['selected_therapists'][$last] = $request->thID;
        }

        if (empty($booking['selected_therapists'])) {
            $booking['selected_therapists'] = [$request->thID];
        }

        Session::put('booking', $booking);

        return response(['message' => 'success'], 200);
    }

    /**
     * Set therapist now: with therapistId, date:today and first available hour
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_therapist_now(Request $request)
    {
        $booking = (array)session('booking');

        $booking['checkArrivalTime'] = true;
        $booking['disclaimer'] = "now";

        //set default booking therapists number
        empty($booking['date']) ? $booking['date'] = date('Y-m-d') : '';
        $booking['therapists'] = 1;
        $booking['therapists_opt'] = "1_th";
        $booking['type'] = "1 therapist";



        //set hour
        $booking['hour'] = $request->hour;
        $repo = new BookingClass();
        $user = User::find($request->thID);

        $hour = Carbon::createFromFormat('H:i', $request->hour);
        $recheckHour = Carbon::createFromFormat('H:i', $repo->getFirstHour($user, $booking));

        $diff = $hour->diffInMinutes($recheckHour);

        if ($diff > 2)
            return response(['message' => trans('schedules::booking.message_booking_now_time_passed')], 403);

        //if one of mandatory fields is missing, return empty array results
        $mandatory_fields = ['duration', 'date'];

        foreach ($mandatory_fields as $field) {
            if (!isset($booking[$field]))
                return response(['message' => 'You must select massage duration, type of massage, date of masage and number of therapists'], 403);
        } //endforeach

        if (!isset($booking['selected_therapists']))
            $booking['selected_therapists'] = [];


        if (in_array($request->thID, $booking['selected_therapists'])) {
            //unmark therapist
            $key = array_search($request->thID, $booking['selected_therapists']);
            if (!is_null($key))
                unset($booking['selected_therapists'][$key]);

            //unset first available therapist hour for booking
            unset($booking['hour']);
        } elseif (count($booking['selected_therapists']) < $booking['therapists']) {
            //mark the therapist as selected
            @$booking['selected_therapists'][] = $request->thID;
        } else {
            //change the last therapist
            $last = count($booking['selected_therapists']) - 1;
            $booking['selected_therapists'][$last] = $request->thID;
        }
        session(['booking' => $booking]);

        //return success response
        return response(['message' => 'success', 'booking' => $booking, 'sessionBooking' => session('booking')], 200);
    }

    /**
     * Set booking focal points
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_focalpoints(Request $request)
    {
        $booking = (array)Session::get('booking');
        $booking['focal_points'] = $request->fp;
        Session::set('booking', $booking);

        //return success response
        return response(['message' => 'success'], 200);
    }

    /**
     * Get selected therapists
     */
    public function get_selected_therapists()
    {
        $booking = (array)Session::get('booking');

        $this->data['therapists'] = $this->book->selected_therapists();

        //render page
        return view('schedules::frontend_new.booking.partial_therapist_info', $this->data);
    }

    public function get_therapist_hours(Request $request)
    {


        if (!$request->date) {
            $date = date('Y-m-d');
        } else {
            $date = $request->date;
        }
        Session::set('therapists_booking_info.' . $request->thID . '.date', $date);
        $booking = Session::get('booking');

        $duration = ServiceDuration::find($booking['duration'])->duration;
        // dd($duration);
        $hours = $this->book->th_hours($date, $request->thID);
        // dd($hours);
        $therapist = User::OfTherapists()
            ->where('id', $request->thID)
            ->first();

        $dateC = Carbon::createFromFormat('Y-m-d', $date)->startOfDay();
        $weekday = date('w', strtotime($dateC->format('Y-m-d')));
        // $twd = $therapist->workingdays()->where('dayoff',0)->where('weekday',$weekday)->first();
        $twds = $therapist->workingdays()->where('dayoff', 0)->where('weekday', $weekday)->get();
        $allHours = collect([]);;
        $allHours = $allHours->merge($hours);
        // dd($allHours);
        $tempHours = collect([]);
        if ($hours) {

            foreach ($twds as $key => $twd) {
                $hours = collect([]);
                $hours = $hours->merge($allHours);
                // if($key == 1) {
                //     dd($allHours);
                //     dd($key, $hours);
                // }
                foreach ($allHours as $k => $hour) {
                    if (isset($hour['hour'])) {
                        $curr_hour_plus_duration = strtotime('+' . $duration . ' minutes', strtotime($hour['hour']));

                        if (!$hour['available']) {
                            unset($hours[$k]);
                        }
                        if ($twd && ($curr_hour_plus_duration > strtotime($twd->bo_end_raw))) {
                            unset($hours[$k]);
                        }
                    } else {
                        unset($hours[$k]);
                    }
                }

                $tempHours = $tempHours->merge($hours);
                // dd($tempHours);
            }
        }

        // $currentDateTimeData = BookingOrder::whereDate('datetime', $date)->get();
        // var_dump("fdsf");die;

        // dd();
        $this->data['hours'] = $hours;
        $this->data['selectedtherapist'] = $request->thID;
        $this->data['selectedtherapistdate'] = $date;
        $this->data['selectedhour'] = isset($booking['hour']) ? $booking['hour'] : null;
        $view = view('schedules::frontend_new.booking.partial_therapist_hours', $this->data)->render();
        //return view partial
        return response([
            'partial_therapist_hours' => $view,
            'hours_count' => count($tempHours)
        ], 200);
        return view('schedules::frontend_new.booking.partial_therapist_hours', $this->data)->render();
    }
    /**
     * Theraspist info modal
     * @param Request $request
     * @return false|stringget_therapists
     * @throws \Throwable
     */
    public function get_therapist_info(Request $request)
    {
        $this->data['availability'] = false;
        $this->data['therapist'] = null;
        $this->data['selected_date'] = '';
        $this->data['selectedhour'] = '';

        $booking = (array)Session::get('booking');
        // dd($booking);
        if (isset($request->thID) && !empty($request->thID)) {
            $therpist = $this->book->therapist_info($request->thID);
            $this->data['therapist'] = $therpist;
            // dd($therpist);
        }
        if (isset($request->availability) && !empty($request->availability)) {
            $this->data['availability'] = true;
        }
        $this->data['selected'] = (array)@$booking['selected_therapists'];
        $this->data['all_days'] = $this->book->available_30_days();

        if (isset($booking['date']) && !empty($booking['date'])) {
            $this->data['selected_date'] = $booking['date'];
        }

        if (isset($booking['hour']) && !empty($booking['hour'])) {
            $this->data['selectedhour'] = $booking['hour'];
        }

        if (isset($booking['massage']) && !empty($booking['massage'])) {
            $this->data['massage'] = ServiceType::whereIn('id', [$booking['massage']])->get();
            // dd($this->data);
        }
        $json['partial'] = view('schedules::frontend_new.booking.partial_therapist_modal_info', $this->data)->render();
        $json['availability'] = $this->data['availability'];
        $json['selectedhour'] = $this->data['selectedhour'];
        $json['selected_date'] = $this->data['selected_date'];
        //render page
        return json_encode($json);
    }

    /**
     * Salon info modal
     * @param Request $request
     * @return false|stringget_therapists
     * @throws \Throwable
     */
    public function get_salon_info(Request $request)
    {
        $this->data['availability'] = false;
        $this->data['therapist'] = null;
        $this->data['selected_date'] = '';
        $this->data['selectedhour'] = '';

        $booking = (array)Session::get('booking');
        $this->data['booking'] = $booking;
        // dd($booking);
        if (isset($request->thID) && !empty($request->thID)) {
            $therpist = $this->book->salon_info($request->thID);
            $this->data['therapist'] = $therpist;
            // dd($therpist);
        }
        if (isset($request->availability) && !empty($request->availability)) {
            $this->data['availability'] = true;
        }
        $this->data['selected'] = (array)@$booking['selected_therapists'];
        $this->data['all_days'] = $this->book->available_30_days();

        if (isset($booking['date']) && !empty($booking['date'])) {
            $this->data['selected_date'] = $booking['date'];
        }

        if (isset($booking['hour']) && !empty($booking['hour'])) {
            $this->data['selectedhour'] = $booking['hour'];
        }

        if (isset($booking['massage']) && !empty($booking['massage'])) {
            $this->data['massage'] = ServiceType::whereIn('id', [$booking['massage']])->get();
            // dd($this->data);
        }
        // dd($this->data['therapist']);
        $json['partial'] = view('schedules::frontend_new.booking.partial_salon_detials_modal_info', $this->data)->render();
        $json['availability'] = $this->data['availability'];
        $json['selectedhour'] = $this->data['selectedhour'];
        $json['selected_date'] = $this->data['selected_date'];
        //render page
        return json_encode($json);
    }

    /**
     * Get focal points
     *
     * @return array
     */
    protected function get_focal_points()
    {
        $results = $this->book->focal_points();
        return $results;
    }

    /**
     * Get massage info
     */
    protected function get_massage_info()
    {
        $m = [];

        //duration massage options
        $durations = ServiceDuration::where('is_extra', '=', 0)
            ->orderBy('is_default', 'desc')
            ->orderBy('duration', 'asc')
            ->lists('name', 'id');


        //type of massage options
        $massageTypes = ServiceType::selectRaw('*, IF(name = "optional", 1,0) as first_el')
            ->orderBy('first_el', 'desc')
            ->orderBy('order_no', 'asc')
            ->lists('name', 'id');

        //if massage type is not selected, select the first one
        $defaultMassageType = $massageTypes->take(1);

        $booking = (array)Session::get('booking');
        if (!isset($booking['massage']) && $defaultMassageType->count() > 0) {
            $key = key($defaultMassageType->toArray());
            $booking['massage'] = $key;
            Session::put('booking', $booking);
        } //endif


        //compose array
        $m['duration_opt'] = $durations;
        $m['massage_opt'] = $massageTypes;

        //return results
        return $m;
    }

    public function check_booking_address_input(Request $request)
    {
        $booking_post = $request->all();
        $booking_sess = (array)Session::get('booking');

        if (isset($booking_post['address']) && empty($booking_post['address'])) {
            if (isset($booking_sess['postcode'])) {
                unset($booking_sess['postcode']);
            }
            if (isset($booking_sess['address'])) {
                unset($booking_sess['address']);
            }
            Session::put('booking', $booking_sess);
        }
    }
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response|null
     */
    public function check_booking_session_min_requirements(Request $request)
    {
        $booking_post = $request->all();

        $booking_min_requirements = $this->booking_min_requirements;
        $booking_sess = (array)Session::get('booking');
        $resp = null;
        $booking_min_requirements_status = true;


        foreach ($booking_min_requirements as $min_requirement) {
            /* Data from post */
            if (isset($booking_post[$min_requirement]) && empty($booking_post[$min_requirement])) {
                if ($min_requirement == 'address') {
                    if (isset($booking_sess['postcode'])) {
                        unset($booking_sess['postcode']);
                    }
                    if (isset($booking_sess['address'])) {
                        unset($booking_sess['address']);
                    }
                    Session::put('booking', $booking_sess);
                    $booking_sess = (array)Session::get('booking');
                }
                $resp = response(['message' => 'Please fill in the postcode, duration and type of massage'], 403);
                $booking_min_requirements_status = false;
                break;
            }

            /* Data from session */
            // if (!isset($booking_sess[$min_requirement]) || empty($booking_sess[$min_requirement]))
            // {
            //     $resp = response(['message'=>'Please fill in the postcode, duration and type of massage'],403);
            //     $booking_min_requirements_status = false;
            //     break;
            // }
        }

        if ($request->type && $booking_min_requirements_status) {
            if ($request->type == 'later') {
                $resp = response(['url' => route('bookings.book_later')], 200);
            } elseif ($request->type == 'now') {
                $resp = response(['url' => route('bookings.book_now')], 200);
            }
        }

        return $resp;
    }

    public function treatmentView()
    {
        $booking = Session::get('booking');
        // dd($booking);
        //create data array
        $this->data = [
            'meta_title' => trans("schedules::booking.book_later_meta_title"),
            'meta_description' => trans("schedules::booking.book_later_meta_description"),
            'meta_keywords' => trans("schedules::booking.book_later_meta_keywords"),
            'booking' => $this->session_booking_info(),
            'fp' => $this->get_focal_points(),
            'massage_info' => $this->get_massage_info(),
            'today' => Carbon::today()->format('Y-m-d'),
        ];
        if (isset($booking['address'])) {
            return view('schedules::frontend_new.booking.treatment', $this->data);
        } else {
            return redirect()->back()->withErrors(['msg' => 'Please enter your postal code/address']);
        }
    }

    public function inPerson()
    {
        $param = request('search');
        // dd($param);
        if ($param) {
            $this->data['search'] = $param;
            $this->data['services'] = ServiceType::whereIn('service_type_id', [1])->where('parent_category_id', 0)->where('name', 'LIKE', '%' . $param . '%')->orderBy('order_no')->get();
        } else {
            $this->data['services'] = ServiceType::whereIn('service_type_id', [1])->where('parent_category_id', 0)->orderBy('order_no')->get();
        }
        // dd($this->data);
        return view('schedules::frontend_new.booking.service_type', $this->data);
    }

    public function online()
    {
        $this->data['services'] = ServiceType::whereIn('service_type_id', [2])->where('parent_category_id', 0)->get();
        // dd($this->data);
        return view('schedules::frontend_new.booking.online_service_type', $this->data);
    }

    public function salonTreatmentSelection()
    {
        $param = request('search');
        if ($param) {
            $this->data['search'] = $param;
            $this->data['services'] = SalonCategory::where('image', '!=', NULL)
                ->where('image', '!=', '')
                ->where('is_showed', 1)
                ->where(function ($query) use ($param) {
                    $query->where('name', 'LIKE', '%' . $param . '%')
                        ->orWhere('search_keywords', 'LIKE', '%' . $param . '%');
                })
                ->get();
        } else {
            $this->data['services'] = SalonCategory::where('image', '!=', NULL)->where('image', '!=', '')->where('is_showed', 1)->get();
        }
        // dd($this->data);
        return view('schedules::frontend_new.booking.salon_service_type', $this->data);
    }

    public function selectSalonTreatment(Request $request)
    {
        $booking = Session::get('booking');
        // $this->data['booking'] = $booking;

        if (!isset($booking['address'])) {
            return redirect('/')->withErrors(['msg' => 'Please enter your postal code/address']);
        }

        $treatment = SalonCategory::with('duration')->where('id', $request->trID)->first();
        // dd($treatment);
        Session::put('salon_booking_treatment_name', $treatment->name);
        Session::put('salon_booking_treatment_id', $treatment->id);

        $salon_booking_treatment_name = Session::get('salon_booking_treatment_name');

        if (Session::has('salon_booking_treatment_name')) {
            $this->data['count'] = 1;
            return response()->json($this->data, 200);
        } else {
            $this->data['count'] = 0;
            return response()->json($this->data, 200);
        }
    }

    public function salon()
    {
        // dd(Session::all());
        $booking = Session::get('booking');
        $this->data['booking'] = $booking;

        if (Session::has('salon_booking_time')) {
            // dd("here");
            $this->data['salon_booking_time'] = Session::get('salon_booking_time');
        }

        if (Session::has('salon_booking_date')) {
            // dd("here");
            $this->data['salon_booking_date'] = Session::get('salon_booking_date');
        }

        if (Session::has('salon_booking_treatment_name')) {
            // dd("here");
            $this->data['salon_booking_treatment_name'] = Session::get('salon_booking_treatment_name');
        }

        if (!isset($booking['address'])) {
            return redirect('/')->withErrors(['msg' => 'Please enter your postal code/address']);
        }
        // dd(Auth::user());
        if (!Auth::user()) {
            $userId = 0;
        } else {
            $userId = Auth::user()->id;
            $this->data['cartContent'] = $this->cartContent();
        }
        $this->data['cartCount'] = SalonCart::where('user_id', $userId)->count();
        $this->data['active_salons'] = User::getSubscribedSalonUser()->get();
        // dd($this->data['active_salons']);
        $this->data['salon_users'] = User::query()->whereHas('roles', function ($query) {
            return $query->where('slug', 'salon');
        })->orderBy('nr_crt', 'asc')->get();

        // set parent category in header in uppercase;
        $treatmentsForHeaders = [];
        // $header_treatments = SalonCategory::where('parent_category_id',0)->pluck('name','id');
        // // dd($header_treatments);
        // foreach($header_treatments as $header_treatment){
        //    $treatmentsForHeaders[] = strtoupper($header_treatment);
        // }
        $this->data['header_treatments'] = $this->salonHeaderTreatments();

        $this->data['treatments'] = SalonCategory::where('parent_category_id', 0)->get();
        // dd(Session::get('salon_booking_time'));
        $this->data['salon_booking_date'] = Session::get('salon_booking_date');
        $this->data['salon_booking_time'] = Session::get('salon_booking_time');
        $this->data['salon_all_users'] = User::query()->whereHas('roles', function ($query) {
            return $query->where('slug', 'salon');
        })->orderBy('nr_crt', 'asc')->get();
        // dd($this->data['salon_all_users']);
        // $this->date['salon_booking_time'] = Session::get('salon_booking_time');
        // dd($this->data);
        return view('schedules::frontend_new.booking.salon', $this->data);
    }

    public function salonTreatments()
    {
        // dd(Session::get('salon_booking_date'));
        $booking = Session::get('booking');
        if (!isset($booking['address'])) {
            return redirect('/')->withErrors(['msg' => 'Please enter your postal code/address']);
        }
        if (Session::get('salon_booking_date') || Session::get('salon_booking_date') != '') {
            $this->data['treatments'] = SalonCategory::where('parent_category_id', 0)->get();
            return view('schedules::frontend_new.booking.salon_treatments', $this->data);
        } else {
            return redirect()->back();
        }
    }

    public function getSalonUserInRange($latitude, $longitude, $km)
    {
        return $salon_users = DB::select("SELECT * FROM (
                    SELECT *, 
                        (
                            (
                                (
                                    acos(
                                        sin(( $latitude * pi() / 180))
                                        *
                                        sin(( `lat` * pi() / 180)) + cos(( $latitude * pi() /180 ))
                                        *
                                        cos(( `lat` * pi() / 180)) * cos((( $longitude - `long`) * pi()/180)))
                                ) * 180/pi()
                            ) * 60 * 1.1515 * 1.609344
                        )
                    as distance FROM `users`
                ) users
                WHERE distance <= $km
                ");
    }

    public function salonUsers($id)
    {
        $booking = Session::get('booking');
        $this->data['booking'] = $booking;

        if (Session::has('salon_booking_time')) {
            // dd("here");
            $this->data['salon_booking_time'] = Session::get('salon_booking_time');
        }

        if (Session::has('salon_booking_date')) {
            // dd("here");
            $this->data['salon_booking_date'] = Session::get('salon_booking_date');
        }

        if (Session::has('salon_booking_treatment_name')) {
            // dd("here");
            $this->data['salon_booking_treatment_name'] = Session::get('salon_booking_treatment_name');
        }
        //find near by salon on behalf of session address
        if (!isset($booking['address'])) {
            return redirect('/')->withErrors(['msg' => 'Please enter your postal code/address']);
        }
        $add = $booking['address'];
        if (!$add) {
            return redirect('/');
        }
        //Formatted address
        $formattedAddr = str_replace(' ', '+', $add);
        // dd($formattedAddr);
        //Send request and receive json data by address
        $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . config('googlemaps.key'));
        $output = json_decode($geocodeFromAddr);
        // dd($output);
        if (!empty($output)) {
            $addressComponents = $output->results[0]->address_components;
            foreach ($addressComponents as $addrComp) {
                if ($addrComp->types[0] == 'postal_code') {
                    //Return the zipcode
                    $address_postcode = $addrComp->long_name;
                    $booking['postcode'] = $address_postcode;
                }
            }
        }
        $addr_latitude = !empty($output->results[0]->geometry->location->lat) ? $output->results[0]->geometry->location->lat : '';
        $addr_longitude = !empty($output->results[0]->geometry->location->lng) ? $output->results[0]->geometry->location->lng : '';
        $this->data['lon'] = $addr_longitude;
        $this->data['lat'] =  $addr_latitude;
        $this->data['salon_users'] = $this->getSalonUserInRange($addr_latitude, $addr_longitude, 100);
        //end

        $this->data['cartCount'] = SalonCart::where('user_id', Auth::user()->id)->count();
        $this->data['cartContent'] = $this->cartContent();

        $this->data['header_treatments'] = $this->salonHeaderTreatments();

        if (Session::get('salon_booking_date') || Session::get('salon_booking_date') != '') {
            Session::put('selected_salon_therapist', 0);
            // $this->data['salon_users'] = User::query()->whereHas('roles', function ($query) {
            //     return $query->where('slug', 'salon');
            // })->orderBy('nr_crt', 'asc')->get();

            return view('schedules::frontend_new.booking.salon_users', $this->data);
        }
        return redirect()->back();
    }

    public function salonOwners()
    {

        $booking = Session::get('booking');
        $this->data['booking'] = $booking;
        // dd(Session::all());
        $this->data['salon_booking_time'] = 'AnyTime';

        if (Session::has('salon_booking_time')) {
            // dd("here");
            $this->data['salon_booking_time'] = Session::get('salon_booking_time');
        }
        $treatment_id = 0;
        if (Session::has('salon_booking_treatment_id')) {
            $treatment_id = Session::get('salon_booking_treatment_id');
        }
        if (Session::has('salon_booking_date')) {
            // dd("here");
            $this->data['salon_booking_date'] = Session::get('salon_booking_date');
        }

        if (Session::has('salon_booking_treatment_name')) {
            // dd("here");
            $this->data['salon_booking_treatment_name'] = Session::get('salon_booking_treatment_name');
        }

        $this->data['treatments'] = SalonCategory::where('parent_category_id', 0)->get();

        //find near by salon on behalf of session address
        if (!isset($booking['address'])) {
            return redirect('/')->withErrors(['msg' => 'Please enter your postal code/address']);
        }
        // dd($booking);
        $add = !empty($booking['address']) ? $booking['address'] : null;
        if (!$add) {
            return redirect('/');
        }
        //Formatted address
        $formattedAddr = str_replace(' ', '+', $add);
        // dd($formattedAddr);
        //Send request and receive json data by address
        $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . config('googlemaps.key'));
        $output = json_decode($geocodeFromAddr);
        // dd($output);
        if (!empty($output)) {
            $addressComponents = $output->results[0]->address_components;
            foreach ($addressComponents as $addrComp) {
                if ($addrComp->types[0] == 'postal_code') {
                    //Return the zipcode
                    $address_postcode = $addrComp->long_name;
                    $booking['postcode'] = $address_postcode;
                }
            }
        }
        $addr_latitude = !empty($output->results[0]->geometry->location->lat) ? $output->results[0]->geometry->location->lat : '';
        $addr_longitude = !empty($output->results[0]->geometry->location->lng) ? $output->results[0]->geometry->location->lng : '';
        $this->data['lon'] = $addr_longitude;
        $this->data['lat'] =  $addr_latitude;
        $this->data['salon_users'] = [];
        $salon_users = $this->getSalonUserInRange($addr_latitude, $addr_longitude, 1);
        // dd($salon_users);
        $yourLocationSumPosition = $this->data['lat'] + $this->data['lon'];
        // dd($yourLocationSumPosition); // 200
        $activeSalons = collect($salon_users)->map(function ($item) use ($yourLocationSumPosition) {
            $sumPosition = $item->lat + $item->long;
            return collect($item)->merge(["diff" => abs($yourLocationSumPosition - $sumPosition)])->toArray();
        })->sortBy('diff');
        $result = $this->activeSalonUsersInRange($activeSalons);

        $parent_salon_category = SalonCategory::where('parent_category_id', 0)->get();
        // dd($result);   
        $this->data['salon_users'] = [];
        $this->data['other_salon_users'] = [];
        $psaloncategory = [];
        // dd($result);
        foreach ($result as $users) {
            if ($users['deleted_at'] == null) {
                $usr = User::where('id', $users['id'])->with('salongallaryall', 'profile', 'address', 'workingdays', 'reviews')->first();
                $salon_rating = 0;
                $overall_salon_rating = 0;
                if (count($usr->reviews) > 0) {
                    foreach ($usr->reviews as $review) {
                        $salon_rating += $review->salon_rating;
                    }
                    $salon_rating = round($salon_rating / count($usr->reviews));
                }
                // dd($salon_rating, $atmosphere, $sanitation, $employees, $satisfaction);
                $usr['salon_rating'] = $salon_rating;
                // dd($treatment_id);
                if ($treatment_id == 0) {
                    $this->data['other_salon_users'][] = $usr;
                } else {
                    $tsubcategory = SalonCategory::where('parent_category_id', $treatment_id)->where('user_id', $usr->id)->get();
                    if ($tsubcategory->count()) {
                        $this->data['salon_users'][] = $usr;
                    } else {
                        // $this->data['other_salon_users'][] = $usr;   // only comment this when only those salon have to show which do the category.
                    }
                }
            }
        }
        $this->data['salon_users'] = array_merge($this->data['salon_users'], $this->data['other_salon_users']);
        $this->data['salon_users_count'] = count($this->data['salon_users']);

        // dd($this->data['salon_users']);
        $userForPolygon = User::getSubscribedSalonUser()->get();
        // dd($userForPolygon);
        $this->data['salon_users_for_polygon'] = [];
        $this->data['other_salon_users_for_polygon'] = [];
        foreach ($userForPolygon as $users) {
            // dd($users);
            if ($users['deleted_at'] == null) {
                $usr = User::where('id', $users->id)->with('salongallaryall', 'profile', 'address', 'workingdays', 'reviews')->first();
                // dd($usr);
                $salon_rating = 0;
                $overall_salon_rating = 0;
                if (count($usr->reviews) > 0) {
                    foreach ($usr->reviews as $review) {
                        $salon_rating += $review->salon_rating;
                    }
                    $salon_rating = round($salon_rating / count($usr->reviews));
                }
                // dd($salon_rating, $atmosphere, $sanitation, $employees, $satisfaction);
                $usr['salon_rating'] = $salon_rating;
                // dd($treatment_id);
                if ($treatment_id == 0) {
                    $this->data['other_salon_users_for_polygon'][] = $usr;
                } else {
                    $tsubcategory = SalonCategory::where('parent_category_id', $treatment_id)->where('user_id', $usr->id)->get();
                    if ($tsubcategory->count()) {
                        $this->data['salon_users_for_polygon'][] = $usr;
                    }
                }
            }
        }
        $this->data['salon_users_for_polygon'] = array_merge($this->data['salon_users_for_polygon'], $this->data['other_salon_users_for_polygon']);

        $salon_users_in_range = [];
        if (!empty($this->data['salon_users_for_polygon'])) {
            foreach ($this->data['salon_users_for_polygon'] as $th) {
                $is_in_polygon = 0;

                $therapist_coverages_1 = UserCoverageArea::where('user_id', $th->id)->get();
                $therapist_coverages_last = UserCoverageArea::where('user_id', $th->id)->orderBy('id', 'DESC')->first();

                if (!empty($therapist_coverages_last->polygon_no)) {
                    foreach ($therapist_coverages_1 as $thp_cover) {
                        //for ($i = 0; $i <= $therapist_coverages_last->polygon_no; $i++) {
                        $therapist_coverages = UserCoverageArea::select('lng', 'lat')->where('user_id', $th->id)->where('polygon_no', $thp_cover->polygon_no)->get();
                        $polygon_lat_lng_Arr  = array();

                        foreach ($therapist_coverages as $coverages) {
                            $longitude = $coverages->lng;
                            $latitude  = $coverages->lat;
                            $polygon_lat_lng_Arr[] = $longitude . ' ' . $latitude;
                        }
                        $longitude_x = $addr_longitude; // x-coordinate of the point to test
                        $latitude_y  = $addr_latitude; // y-coordinate of the point to test
                        // echo $point = $longitude_x.' '.$latitude_y;
                        $point = $longitude_x . ' ' . $latitude_y;

                        // dd($point, $polygon_lat_lng_Arr, UserCoverageArea::pointInPolygon($point, $polygon_lat_lng_Arr));
                        //print_r($polygon_lat_lng_Arr);
                        if (UserCoverageArea::pointInPolygon($point, $polygon_lat_lng_Arr)) {
                            $is_in_polygon++;
                        }
                        // echo $is_in_polygon;
                    }
                }
                // dd($is_in_polygon);
                if (!empty($addr_longitude) && !empty($addr_latitude)) {
                    if ($is_in_polygon > 0) {
                        $is_in_polygon = 0;
                        $salon_users_in_range[] = $th;
                    }
                }
            }
        }

        $this->data['salon_users'] = array_merge($this->data['salon_users'], $salon_users_in_range);
        $this->data['salon_users_count'] = count($this->data['salon_users']);
        //dd($this->data['salon_users']);
        if (!empty(Auth::user())) {
            $this->data['cartCount'] = SalonCart::where('user_id', Auth::user()->id)->count();
            $this->data['cartContent'] = $this->cartContent();
        } else {
            $this->data['cartCount'] = 0;
            $this->data['cartContent'] = [];
        }

        $this->data['header_treatments'] = $this->salonHeaderTreatments();
        if (Session::get('salon_booking_date') || Session::get('salon_booking_date') != '') {
            Session::put('selected_salon_therapist', 0);

            return view('schedules::frontend_new.booking.salon_users', $this->data);
        } else {
            return redirect()->back();
        }
    }

    public function activeSalonUsersInRange($result)
    {
        $activeUsers = User::getSubscribedSalonUser()->pluck('id');
        $ids_array = [];
        foreach ($activeUsers as $active) {
            $ids_array[] = $active;
        }
        $matchedObjects = [];
        // dd($result, $activeUsers);
        // Loop through the array of objects and compare with the given IDs
        foreach ($result as $object) {
            if (in_array($object['id'], $ids_array)) {
                $matchedObjects[] = $object;
            }
        }
        // $results
        return $matchedObjects;
    }

    public function salonTherapist($id)
    {
        $therapists = [];
        if (isset($id)) {
            $group = Role::where('name', 'therapist')->first();
            $obj = User::query()->where('salon_id', $id)->whereHas('roles', function ($query) {
                return $query->where('slug', 'therapist');
            })->orderBy('nr_crt', 'asc')->get();
        }


        if ($obj) {
            foreach ($obj as $therapist) {
                $therapists[] = User::where('id', $therapist->id)->with('profile', 'workingdays')->first();
                // dd($therapists);
            }
        }

        // $obj = User::where('salon_id',$id)->where('role',);

        return $therapists;
    }

    public function setSalonTherapsit($key, $salon_id)
    {
        // dd($salon_id);
        if ($key) {
            $data = Session::put('selected_salon_therapist', $key);
        } else {
            $data = Session::put('selected_salon_therapist', 0);
        }


        $date = Session::get('salon_booking_date');
        $Sessionday = Carbon::createFromFormat('d-m-Y', $date)->format('l');
        // dd($therapist_key);

        $this->data['therapist_key'] = $key;
        $this->data['salon_therapist'] = $this->salonTherapist($salon_id);
        // dd($this->data['salon_therapist']);
        foreach ($this->data['salon_therapist'][$key]->workingdays as $weekday) {
            if ($weekday->name == $Sessionday) {
                // dd("here");
                $startTime = $weekday->bo_start;
                $endTime = $weekday->bo_end;
            }
        }

        $this->data['salon_available_slots'] = $this->availableSlotOnSessionDate($startTime, $endTime, $this->data['salon_therapist'][$key]->id);
        // dd($this->data['salon_available_slots']);
        // return "Success";
        return view('schedules::frontend_new.booking.salon_slots', $this->data);
        // return response()->json([
        //     'success' => true,
        //     'data' => $data,
        //     'availabe_slots' => $$this->data['salon_available_slots'],
        //     // 'count' => $cartCount
        // ]);
    }

    public function availableSlotOnSessionDate($startTime, $endTime, $thid)
    {
        $date = Session::get('salon_booking_date');
        $booking_date = Carbon::createFromFormat('d-m-Y', $date)->format('Y-m-d');
        // dd($thid);

        $booked_time = TherapistBooking::where('therapist_id', $thid)->where('date', $booking_date)->get();
        // dd($booked_time);
        $booked_therapist_time = [];
        $booked_array = [];
        $buffer = '30';
        $add_min = $buffer * 60;
        foreach ($booked_time as $time) {
            $start = strtotime($time->hour);
            $i = 0;
            $n = floor($time->duration / $buffer);
            while ($i != $n) {
                $booked_array[] = date("H:i", $start);
                $start += $add_min;
                $i++;
            }
            // dd($booked_array);
        }

        $AddMins  = $buffer * 60;
        // dd($AddMins, $startTime, $endTime);
        $ReturnArray = array(); // Define output
        $StartTime    = strtotime($startTime); //Get Timestamp
        $EndTime      = strtotime($endTime); //Get Timestamp


        // dd($AddMins, $StartTime, $EndTime);
        // dd($startTime <= $endTime);
        while ($StartTime <= $EndTime) //Run loop
        {
            // dd("here");
            $ReturnArray[] = date("H:i", $StartTime);
            $StartTime += $AddMins; //Endtime check
            // dd($ReturnArray);
        }

        // dd($ReturnArray);
        $array = array_diff($ReturnArray, $booked_array);
        // dd($array);
        return $array;
    }

    public function salonPreview($id)
    {
        // dd(Session::all());
        $this->data['salon_id'] = $id;
        $therapist_key = Session::get('selected_salon_therapist');
        if (!$therapist_key) {
            Session::put('selected_salon_therapist', 0);
            $therapist_key = Session::get('selected_salon_therapist');
        }
        $this->data['therapist_key'] = $therapist_key;
        // dd($therapist_key);
        $date = Session::get('salon_booking_date');
        // dd($date);
        $this->data['salon_booking_date'] = $date;
        $this->data['salon_booking_time'] = Session::get('salon_booking_time');

        $salon = User::where('id', $id)->with('salongallaryall', 'profile', 'address', 'workingdays')->first();
        $this->data['salon_therapist'] = $this->salonTherapist($id);
        // dd($salon);
        if ($salon == null) {
            return redirect('/');
        }

        if (count($salon->address) == 0) {
            return redirect()->back();
        }
        if (count($salon->address) != 0) {
            foreach ($salon->address as $address) {
                if ($address->is_main) {
                    $add = $address->address . ' ' . $address->county . ' ' . $address->postcode;
                }
            }
            // $add = "Gielly Green Boutique Salon, 42-44 George St, London W1U 7ES, UK";
            //Formatted address
            $formattedAddr = str_replace(' ', '+', $add);
            // dd($formattedAddr);
            //Send request and receive json data by address
            $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . config('googlemaps.key'));
            $output = json_decode($geocodeFromAddr);
            // dd($output);
            if (!empty($output)) {
                $addressComponents = $output->results[0]->address_components;
                foreach ($addressComponents as $addrComp) {
                    if ($addrComp->types[0] == 'postal_code') {
                        //Return the zipcode
                        $address_postcode = $addrComp->long_name;
                        $booking['postcode'] = $address_postcode;
                    }
                }
            }
            $addr_latitude = !empty($output->results[0]->geometry->location->lat) ? $output->results[0]->geometry->location->lat : '';
            $addr_longitude = !empty($output->results[0]->geometry->location->lng) ? $output->results[0]->geometry->location->lng : '';
            $this->data['lon'] = $addr_longitude;
            $this->data['lat'] =  $addr_latitude;
        }

        // dd($lang);
        $this->data['salon'] = $salon;
        $this->data['salon_category'] = SalonCategory::where('parent_category_id', 0)->get();
        $this->data['all_sub_category'] = SalonCategory::with('duration')->where('parent_category_id', '!=', 0)->where('user_id', $id)->get();
        // dd($this->data);
        foreach ($this->data['salon_category'] as $category) {
            $subcategory[$category->name] = SalonCategory::with('duration')->where('parent_category_id', $category->id)->where('user_id', $id)->get();
        }
        $this->data['subcategory'] = $subcategory;
        $this->data['cartCount'] = SalonCart::where('user_id', Auth::user()->id)->count();
        $this->data['cartContent'] = $this->cartContent();
        // dd($this->data);
        $day = Carbon::now();
        $day = $day->toArray();
        foreach ($day as $key => $d) {
            // dd($day);
            if ($key == "dayOfWeek") {
                $this->data['today'] = $d;
            }
        }
        // dd($this->data['today']);
        $Sessionday = Carbon::createFromFormat('d-m-Y', $date)->format('l');
        // dd($therapist_key);
        // dd($this->data['salon_therapist'][$therapist_key]->workingdays, $Sessionday);
        if ($salon->workingdays) {
            foreach ($this->data['salon_therapist'][$therapist_key]->workingdays as $weekday) {
                if ($weekday->name == $Sessionday) {
                    // dd("here");
                    $startTime = $weekday->bo_start;
                    $endTime = $weekday->bo_end;
                }
            }
        }
        // dd($startTime, $endTime);
        $this->data['salon_available_slots'] = $this->availableSlotOnSessionDate($startTime, $endTime, $this->data['salon_therapist'][$therapist_key]->id);
        // dd($this->data['salon_available_slots']);
        return view('schedules::frontend_new.booking.salon_details', $this->data);
    }

    public function salonDetails($id)
    {
        // dd(Session::all());
        $booking = Session::get('booking');
        $this->data['booking'] = $booking;
        // dd($booking);                     
        // if(Auth::check()) {
        //     if(Auth::user()->id != $id) {
        //         if(!isset($booking['address'])){
        //            return redirect('/')->withErrors(['msg' => 'Please enter your postal code/address']);
        //         }
        //     }
        // } else {
        //     if(!isset($booking['address'])){
        //        return redirect('/')->withErrors(['msg' => 'Please enter your postal code/address']);
        //     }
        // }
        $this->data['lon'] = 0;
        $this->data['lat'] =  0;
        // dd($booking['address']);
        $therapist_key = Session::get('selected_salon_therapist');
        if (!$therapist_key) {
            Session::put('selected_salon_therapist', 0);
            $therapist_key = Session::get('selected_salon_therapist');
        }
        $this->data['therapist_key'] = $therapist_key;
        // dd($therapist_key);
        $date = Session::get('salon_booking_date');
        $this->data['salon_booking_date'] = $date;
        $this->data['salon_booking_time'] = Session::get('salon_booking_time');

        $salon = User::where('name_slug', $id)->with('salongallaryall', 'profile', 'address', 'workingdays', 'reviews')->first();
        $this->data['salon_id'] = $salon->id;
        $id = $salon->id;
        if (!isset($salon)) {
            return redirect('/');
        }
        $salon_rating = 0;
        $atmosphere = 0;
        $sanitation = 0;
        $employees = 0;
        $satisfaction = 0;
        $overall_salon_rating = 0;
        if (count($salon->reviews) > 0) {
            foreach ($salon->reviews as $review) {
                $salon_rating += $review->salon_rating;
                $atmosphere += $review->atmosphere;
                $sanitation += $review->sanitation;
                $employees += $review->employees;
                $satisfaction += $review->satisfaction;
            }
            $salon_rating = round($salon_rating / count($salon->reviews));
            $atmosphere = round($atmosphere / count($salon->reviews));
            $sanitation = round($sanitation / count($salon->reviews));
            $employees = round($employees / count($salon->reviews));
            $satisfaction = round($satisfaction / count($salon->reviews));
        }
        // dd($salon_rating, $atmosphere, $sanitation, $employees, $satisfaction);
        $this->data['salon_rating'] = $salon_rating;
        $this->data['atmosphere'] = $atmosphere;
        $this->data['sanitation'] = $sanitation;
        $this->data['employees'] = $employees;
        $this->data['satisfaction'] = $satisfaction;


        $this->data['salon_therapist'] = $this->salonTherapist($id);
        // dd($salon);
        if ($salon == null) {
            return redirect('/');
        }

        if (count($salon->address) == 0) {
            return redirect()->back();
        }
        if (!empty($booking['address'])) {
            // foreach($salon->address as $address){
            //     if($address->is_main){
            //         $add = $address->address.' '.$address->county.' '.$address->postcode;        
            //     }

            // }
            $add = $booking['address'];
            //Formatted address
            $formattedAddr = str_replace(' ', '+', $add);
            // dd($formattedAddr);
            //Send request and receive json data by address
            $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . config('googlemaps.key'));
            $output = json_decode($geocodeFromAddr);
            // dd($output);
            if (!empty($output)) {
                $addressComponents = $output->results[0]->address_components;
                foreach ($addressComponents as $addrComp) {
                    if ($addrComp->types[0] == 'postal_code') {
                        //Return the zipcode
                        $address_postcode = $addrComp->long_name;
                        $booking['postcode'] = $address_postcode;
                    }
                }
            }
            $addr_latitude = !empty($output->results[0]->geometry->location->lat) ? $output->results[0]->geometry->location->lat : '';
            $addr_longitude = !empty($output->results[0]->geometry->location->lng) ? $output->results[0]->geometry->location->lng : '';
            $this->data['lon'] = $addr_longitude;
            $this->data['lat'] =  $addr_latitude;
        }

        // dd($lang);

        if (!$salon->lat || !$salon->long) {
            if (count($salon->address) > 0) {
                foreach ($salon->address as $saddress) {

                    if ($saddress->is_main == 1) {
                        // dd($saddress->address);
                        $add = $saddress->county . '+' . $saddress->postcode . ',uk';
                        $formattedAddr = str_replace(' ', '+', $add);
                        // dd($formattedAddr);
                        //Send request and receive json data by address
                        $geocodeFromAddr = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . config('googlemaps.key'));
                        $output = json_decode($geocodeFromAddr);
                        // dd($output);
                        if (!empty($output)) {
                            $addressComponents = $output->results[0]->address_components;
                            foreach ($addressComponents as $addrComp) {
                                if ($addrComp->types[0] == 'postal_code') {
                                    //Return the zipcode
                                    $address_postcode = $addrComp->long_name;
                                    $booking['postcode'] = $address_postcode;
                                }
                            }
                        }
                        $addr_latitude = !empty($output->results[0]->geometry->location->lat) ? $output->results[0]->geometry->location->lat : '';
                        $addr_longitude = !empty($output->results[0]->geometry->location->lng) ? $output->results[0]->geometry->location->lng : '';
                        $salon->long = $addr_longitude;
                        $salon->lat = $addr_latitude;
                        User::where('id', $salon->id)->update([
                            'lat' => $addr_latitude,
                            'long' => $addr_longitude
                        ]);
                    }
                }
            }
            // dd($salon);
        }
        $this->data['salon'] = $salon;
        $parent_salon_category = SalonCategory::where('parent_category_id', 0)->get();
        $psaloncategory = [];
        foreach ($parent_salon_category as $category) {
            $tsubcategory = SalonCategory::where('parent_category_id', $category->id)->where('user_id', $id)->get();
            if ($tsubcategory->count()) {
                $psaloncategory[] = $category;
            }
        }
        $this->data['salon_category'] = $psaloncategory;
        // dd($this->data['salon_category']);
        $this->data['all_sub_category'] = SalonCategory::with('duration')->where('parent_category_id', '!=', 0)->where('user_id', $id)->get();
        // dd($this->data['salon_category']);
        $subcategory = [];
        foreach ($this->data['salon_category'] as $category) {
            // dd($category);
            $subcategory[$category->id] = SalonCategory::with('duration')->where('parent_category_id', $category->id)->where('user_id', $id)->get();
        }
        // dd($subcategory);
        $this->data['cartCount'] = 0;
        $this->data['cartContent'] = [];
        $this->data['subcategory'] = $subcategory;
        if (Auth::user()) {
            $this->data['cartCount'] = SalonCart::where('user_id', Auth::user()->id)->count();
            $this->data['cartContent'] = $this->cartContent();
        }

        // dd($this->data);
        $day = Carbon::now();
        $day = $day->toArray();
        foreach ($day as $key => $d) {
            // dd($day);
            if ($key == "dayOfWeek") {
                $this->data['today'] = $d;
            }
        }
        // dd($date);
        // $Sessionday = Carbon::createFromFormat('d-m-Y', $date)->format('l');
        if ($date == "AnyDate" || $date == "") {
            $date =  Carbon::today()->toDateString();
            $date = Carbon::parse($date)->format('d-m-Y');
            // dd($date->format('l'));
            $Sessionday = Carbon::createFromFormat('d-m-Y', $date)->format('l');

            Session::put('salon_booking_date', $date);
            // dd($date);
            $this->data['salon_booking_date'] = $date;
            // dd($date, $Sessionday);
        } else {
            $Sessionday = Carbon::createFromFormat('d-m-Y', $date)->format('l');
            // dd($Sessionday);
        }
        // dd($Sessionday);
        // dd($this->data['salon_therapist'][$therapist_key]->workingdays, $Sessionday);
        // if($salon->workingdays && $this->data['salon_therapist']){
        //     foreach($this->data['salon_therapist'][$therapist_key]->workingdays as $weekday){
        //         if($weekday->name == $Sessionday){
        //             // dd("here");
        //             $startTime = $weekday->bo_start;
        //             $endTime = $weekday->bo_end;
        //         }
        //     }
        // }
        // dd($startTime, $endTime);
        // $this->data['salon_available_slots'] = $this->availableSlotOnSessionDate($startTime, $endTime, $this->data['salon_therapist'][$therapist_key]->id);
        // dd($this->data);
        return view('schedules::frontend_new.booking.salon_details', $this->data);
    }

    public function getSubCategory(Request $request)
    {
        // dd($id, $salon_id);
        // dd($request->all());
        $this->data['key'] = $request->id;
        $this->data['salon_id'] = $request->salon_id;
        $this->data['category'] = SalonCategory::with('duration')->where('parent_category_id', $request->id)->where('user_id', $request->salon_id)->get();
        if (count($this->data['category'])) {
            return view('schedules::frontend_new.booking.salon_subcategory', $this->data);
        } else {
            $this->data['category'] = SalonCategory::with('duration')->where('id', $request->id)->get();
            return view('schedules::frontend_new.booking.salon_subcategory', $this->data);
        }
        // dd($this->data);
        // return view('schedules::frontend_new.booking.salon_subcategory',$this->data);
    }

    public function getCategory(Request $request)
    {
        // dd($request->all());
        $this->data['category'] = SalonCategory::with('duration')->where('parent_category_id', $request->id)->where('user_id', $request->salon_id)->get();
        if (count($this->data['category'])) {
            return view('schedules::frontend_new.booking.salon_category', $this->data);
        } else {
            $this->data['category'] = SalonCategory::with('duration')->where('id', $request->id)->get();
            return view('schedules::frontend_new.booking.salon_category', $this->data);
        }
    }


    public function treatmentService($id)
    {
        $param = request('search');
        $parentCategory = ServiceType::whereIn('id', [$id])->get();
        // dd($parentCategory);
        $this->data['parent_category'] = $parentCategory;
        if ($parentCategory[0]->parent_category_id == 0) {
            if ($parentCategory[0]->service_type_id == 1) {
                $this->data['old_service_type_id'] = 1;
            } else if ($parentCategory[0]->service_type_id == 2) {
                $this->data['old_service_type_id'] = 2;
            } else {
                $this->data['old_service_type_id'] = 3;
            }
        } else {
            $this->data['old_parent_category_id'] = $parentCategory[0]->parent_category_id;
        }
        // dd($this->data);
        if ($param) {
            $this->data['search'] = $param;
            $this->data['services'] = ServiceType::whereIn('parent_category_id', [$id])->where('name', 'LIKE', '%' . $param . '%')->get();
        } else {
            $this->data['services'] = ServiceType::whereIn('parent_category_id', [$id])->get();
        }
        $category = ServiceType::whereIn('parent_category_id', [$id])->get();
        // $this->data['trID'] = $id;
        if (count($category) == 0) {
            $treatment_detail = ServiceType::whereIn('id', [$id])->get();
            return response()->json($treatment_detail, 200);
            //  return redirect()->back()->with('treatment_detail', $treatment_detail);
        } else {
            return view('schedules::frontend_new.booking.service_type_sub_category', $this->data);
        }
    }

    public function getTherapistModalInfo(Request $request)
    {
        if ($request->id) {
            $user = $this->book->salon_therapist_info($request->id);
            // dd($user);
            $therapist = $user['data'];
            $services = $user['services'];
            // $therapist = User::with('profile', 'workingdays')->where('id', $request->id)->first();
            // dd($therapist); 
            //return response
            $json['partial'] = view('schedules::frontend_new.booking.salon_therapist_modal', compact('therapist', 'services'))->render();
            //render page
            return json_encode($json);
        } else {
            return "false";
        }
    }

    public function setDate(Request $request)
    {
        // dd($request->all());
        // $date = $request->date;
        if ($request->date == "AnyDate") {
            $date = $request->date;
            Session::put('salon_booking_date', $date);
        } else {
            $date = date('d-m-Y', strtotime($request->date));
            Session::put('salon_booking_date', $date);
        }
        $message = [
            'success' => true,
            'date' => $date,
        ];

        //return response
        return response($message, 200);
        // return $date;
        // dd("here");
    }

    public function setTime(Request $request)
    {
        // dd($request->all());
        // $date = $request->date;
        $time = $request->time;
        // dd($time);
        Session::put('salon_booking_time', $time);
        $message = [
            'success' => true,
            'time' => $time,
        ];

        //return response
        return response($message, 200);
        // return $date;
        // dd("here");
    }

    public function setTreatment(Request $request)
    {
        // dd($request->all());
        $treatment = SalonCategory::with('duration')->where('id', $request->id)->first();
        // dd($treatment);
        Session::put('salon_booking_treatment_name', $treatment->name);
        Session::put('salon_booking_treatment_id', $treatment->id);

        $salon_booking_treatment_name = Session::get('salon_booking_treatment_name');
        // dd($salon_booking_treatment_name);

        $message = [
            'success' => true,
            'treatment' => $treatment,
        ];

        //return response
        return response($message, 200);
    }

    public function get_treatment_info(Request $request)
    {
        // dd($request->all());
        // dd("inside get treatment info");
        $booking = Session::get('booking');
        if (isset($booking['duration'])) {
            $booking['duration'] = 0;
        }
        Session::put('booking', $booking);
        $this->data['treatment'] = null;
        $category = ServiceType::whereIn('parent_category_id', [$request->trID])->get();
        $this->data['duration'] = [];
        if (count($category) == 0) {
            $treatment = ServiceType::whereIn('id', [$request->trID])->get();

            $json['treatment'] = $treatment;
            foreach ($treatment as $treatment) {
                if ($treatment->is_massage == 1) {
                    $duration = ServiceDuration::whereIn('is_massage_duration', [1])->get();
                    $this->data['duration'] = $duration;
                } else {
                    $duration = ServiceDuration::whereIn('sub_category_id', [$treatment->id])->get();
                    $this->data['duration'] = $duration;
                }
            }
            // dd($this->data['duration']);
            if (count($this->data['duration']) == 1) {

                $obj = ServiceType::where('id', $request->trID)->first();
                $booking = (array)Session::get('booking');
                $booking['massage'] = $obj ? $obj->id : null;
                Session::put('booking', $booking);

                $json['duration'] = $this->data['duration'];
                $booking = (array)Session::get('booking');
                $booking['duration'] = $this->data['duration'][0]->id;
                unset($booking['hour']);
                Session::put('booking', $booking);
            }
            $this->data['treatment'] = $json['treatment'];
            $json['count'] = count($category);
            $json['partial'] = view('schedules::frontend_new.booking.partial_treatment_modal_info', $this->data)->render();
            return json_encode($json);
        } else {
            $this->data['count'] = count($category);
            return response()->json($this->data, 200);
        }
    }

    public function get_treatment_duration_info(Request $request)
    {
        // dd(Session::get('booking'));
        $treatment = ServiceType::whereIn('id', [$request->trID])->get();
        $this->data['treatment'] = $treatment;
        foreach ($treatment as $treatment) {
            if ($treatment->is_massage == 1) {
                $duration = ServiceDuration::whereIn('is_massage_duration', [1])->get();
                $this->data['duration'] = $duration;
            } else {
                $duration = ServiceDuration::whereIn('sub_category_id', [$treatment->id])->get();
                $this->data['duration'] = $duration;
            }
        }
        $json['treatment'] = $treatment;
        $json['partial'] = view('schedules::frontend_new.booking.partial_treatment_duration_modal_info', $this->data)->render();
        return json_encode($json);
    }


    public function addCategoryToSession(Request $request)
    {
        if (!$request->itemId) {
            return redirect()->back();
        }
        $subcategory = SalonCategory::with('duration')->where('id', $request->itemId)->where('parent_category_id', '!=', 0)->first();
        $data = [
            'user_id' => Auth::user() ? Auth::user()->id : null,
            'subcategory_id' => $subcategory->id,
            'duration_id' => $subcategory->duration->id,
            'salon_id' => $subcategory->user_id,
        ];
        $newData = (object) $data;
        Session::put('cartItem', $newData);
        Session::put('categoryIdForCart', $request->itemId);
        return response()->json([
            'success' => true,
        ]);
    }
    //Salon Cart
    // public function addToCart(Request $request){
    //     if(!$request->itemId){
    //         return redirect()->back();
    //     }
    //     $subcategory = SalonCategory::with('duration')->where('id',$request->itemId)->where('parent_category_id', '!=' ,0)->first();
    //     $data = [
    //         'user_id' => Auth::user()->id,
    //         'subcategory_id' => $subcategory->id,
    //         'duration_id' => $subcategory->duration->id,
    //         'salon_id' => $subcategory->user_id,
    //     ];
    //     $cart = SalonCart::create($data);
    //     $cartCount = SalonCart::where('user_id', Auth::user()->id)->count(); 
    //     Session::put('cartItem', $cart);
    //     return response()->json([
    //         'success' => true,
    //         'data' => $cart,
    //         'count' => $cartCount
    //     ]);
    // }
    //Salon Cart
    public function addToCart($itemId, $thId, $date, $hour)
    {
        \Cart::clear();
        if (Auth::check()) {
            if (!$itemId) {
                return redirect()->back();
            }
            // Get the current time
            $currentDateTime = Carbon::now();
            $subcategory = SalonCategory::with('duration')->where('id', $itemId)->where('parent_category_id', '!=', 0)->first();
            $data = [
                'user_id' => Auth::user()->id,
                'subcategory_id' => $subcategory->id,
                'duration_id' => $subcategory->duration->id,
                'salon_id' => $subcategory->user_id,
                'therapist_id' => $thId,
                'booking_date' => $date,
                'booking_time' => $hour
            ];
            $cart = SalonCart::create($data);

            $sessionData = [
                'basket_item_id' => $cart->id,
                'session_id' => '',
                'user_id' => Auth::user()->id,
                'therapist_id' => $thId,
                'reserved_until' => $currentDateTime->addMinutes(10)->toDateTimeString(),
                'date' => Carbon::parse($date)->format('Y-m-d'),
                'hour' => $hour,
                'duration_id' => $subcategory->duration->id,
                'duration_name' => $subcategory->duration->name,
                'duration_min' => $subcategory->duration->duration,
            ];

            // dd($sessionData) ;
            BasketTherapist::create($sessionData);
            $cartCount = SalonCart::where('user_id', Auth::user()->id)->count();
            Session::put('cartItem', $cart);
            return response()->json([
                'success' => true,
                'data' => $cart,
                'count' => $cartCount
            ]);
        } else {
            return redirect('/login');
        }
    }

    public function deleteFromCart(Request $request)
    {
        if (!$request->itemId) {
            return redirect()->back();
        }
        $cartData = SalonCart::where('user_id', Auth::user()->id)->where('subcategory_id', $request->itemId)->first();
        $itemId = $request->itemId;
        $json['cart'] = SalonCart::where('user_id', Auth::user()->id)->where('subcategory_id', $request->itemId)->delete();
        BasketTherapist::where('user_id', Auth::user()->id)->where('basket_item_id', $cartData->id)->delete();
        $json['cartCount'] = SalonCart::where('user_id', Auth::user()->id)->count();
        $json['cartContent'] = $this->cartContent();
        // dd($json);
        $json['partial'] = view('schedules::frontend_new.booking.select_button_for_sub_category', compact('itemId'))->render();
        $json['partialCart'] = view('schedules::frontend_new.booking.partial_cart_for_header', $json)->render();

        return json_encode($json);
        // return response()->json([
        //     'success' => true,
        //     'data' => $cart,
        //     'count' => $cartCount
        // ]);
    }

    public function deleteFromHeader(Request $request)
    {
        if (!$request->itemId) {
            return redirect()->back();
        }
        $itemId = $request->itemId;
        // dd(Auth::user()->id);
        $cartData = SalonCart::where('id', $itemId)->first();
        $json['cart'] = SalonCart::where('id', $itemId)->delete();
        BasketTherapist::where('user_id', Auth::user()->id)->where('basket_item_id', $cartData->id)->delete();
        $json['cartCount'] = SalonCart::where('user_id', Auth::user()->id)->count();
        $json['cartContent'] = $this->cartContent();
        // dd($json);
        $json['partial'] = view('schedules::frontend_new.booking.select_button_for_sub_category', compact('itemId'))->render();
        $json['partialCart'] = view('schedules::frontend_new.booking.partial_cart_for_header', $json)->render();

        return json_encode($json);
        // return response()->json([
        //     'success' => true,
        //     'data' => $cart,
        //     'count' => $cartCount
        // ]);
    }

    public function deleteCartFromCheckout(Request $request)
    {
        if (!$request->itemId) {
            return redirect()->back();
        }
        $itemId = $request->itemId;
        $json['cart'] = SalonCart::where('id', $request->itemId)->delete();

        return response()->json([
            'success' => true,
        ]);
    }

    public function cartContent()
    {
        if (!Auth::user()) {
            $cartDetails = [];
            return $cartDetails;
        }
        $cart = SalonCart::where('user_id', Auth::user()->id)->get();
        $cartDetails = [];
        foreach ($cart as $c) {

            $get_date = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $c->created_at)->addMinutes(10)->format('Y-m-d H:i:s');
            $reserved_until = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $get_date);
            $reserved_ttl = $reserved_until->diffInSeconds(null, false);
            $reserved_ttl = \Carbon\Carbon::now()->diffInSeconds($reserved_until, false);
            if ($reserved_ttl <= 0) {
                SalonCart::where('id', $c->id)->delete();
                return;
            }
            $details = SalonCategory::with('duration')->where('id', $c->subcategory_id)->first();
            $details->setAttribute('cart_id', $c->id);
            $parentCategory = SalonCategory::where('id', $details->parent_category_id)->first();
            $parentCategory1 = SalonCategory::where('id', $parentCategory->parent_category_id)->first();
            if (empty($parentCategory1->image)) {
                $parentCategory2 = SalonCategory::where('id', $parentCategory1->parent_category_id)->first();
                $details->setAttribute('parent_image', $parentCategory2->image);
                $details->setAttribute('parent_icon', $parentCategory2->icon);
            } else {
                $details->setAttribute('parent_image', $parentCategory1->image);
                $details->setAttribute('parent_icon', $parentCategory1->icon);
            }

            // dd();

            $cartDetails[] = $details;
        }
        // die;

        return $cartDetails;
    }

    public function salonHeaderTreatments()
    {
        $header_treatments =  SalonCategory::where('parent_category_id', 0)->where('is_header', 1)->pluck('name', 'id');
        return $header_treatments;
    }

    public function get_salon_therapists()
    {
        $booking = Session::get('booking');

        $results = $this->book->salontherapists();

        $this->data['results'] = $results;
        $this->data['selected'] = (array)@$booking['selected_therapists'];
        // dd($this->data['results']);
        return view('schedules::frontend_new.booking.partial_all_salon_therapists_list', $this->data);
    }

    // get salon therapist count

    public function get_salon_therapists_count()
    {
        $booking = Session::get('booking');

        $results = $this->book->therapists();

        $this->data['results'] = $results;
        $this->data['selected'] = (array)@$booking['selected_therapists'];
        if (!isset($results['unavailable']) && !isset($results['available'])) {
            return $count = 0;
        } else {
            return $count = 1;
        }
    }

    public function salon_booking()
    {
        $booking = Session::get('booking');
        //reset booking keys for massage me later
        if (isset($booking['checkArrivalTime']) and $booking['checkArrivalTime'] == true) {
            unset($booking['hour']);
            unset($booking['selected_therapists']);
            $booking['checkArrivalTime'] = false;
            Session::put('booking', $booking);
        }
        // $this->data['cartCount'] = SalonCart::where('user_id', Auth::user()->id)->count();
        // $this->data['cartContent'] = $this->cartContent();

        $all_days = $this->book->available_30_days();
        //create data array
        $this->data = [
            'meta_title' => trans("schedules::booking.book_later_meta_title"),
            'meta_description' => trans("schedules::booking.book_later_meta_description"),
            'meta_keywords' => trans("schedules::booking.book_later_meta_keywords"),
            'booking' => $this->session_booking_info(),
            'fp' => $this->get_focal_points(),
            'massage_info' => $this->get_massage_info(),
            'selected_date' => isset($booking['date']) ? $booking['date'] : date('Y-m-d'),
            'all_days' => $all_days,
            'cartCount' => Auth::user() ? SalonCart::where('user_id', Auth::user()->id)->count() : 0,
            'cartContent' => $this->cartContent()
        ];
        //render page
        return view('schedules::frontend_new.booking.salon_therapist', $this->data);
    }

    public function getSubCategoryOnSalonDetails(Request $request)
    {
        // dd("here", $request->all());

        $this->data['salon_user'] = User::with('profile')->where('id', $request->salon_id)->first();
        // dd($salon_user);
        $salon_treatment = SalonCategory::with(['subCategory' => function ($q) {
            $query = $q->select('salon_categories.id as subsubcate_id', 'salon_categories.*')->with('duration')->get();
            $query_array = $q->select('salon_categories.id as subsubcate_id', 'salon_categories.*')->pluck('id');
            $subcategory_id = $query_array;
            $q->with(['subsubCategory' => function ($sq) use ($subcategory_id) {
                $sq->select('salon_categories.id as subsubsubcate_id', 'salon_categories.*')->with('duration')->whereIn('parent_category_id', $subcategory_id);
            }]);
        }])->where('parent_category_id', $request->id)->where('user_id', $request->salon_id)->get();
        // dd($salon_treatment);
        $this->data['salon_categories'] = $salon_treatment;
        $collection = $salon_treatment->sortBy('price');
        // dd($this->data);
        return view('schedules::frontend_new.booking.salon_category', $this->data);
    }

    public function getSalonServiceModal(Request $request)
    {
        $this->data['category'] = SalonCategory::where('id', $request->id)->first();
        return view('schedules::frontend_new.booking.show_button_modal', $this->data);
    }

    public function get_salon_therapist_info(Request $request)
    {
        $this->data['availability'] = false;
        $this->data['therapist'] = null;
        $this->data['selected_date'] = '';
        $this->data['selectedhour'] = '';

        $booking = (array)Session::get('booking');
        $session = Session::all();
        // dd($booking);
        if (isset($request->thID) && !empty($request->thID)) {
            $therpist = $this->book->salon_therapist_info($request->thID);
            $this->data['therapist'] = $therpist;
            // dd($therpist['data']->therapistreview);
        }
        if (isset($request->availability) && !empty($request->availability)) {
            $this->data['availability'] = true;
        }
        $this->data['selected'] = (array)@$booking['selected_therapists'];
        $this->data['all_days'] = $this->book->salon_available_30_days();

        // if(isset($booking['date']) && !empty($booking['date']))
        // {
        //     $this->data['selected_date'] = $booking['date'];
        // }

        // if(isset($booking['hour']) && !empty($booking['hour']))
        // {
        //     $this->data['selectedhour'] = $booking['hour'];
        // }

        if (isset($session['cartItem']) && !empty($session['cartItem'])) {
            $this->data['massage'] = SalonCategory::whereIn('id', [$session['cartItem']->subcategory_id])->get();
        }
        $json['partial'] = view('schedules::frontend_new.booking.partial_salon_therapist_modal_info', $this->data)->render();
        $json['availability'] = $this->data['availability'];
        $json['selectedhour'] = $this->data['selectedhour'];
        $json['selected_date'] = $this->data['selected_date'];
        //render page
        return json_encode($json);
    }

    public function get_salon_therapist_hours(Request $request)
    {

        if (!$request->date) {
            $date = date('Y-m-d');
        } else {
            $date = $request->date;
        }
        Session::set('therapists_booking_info.' . $request->thID . '.date', $date);

        $booking = Session::get('booking');
        $session = Session::all();

        $duration = SalonServiceDuration::find($session['cartItem']->duration_id)->duration;
        // dd($duration);
        $hours = $this->book->salon_th_hours($date, $request->thID);
        // dd($hours);
        $therapist = User::OfTherapists()
            ->where('id', $request->thID)
            ->first();

        $dateC = Carbon::createFromFormat('Y-m-d', $date)->startOfDay();
        $weekday = date('w', strtotime($dateC->format('Y-m-d')));
        $twd = $therapist->workingdays()->where('dayoff', 0)->where('weekday', $weekday)->first();
        // dd($hours);
        if ($hours) {
            foreach ($hours as $k => $hour) {
                if (isset($hour['hour'])) {
                    $curr_hour_plus_duration = strtotime('+' . $duration . ' minutes', strtotime($hour['hour']));
                    // dd($hour['available'] == 1);
                    if (!$hour['available']) {
                        unset($hours[$k]);
                    }
                    if ($twd && ($curr_hour_plus_duration > strtotime($twd->bo_end_raw))) {
                        unset($hours[$k]);
                    }
                } else {
                    unset($hours[$k]);
                }
            }
        }

        // dd($hours);
        $this->data['hours'] = $hours;
        $this->data['selectedtherapist'] = $request->thID;
        $this->data['selectedtherapistdate'] = $date;
        $this->data['selectedhour'] = isset($booking['hour']) ? $booking['hour'] : null;

        //return view partial
        return view('schedules::frontend_new.booking.partial_salon_therapist_hours', $this->data)->render();
    }


    public function set_salon_therapist(Request $request)
    {

        $booking = Session::get('booking');
        $itemIdForCart = Session::get('categoryIdForCart');
        // dd($allSession);

        if ($request->thID) {
            //therapist key through session
            $salon_thid = Session::set('selected_salon_therapist', $request->thID);
            $date = Carbon::createFromFormat('Y-m-d', $booking['date'])->format('d-m-Y');
            Session::set('salon_booking_date', $date);
            Session::set('salon_booking_time', $booking['hour']);
        }

        if ($itemIdForCart && $request->thID)
            $this->addToCart($itemIdForCart, $request->thID, $booking['date'], $booking['hour']);


        if (!isset($booking['therapists']) || !isset($booking['therapists_opt']) || !isset($booking['type'])) {
            $booking['therapists'] = 1;
            $booking['therapists_opt'] = "1_th";
            $booking['type'] = "1 therapist";
        }

        //         //if one of mandatory fields is missing, return empty array results
        //         $mandatory_fields = ['postcode','duration','date','therapists'];
        //         foreach($mandatory_fields as $field){
        //             if (!isset($booking[$field]))
        //                 return response(['message'=>'You must select postcode, massage duration, type of massage, date of masage and number of therapists'],403);
        //         } //endforeach

        //         if (!isset($booking['selected_therapists']))
        //             $booking['selected_therapists'] = [];


        //         if (in_array($request->thID,$booking['selected_therapists'])){
        //             //unmark therapist
        //             $key = array_search($request->thID, $booking['selected_therapists']);
        //             if(!is_null($key))
        //                 unset($booking['selected_therapists'][$key]);
        //         }
        //         elseif (count($booking['selected_therapists']) < $booking['therapists']){
        //             //mark the therapist as selected
        //             @$booking['selected_therapists'][] = $request->thID;
        //         }
        //         else{
        //             //change the last therapist
        //             $last = count($booking['selected_therapists'])-1;
        //             $booking['selected_therapists'][$last] = $request->thID;
        //         }

        // //        session(['booking' => $booking]);
        //         Session::put('booking',$booking);

        //         //dd($booking);
        //         //return success response
        return response(['message' => 'success'], 200);
    }


    /**
     * Set therapist modal
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function set_salon_therapist_modal(Request $request)
    {
        $itemIdForCart = Session::get('categoryIdForCart');
        if ($request->date) {
            $date = Carbon::createFromFormat('Y-m-d', $request->date)->format('d-m-Y');
            Session::set('booking.date', $request->date);
            //date & time through session
            Session::set('salon_booking_date', $date);
        }

        if ($request->hour) {
            Session::set('booking.hour', $request->hour);
            Session::set('salon_booking_time', $request->hour);
        }
        $booking = Session::get('booking');

        if ($itemIdForCart && $request->thID)
            $this->addToCart($itemIdForCart, $request->thID, $request->date, $request->hour);

        if ($request->thID) {
            //therapist key through session
            $salon_thid = Session::set('selected_salon_therapist', $request->thID);
        }


        if (!isset($booking['therapists']) || !isset($booking['therapists_opt']) || !isset($booking['type'])) {
            $booking['therapists'] = 1;
            $booking['therapists_opt'] = "1_th";
            $booking['type'] = "1 therapist";
        }

        //if one of mandatory fields is missing, return empty array results
        //         $mandatory_fields = ['postcode','date'];
        //         foreach($mandatory_fields as $field){
        //             if (!isset($booking[$field]))
        //                 return response(['message'=>'You must select postcode, massage duration, type of massage, date of masage and number of therapists'],403);
        //         } //endforeach

        //         if (!isset($booking['selected_therapists']))
        //             $booking['selected_therapists'] = [];


        //         if (in_array($request->thID,$booking['selected_therapists'])){
        //             //unmark therapist
        //             $key = array_search($request->thID, $booking['selected_therapists']);
        //             if(!is_null($key))
        //                 unset($booking['selected_therapists'][$key]);
        //         }
        //         elseif (count($booking['selected_therapists']) < $booking['therapists']){
        //             //mark the therapist as selected
        //             @$booking['selected_therapists'][] = $request->thID;
        //         }
        //         else{
        //             //change the last therapist
        //             $last = count($booking['selected_therapists'])-1;
        //             $booking['selected_therapists'][$last] = $request->thID;
        //         }

        // //        session(['booking' => $booking]);
        //         Session::put('booking',$booking);

        //dd($booking);
        //return success response
        return response(['message' => 'success'], 200);
    }

    public function get_salon_hours($date = null)
    {
        $cartItem = Session::get('cartItem');
        // dd($cartItem->duration_id);

        if (!$date)
            $date = date('Y-m-d');
        $booking = Session::get('booking');

        if (!isset($booking['hour']) || $booking['hour'] == '00:00') {
            $first_hours = $this->book->getAndSetFirstAvailableDayHourSalon();
            $booking = Session::get('booking');
        }

        $hours = $this->book->all_salon_hours($date, $cartItem->duration_id);

        $this->data['hours'] = $hours;
        $this->data['selectedhour'] = isset($booking['hour']) ? $booking['hour'] : null;

        //return view partial
        return view('schedules::frontend_new.booking.partial_hours', $this->data);
    }

    public function contactVenue(Request $request)
    {
        // dd($request->all());
        try {
            //code...
            SalonContact::create([
                'venue_id' => $request->venue_id,
                'name' => $request->name,
                'email' => $request->email,
                'number' => $request->number,
                'description' => $request->description,
            ]);
            return redirect()->back()->with('success', 'Query Generated Successfully!');
        } catch (\Throwable $th) {
            //throw $th;
            return response(['message' => 'An error occurred while contacting the venue. Please try again later.'], 500);
        }
    }
}

ZeroDay Forums Mini