<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\All_session;
use App\Models\EnabledService;
use App\Models\Language;
use App\Models\ScheduleWorktime;
use App\Models\Service;
use App\Models\ServiceSchedule;
use App\Models\User;
use App\Models\UserBooking;
use App\Models\UserLanguage;
use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Auth;
use App\Models\PrefilledQuestions;
use App\Models\Answer;
use App\Models\CalenderService;
use App\Models\Category;
use App\Models\City;
use App\Models\DiscussionService;
use App\Models\OpenCalendar;
use App\Models\OpenCalendarSchedule;
use App\Models\Request as ModelsRequest;
use App\Models\Schedule_calendar_requests;
use App\Models\State;
use App\Models\UserProfile as ModelsUserProfile;
use Carbon\Carbon;
use DateTime;
use DateTimeZone;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rules\Exists;
use Illuminate\Validation\Rules\Unique;
use UserProfile;
use Illuminate\Support\Str;
class PavsController extends Controller
{

    public function __construct()
    {
        define('RESCHEDULE_REQUESTED',1);
        define('RESCHEDULE_ACCEPTED',2);
        define('RESCHEDULE_REJECTED',3);
        define('COMPLETED',4);
        define('REQUEST_TYPE_REFUND','refund');
        define('REQUEST_TYPE_RESCHEDULE','reschedule');
    }

    public function categories(Request $request)
    {
        $categories = \App\Models\Category::query();
        if ($request->has('search')) {
            $categories->where('category_name', 'like', '%' . $request->search . '%');
        }

        if ($request->has('parent_id')) {
            $categories->where('category_parent', $request->parent_id);
        } else {
            //category_parent = 0 or null
            $categories->where(function ($q) {
                $q->where('category_parent', 0)
                    ->orWhereNull('category_parent');
            });
        }


        // order by name
        $categories->orderBy('category_name', 'asc');

        // row has children or not
        // does it have children
        $categories->withCount('children');
        $categories = $categories->get();
        return response()->json($categories);
    }


    // get service providers
    public function serviceProviders(Request $request)
    {

        $user = Auth::user();
        
        //update user last login
        $userInfo = User::find($user->id);
        $userInfo->last_login = date('Y-m-d H:i:s');
        $userInfo->save();
       
        $userCity = $request->city ?? "";
        $userState = $request->state ?? "";
        // $userLanguage = $user->languages->pluck('language_id')->toArray();
        $userLanguage = $request->requested_languages;
        $service_category = $request->service_category ?? "";
        $sub_category = $request->sub_category ?? "";
        $child_category = $request->child_category ?? "";
        if (empty($userLanguage)) {
            $userLanguage = [];
        }



        $DB = new DB;

        //enable query log
        $DB::connection()->enableQueryLog();


        //user_profile
        $sp = User::query();
        $sp->select('users.name', 'users.id', 'user_profile.rating', 'user_profile.skill_set', 'c1.category_name as category_name','c2.category_name as service_offered_name');
        
      


        //Identify service providers
        $sp->whereHas('profile', function ($q) {
            $q->whereNotNull('service_offered')
                ->where('service_offered', '!=', '')
                ->where('service_offered', '!=', 0);
        });

   
         // get service providers in same city
         if(!empty($userCity)){
            $sp->whereHas('profile', function ($q) use ($userCity) {
                $q->where('city', $userCity);
            });
        }

        // get service providers in same state
        if(!empty($userState)){
            $sp->whereHas('profile', function ($q) use ($userState) {
                $q->where('state', $userState);
            });
        }
        if (!empty($userLanguage)) {
            // get service providers with same language
            $sp->whereHas('languages', function ($q) use ($userLanguage) {
                $q->whereIn('language_id', $userLanguage);
            });
        }

        $sp->whereHas('enabled_services', function ($q) {
            $q->where('service_id', 7)->where('status', 1);
        });

        // join to profile table
        $sp->join('user_profile', 'user_profile.user_id', '=', 'users.id');

        // join user_languages and get language name from languages table
        //$sp->join('user_languages', 'user_languages.user_id', '=', 'users.id');
        //$sp->join('languages', 'languages.id', '=', 'user_languages.language_id');


        // get total booked duration
        $sp->addSelect([
            'total_duration' => \App\Models\ServiceBooking::select(DB::raw('sum(duration)'))
                ->whereColumn('provider_id', 'users.id')
                // ->where('status', 1)
                ->limit(1)
        ]);


        // get total clients
        $sp->addSelect([
            'total_clients' => \App\Models\ServiceBooking::select(DB::raw('count(distinct user_id)'))
                ->whereColumn('provider_id', 'users.id')
                // ->where('status', 1)
                ->limit(1)
        ]);


        // join to service table
        $sp->join('categories as c1', 'c1.id', '=', 'user_profile.service_category');
        $sp->join('categories as c2', 'c2.id', '=', 'user_profile.service_offered');

        // if service category not empty
        if (!empty($service_category)) {
            $sp->where('c1.id', $service_category);
        }

        // if sub category not empty
        if (!empty($sub_category)) {
            $sp->where('c2.id', $sub_category);
        }

        // if child category not empty
        if (!empty($child_category)) {
            $sp->where('c1.category_parent', $child_category);
        }


        // get service name
        // $sp->addSelect([
        //     'category_name' => 'categories.category_name'
        // ]);

        
        //filter last 30 days inactive providers
       
        $sp->where('last_login','>=',date('Y-m-d H:i:s',strtotime('-29 days')));
        $sp->orWhere('last_login',NULL);

        // order by rating
        $sp->orderBy('user_profile.rating', 'desc', 'total_duration', 'desc');
        //paginate to 10.
        $data = $sp->paginate(5);

        //
        foreach ($data as $key => $value) {

            if ($value->id == $user->id) {
                // add a new property to the object
                $value->own_profile = true;
            } else {
                $value->own_profile = false;
            }

            //get last rating & feedback
            $reviews = UserBooking::where('service_provider_id', $value->id)->where('rating','!=',"")->orderBy('id', 'desc')->first();
            if($reviews){ 
                $rating = $reviews->rating;
                $last_review = $reviews->review;
            }else{
                $rating = 0;
                $last_review = "";
            }
            $value->last_rating = $rating;
            $value->last_feedback    = $last_review;

          
            $details = $this->serviceProvidersById($request, $value->id);
            $value->details = $details->getData();
        }




        // return data
        return response()->json($data);
    }

    public function serviceProvidersById(Request $request, $id)
    {

        // get user by id
        $user = User::find($id);
     
        // $user->profile = $user->profile;

        // get user language like ['1'=>'English', '2'=>'Hindi']
        //  $user->languages = 

        // $lang = UserLanguage::where('user_id', $id)->pluck('language_id')->toArray();
        //    $user->languages = Language::whereIn('id', $lang)->pluck('language', 'id')->toArray();
        
        //get last review informations
        $user_bookings = UserBooking::where('service_provider_id', $id)->where('rating','!=',"")->orderBy('id', 'desc')->first();
        $feedbacks = [];
        if($user_bookings){

            $rating_user = User::find($user_bookings->customer_id);
            
            if($rating_user){
                $schedule_name = "";
                // dd($user_bookings);
                if($user_bookings->service_type == "schedule_calendar"){
                    $service_schedule = ServiceSchedule::find($user_bookings->schedule_id);
                    if($service_schedule){
                        $schedule_name = $service_schedule->schedule_name;
                    }else{
                        $schedule_name = "Schedule Calendar";
                    }
                }elseif($user_bookings->service_type == "open_calendar"){ 
                    $schedule_name = "Open Calendar Schedule";
                }else{
                    $schedule_name = "Discussion Service";
                }
                $feedbacks = array(
                    'user_id'        => $rating_user->id,
                    'user_name'      => $rating_user->username,
                    'profile_pic'    => url('storage/profile_image/'.$rating_user->profile_picture),
                    'schedule_name'  => $schedule_name,
                    'rating'         => $user_bookings->rating,
                    'feedback'       => $user_bookings->review,
                    'reviewed_at'    => $user_bookings->reviewed_at,
                    
                );
            }
            
        }
        $user->reviews = $feedbacks;


        // check available services
        // dd($id);
        $sc = new ServiceController;
        $services = $sc->getAllServices($request, $id);
        $services = $services->getData();
       
        // get available days from calendar service
        $calendarServiceDetails = $services->calendar_service;
        $days = [];
        $availableTime = ["start_time"=>null, "end_time"=>null];
        if (isset($calendarServiceDetails->type)) {
            if ($calendarServiceDetails->type == 1) {

                $details = $calendarServiceDetails->service_schedule;
                foreach ($details as $k => $v) {
                    $v = (array) $v;
                    // $detailsArr['days'] = $v['days'];
                    // $detailsArr['start_time'] = $v['start_time'] ?? "";
                    // $detailsArr['end_time'] = $v['end_time'] ?? "";
                    // $days[] = $detailsArr;
                    if (is_string($v['days'])) {
                        $v['days'] = json_decode($v['days']);
                    }

                    $days = array_merge($days, $v['days']);
                }
            } else {

                $details = $calendarServiceDetails->open_calendar;
                $openCalendarDays = [];
                foreach ($details as $k => $v) {
                    $v = (array) $v;
                    //merge days array to openCalendarDays

                    //if $v['days'] is string "[2]", convert to array
                    if (is_string($v['days'])) {
                        $v['days'] = json_decode($v['days']);
                    }
                    $availableTime['start_time'] = $v['start_time'] ?? "";
                    $availableTime['end_time'] = $v['end_time'] ?? "";
                    //  dd($v['days'], $openCalendarDays);
                    $openCalendarDays = array_merge($openCalendarDays, $v['days']);
                }
                $days = array_unique($openCalendarDays);
                // merge $openCalendarDays sub array to $days array

            }
        }


        $enabledServices = EnabledService::where('user_id', $id)->where('status', 1)->pluck('service_id')->toArray();
        // get service name by id
        $servicesList = Service::whereIn('id', $enabledServices)->pluck('service_name', 'id')->toArray();

        // $servicesList to simple array
        $servicesList = array_values($servicesList);
        $user->services = $servicesList;
        $user->available_days = array_values(array_unique($days));
        $user->available_time = $availableTime;

        //   $user->services = $services;
      
        $calendarService = [];

        if (isset($services->calendar_service->type) && $services->calendar_service->type == 1) {

            $schedules = $services->calendar_service->service_schedule;
            if (count($schedules) > 0) {
                // find min and max charges_per_session from schedules array
                $min = min(array_column($schedules, 'charges_per_session'));
                $max = max(array_column($schedules, 'charges_per_session'));
            } else {
                $min = 0;
                $max = 0;
            }
        }
        if (isset($services->calendar_service->type) && $services->calendar_service->type == 2) {
            // dd($services->calendar_service);
            $schedules = $services->calendar_service->open_calendar;
            $charges = [];
            if (count($schedules) > 0) {
                foreach ($schedules as $schedule) {
                    $schedule = (array) $schedule;
                    if (count($schedule['open_calendar_schedule']) > 0) {
                        foreach ($schedule['open_calendar_schedule'] as $open_calendar_schedule) {
                            $charges[] = $open_calendar_schedule->price ?? 0;
                        }
                    }
                }
            }

            $min = min($charges);
            $max = max($charges);
        }


        $user->price = [
            'min' => $min ?? 0,
            'max' => $max ?? 0
        ];



        $user->basic_details = $services->basic_profile->profile;
        $user->profile_picture = $services->basic_profile->profile_picture;

        // dd($user);

        return response()->json($user);


        //enable query log
        // $DB::connection()->enableQueryLog();
    }

    // get prefilled questions by service provider id
    function get_prefilled_questions(Request $request, $service_provider_id){
      $user = Auth::user();
      $prefilledQuestions = PrefilledQuestions::where('user_id', $service_provider_id)->get();
      return response()->json($prefilledQuestions);
    }

    public function save_answers(Request $request){
        $user = Auth::user();
        $answers = $request->answers;

        // start db transaction
        DB::beginTransaction();

        foreach($answers as $k=>$value){
            //get question by id
            $question = PrefilledQuestions::find($value['question_id']);
          //  dd($question);
            if($question==null){
                return response()->json(['success'=>false, 'message'=>'Question not found']);
            }
        //    $question = $question->first();
            $answer = new Answer;
            $answer->question_id = $value['question_id'];
            $answer->question =$question->question;
            $answer->answer = $value['answer'];
            $answer->user_id = $user->id;
            $answer->provider_id = $question->user_id;
            $answer->status =1;
            $answer->save();
        }
        // commit db transaction
        DB::commit();

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




    public function prepaidHours(Request $request)
    {
        $user = Auth::user();
        // 1 Hrs 20 Rs
        // 2 Hrs 40 Rs
        // 8 Hrs 160 Rs
        // 16 Hrs 320 Rs
        // 24 Hrs 480 Rs
        // 32 Hrs 640 Rs
        // 40 Hrs 800 Rs
        // 48 Hrs 960 Rs
        // 56 Hrs 1120 Rs

        $array = [
            [
                'id' => 1,
                'hours' => 1,
                'price' => 20
            ],
            [
                'id' => 2,
                'hours' => 2,
                'price' => 40
            ],
            [
                'id' => 3,
                'hours' => 8,
                'price' => 160
            ],
            [
                'id' => 4,
                'hours' => 16,
                'price' => 320
            ],
            [
                'id' => 5,
                'hours' => 24,
                'price' => 480
            ],
            [
                'id' => 6,
                'hours' => 32,
                'price' => 640
            ],
            [
                'id' => 7,
                'hours' => 40,
                'price' => 800
            ],
            [
                'id' => 8,
                'hours' => 48,
                'price' => 960
            ],
            [
                'id' => 9,
                'hours' => 56,
                'price' => 1120
            ],
        ];

        return response()->json($array);
    }
     
    public function getschedules(Request $request,$id,$daystring,$schedule_id=""){  
      
        $user = User::findOrFail($id);
        //check calendar type
        $open_calendar = OpenCalendar::where('user_id',$user->id)->first();
         
        if($open_calendar == null){
            $service_provider_id = $id;
            $month_number = $daystring;
            $schedule_id = $schedule_id;
            
            $schedule = ServiceSchedule::findOrFail($schedule_id);
           
            $days = $schedule->days;
            $data = [];
           
            //split appointment & monthby charges per
            if($schedule->charges_per == 1 || $schedule->charges_per == "1"){
                $todaystr = date('D',strtotime('today'));
                // check daystring is today or next day's ?
                if($daystring == $todaystr)
                {
                    $date = date('Y-m-d');
                }else{
                    $date = date('Y-m-d',strtotime('next '.$daystring));
                }
             
                $day_num =$this->get_daynum_from_daystring($daystring);
                $days = [$day_num];


                 $data[] = array(
                    'day' => $daystring,
                    'id' => $schedule->id,
                    'name' => $schedule->schedule_name,
                    'start_time' => $schedule->schedule_start_time,
                    'end_time'   => $schedule->schedule_end_time,
                    'allow_booking_after' => $schedule->allow_booking_after,
                    'date'       => $date,
                    'days'       => $days,
                    'clients_per_session' => $schedule->clients_per_session,
                    'charges_per_session' => $schedule->charges_per_session,
                    'type'       => 'schedule calendar',
                    'paid_by'    => $schedule->paid_by,
                    'charges_per' => $schedule->charges_per,
                    'slots'      => $this->schedule_cal_appointment_slot($schedule->id,$daystring),
                 );

            }else{
                $data[] = array(
                    'day' => "",
                    'id' => $schedule->id,
                    'name' => $schedule->schedule_name,
                    'start_time' => $schedule->schedule_start_time,
                    'end_time'   => $schedule->schedule_end_time,
                    'allow_booking_after' => $schedule->allow_booking_after,
                    'date'       => "",
                    'days'       => $schedule->days,
                    'clients_per_session' => $schedule->clients_per_session,
                    'charges_per_session' => $schedule->charges_per_session,
                    'type'       => 'schedule calendar',
                    'paid_by'    => $schedule->paid_by,
                    'charges_per' => $schedule->charges_per,
                    'slots'      => $this->getSlots($schedule->id,$schedule->clients_per_session,$schedule->charges_per,$month_number,$days),
                );
            }
                
           
        
    }else{
        //open calendar
        $todaystr = date('D',strtotime('today'));
        // check daystring is today or next day's ?
        if($daystring == $todaystr)
        {
            $date = date('Y-m-d');
        }else{
            $date = date('Y-m-d',strtotime('next '.$daystring));
        }

        $allow_booking_after = $open_calendar->allow_booking_after;
        $st_date = date('Y-m-d',strtotime($open_calendar->created_at));
      
        $end_dt =  date('Y-m-d',strtotime($st_date.'+'.($allow_booking_after - 1).'days'));
        $data[] = array(
            'id' => $open_calendar->id,
            'start_time' => $open_calendar->start_time,
            'end_time'   => $open_calendar->end_time,
            'allow_booking_after' => $open_calendar->allow_booking_after,
            'date'       => $date,
            'days'       => json_decode($open_calendar->days),
            'type'       => 'open calendar',
            'paid_by'    => $open_calendar->paid_by,
            'slots'      => $this->opencalDetailedSlot($open_calendar->id,$daystring,$open_calendar->days,$user->id),
        );
    }

        return response()->json($data);
    }

    /**
     * Get Schedule Calendar appointment slots
     */
    public function schedule_cal_appointment_slot($schedule_id,$daystring){
        $schedule = ServiceSchedule::find($schedule_id);
        $schedule_worktime = ScheduleWorktime::where('schedule_id',$schedule_id)->get();
        if($schedule_worktime){

            $todaystr = date('D',strtotime('today'));
            // check daystring is today or next day's ?
            if($daystring == $todaystr)
            {
                $date = date('Y-m-d');
            }else{
                $date = date('Y-m-d',strtotime('next '.$daystring));
            }
            
            foreach($schedule_worktime as $worktime){ 
                $user_bookings = UserBooking::where('schedule_id',$schedule_id)
                                            ->where('service_provider_id',$schedule->user_id)
                                            ->where('service_type','schedule_calendar')
                                            ->where('schedule_id',$schedule_id)
                                            ->where('date',$date)
                                            ->where('start_time',$worktime->start_time)
                                            ->where('end_time',$worktime->end_time)
                                            ->get();
                
                $status = "";
                if(count($user_bookings) < $schedule->clients_per_session){ 
                   $status = "Available";
                }else{
                    $status = "Not Available";
                }
                $return_data[] = array(
                    'start_time' => $worktime->start_time,
                    'end_time' => $worktime->end_time,
                    'charges'  => $schedule->charges_per_session,
                    'available_clients_count' => $schedule->clients_per_session - count($user_bookings),
                    'booked_clients_count' => count($user_bookings),
                    'is_available' => $status
                );
                
               
            }
            return $return_data;
        }else{
              return 'Something  Went Wrong';
        }
        
    }
    public function getSlots($id,$clients_per_session,$charges_per,$month_number,$days){
                    
       
       
        $work_time = ScheduleWorktime::select('schedule_worktime.*','service_schedules.charges_per_session')
                     ->join('service_schedules','service_schedules.id' ,'=','schedule_worktime.schedule_id')
                    //  ->where('start_time','>',date('H:i:s'))
                     ->where('schedule_worktime.schedule_id',$id)
                     ->get();
     
       
        if($work_time->count() == 0){
            return 'Not Scheduled';
        }
        $currentMonthNum = intval(date('m'));
        
        $startOfMonth = Carbon::create(date('Y'),$month_number,date('d'));
        $endOfMonth = Carbon::create(date('Y'),$month_number,1)->endOfMonth();
        $today = date('Y-m-d');
        $start_date = $startOfMonth->format('Y-m-d');
        $end_date = $endOfMonth->format('Y-m-d');  

        if($month_number != $currentMonthNum){
            $next_month_start = Carbon::create(date('Y'),$month_number,1);
            $start_date = $next_month_start->format('Y-m-d');

            $next_end = Carbon::create(date('Y'),$month_number,1)->endOfMonth();
            $end_date = $next_end->format('Y-m-d');
         
        }

        
      
        $remaining_sessions = $this->checkTotalClientsCount($start_date,$end_date,$days);
      
        $totalclients_count =  $clients_per_session;

        foreach($work_time as $time){
            $available_status = UserBooking::where('schedule_id',$id)
                                ->where('status',1)
                                ->whereTime('start_time','>=',$time->start_time)
                                ->whereTime('end_time','<=',$time->end_time)
                                ->whereBetween('date',[$start_date,$end_date])
                                ->get();
            // dd($time->start_time);
             $available_client_count = 0;
             $booked_clients_count = 0;
             if(!empty($available_status)){
                $booked_clients_count = $available_status->count();
             }
            if($available_status->count() >= $clients_per_session){
                $status = 'Not Available';
            }else{
                $available_client_count = $totalclients_count - count($available_status);
                $status = 'Available';
            }
            $booked_charges = $remaining_sessions * $time->charges_per_session;
            $slots[] = array(
                'start_time' => $time->start_time,
                'end_time'   => $time->end_time,
                'charges'    => $booked_charges,
                'available_clients_count' => $available_client_count,
                'booked_clients_count'    => $booked_clients_count,
                'is_available' => $status
            );

        }
        return $slots;
    }

    //checkTotalClientsCount
    public function checkTotalClientsCount($start_date,$endDate,$days)
    {
        $currentDate = $start_date;
       
        $days = json_decode($days);
        
        $day_count = 0;
        while (strtotime($currentDate) <= strtotime($endDate)) {
        
              $daystring = date('D',strtotime($currentDate));
              
              if($daystring == "Sun" || $daystring == "sun"){
                 $day_num = 0;
              }elseif($daystring == "Mon" || $daystring == "mon"){
                 $day_num = 1;
              }elseif($daystring == "Tue" || $daystring == "tue"){
                $day_num = 2;
              }elseif($daystring == "Wed" || $daystring == "wed"){
                $day_num = 3;
              }elseif($daystring == "Thu" || $daystring == "thu"){ 
                $day_num = 4;
              }elseif($daystring == "Fri" || $daystring == "fri"){ 
                $day_num = 5;
              }elseif($daystring == "Sat" || $daystring == "sat"){ 
                $day_num = 6;
              }
              if(in_array($day_num,$days)){
                $day_count += 1;
              }
            //   echo $currentDate.'   ';
            // Increment the current date by 1 day
            $currentDate = date("Y-m-d", strtotime($currentDate . "+1 day"));
        }
         
         return $day_count;
        
    }


    //opencalDetailedStatus
    public function opencalDetailedSlot($opencalid,$daystring,$days,$userid)
    {
        $todaystr = date('D',strtotime('today'));
            // check daystring is today or next day's ?
            if($daystring == $todaystr)
            {
                $date = date('Y-m-d');
            }else{
                $date = date('Y-m-d',strtotime('next '.$daystring));
            }
        $num = '';
        //check days
        if($daystring == 'Sun' || $daystring == 'sun'){
            $num = 0;
        }elseif($daystring == 'Mon' || $daystring == 'mon'){
            $num = 1;
        }elseif($daystring == 'Tue' || $daystring == 'tue'){
            $num = 2;
        }elseif($daystring == 'Wed' || $daystring == 'wed'){
            $num = 3;
        }elseif($daystring == 'Thu' || $daystring == 'thu'){
            $num = 4;
        }elseif($daystring == 'Fri' || $daystring == 'fri'){
            $num = 4;
        }elseif($daystring == 'Sat' || $daystring == 'sat'){
            $num = 6;
        }

        //days
        $days = json_decode($days);

        if(in_array($num,$days)){
            $open_calendar = OpenCalendar::find($opencalid);
            $min_session = OpenCalendarSchedule::select('time_per_session')->where('open_calendar_id',$open_calendar->id)->min('time_per_session');
             $s_time = date('H',strtotime($open_calendar->start_time));
             $start_time = $s_time.':00:00';
             $actual_st_time = $open_calendar->start_time;
             $end_time = $open_calendar->end_time;
             $interval = 1;
             $calendarService = CalenderService::find($open_calendar->calendar_service_id);
             $gap = $calendarService->gap_between_slots;
            
             $i = 0;
           
             while($start_time < $end_time){
          
                
                // $start_wth_gap = 
                $slotstatus = NULL;
                $status = '';
                if($i == 0){
                  
                    if($start_time == $open_calendar->start_time){
                       
                        $start_wth_gap = $actual_st_time;
                        $end_wth_gap = date('H:i:s',strtotime($actual_st_time.' +1 minutes'));
                    }else{
                      
                        $start_wth_gap = $actual_st_time;
                       
                        $end_wth_gap = date('H:i:00',strtotime($actual_st_time.' +1 minutes'));
                      
                      
                    }
                    
                }else{
                  
                    $session = $interval + $gap;
                    $start_wth_gap = date('H:i:s',strtotime($start_time.' +'.$gap.' minutes'));
                    $end_wth_gap = date('H:i:s',strtotime($start_time.' +'.$session.' minutes'));
                }
               
         
            //    $start_wth_gap = '11:00:00';
            //    $end_wth_gap   = '12:00:00';
                $slotstatus = UserBooking::where('service_provider_id',$userid)
                              ->where('date',$date)
                              ->where('status',1)
                              ->where('service_type','open_calendar')
                              ->where(function($query) use ($start_wth_gap,$end_wth_gap){
                                $query->where(function($q) use ($start_wth_gap, $end_wth_gap) {
                                    $q->where('start_time', '<=', $start_wth_gap)
                                      ->where('end_time', '>=', $start_wth_gap);
                                })
                                ->orWhere(function($q) use ($start_wth_gap, $end_wth_gap) {
                                    $q->where('start_time', '<', $end_wth_gap)
                                      ->where('end_time', '>', $end_wth_gap);
                                })
                                ->orWhere(function($q) use ($start_wth_gap, $end_wth_gap) {
                                    $q->where('start_time', '>', $start_wth_gap)
                                      ->where('end_time', '<', $end_wth_gap);
                                });
                        })
                              ->get();
                          
                $last_index = count($slotstatus) - 1;
                //  dd($slotstatus);
                if(strtotime($start_time) < strtotime($open_calendar->start_time)){
                    $status = "Not Scheduled";
                    
                }else{
                    if(count($slotstatus) == 0){
                        $status = 'Available';
                    }else{
                        $current_end_time = "";
                        foreach($slotstatus as $k => $sl_status){
                            
                            if(count($slotstatus) == 1){
                            
                                $f_st_time = new DateTime($start_wth_gap);
                                $f_e_time = new DateTime($sl_status->start_time);
                                $f_interval = $f_st_time->diff($f_e_time);
                                $f_diff = $f_interval->i;
                                
                                if($end_wth_gap > $sl_status->end_time){
                                    $l_st_time = new DateTime($sl_status->end_time);
                                    //check if session end_time is greater than slot_end_time
                                    if($end_time >= $end_wth_gap){
                                        $l_e_time  = new DateTime($end_wth_gap);
                                    }else{
                                        $l_e_time  = $end_time;
                                    }
                                    $l_interval = $l_st_time->diff($l_e_time);
                                    $l_diff = $l_interval->i;
                                }else{
                                    $l_diff = 0;
                                }
                               
                               
                                $l_status = "";
                                $f_status = "";
                                // dd($end_time);
                                if($f_diff >= $min_session && $f_e_time->format('H:i:s') <= $end_time){
                                    $f_status = "Available";
                                }
                                if($l_diff >= $min_session && $l_e_time->format('H:i:s') <= $end_time){
                                    $l_status = "Available";
                                }
                                 
                                if($f_status == "Available" || $l_status == "Available"){
                                    $status = "Available";
                                }else{
                                    $status = "Not Available";
                                }
                                // echo $status;die;
                            }else{
                                $sn_status = [];
                                if($k == 0){
                                    $s1_st_time = new DateTime($start_wth_gap);
                                    $s1_e_time  = new DateTime($sl_status->start_time);
                                    $s1_interval = $s1_st_time->diff($s1_e_time);
                                    $s1_diff = $s1_interval->i;
                                    if($s1_diff >= $min_session){
                                        $sn_status[] = "Available";
                                    }
                                }elseif($k == $last_index){
                                    $sl_st_time = new DateTime($sl_status->end_time);
                                    //check if session end_time is greater than slot_end_time
                                    if($end_time >= $end_wth_gap){
                                        $sl_e_time  = new DateTime($end_wth_gap);
                                    }else{
                                        $sl_e_time  = new DateTime($end_time);
                                    }
                                    $sl_interval = $sl_st_time->diff($sl_e_time);
                                    $sl_diff = $sl_interval->i;
                                    if($sl_diff >= $min_session && $sl_e_time->format('H:i:s') <= $end_time){
                                        $sn_status[] = "Available";
                                    }
                                    
                                 
    
                                }else{
                                    $sn_st_time = new DateTime($current_end_time);
                                    $sn_e_time  = new DateTime($sl_status->start_time);
                                    $sn_interval= $sn_st_time->diff($sn_e_time);
                                    $sn_diff    = $sn_interval->i;
                                    if($sn_diff >= $min_session){
                                        $sn_status[] = "Available";
                                    }
                                }
                               
                                if(in_array("Available",$sn_status)){
                                    $status = "Available";
                                }else{
                                    $status = "Not Available";
                                }
                            }
    
                            $current_end_time = $sl_status->end_time;
                           
                        }
                       
                        // echo $current_end_time;die;
                    }
                }
                
                $times[] = array(
                    'start_time'    => $start_time,
                    'end_time' => date('H:i:s',strtotime($start_time.' +1 minutes')),
                    'is_available' => $status
                );
                $start_time = date('H:i:s',strtotime($start_time.' +1 minutes'));
                
                $i++;
             }

            //  dd($times);
             return $times;
        }else{
            return 'Not Scheduled';
        }
       
    }

    // store_userbookings
    public function store_userbookings(Request $request)
    {
       
        $todate = date('Y-m-d');
        if($request->service_type == "schedule_calendar"){

            $service_schedule = ServiceSchedule::findOrFail($request->schedule_id);
            if($service_schedule->charges_per == 1 || $service_schedule->charges_per == "1"){
                
                $date = $request->date;
                $todate = $request->date;
                
            }else{
                $month_number = $request->date;
                $endofmonth = Carbon::create(date('Y'), $month_number, 1)->endOfMonth();
                $todate = $endofmonth->format('Y-m-d');
                $currentMonthNum = intval(date('m'));
    
                if($currentMonthNum == $month_number){
                    $date = date('Y-m-d');
                }elseif($month_number == 1){
                   if($currentMonthNum == 12){
                       $carbondate = Carbon::create(date('Y',strtotime('+1 year')),$month_number,1)->startOfMonth();
                       $date = $carbondate->format('Y-m-d');
                   }else{
                        $carbondate = Carbon::create(date('Y'),$month_number,1)->startOfMonth();
                        $date = $carbondate->format('Y-m-d');
                   }
                }
                else{
                    $startOfMonth = Carbon::create(date('Y'),$month_number,1)->startOfMonth();
                    $date = $startOfMonth->format('Y-m-d');
                }
            }

          
            
        }else{
            $date = $request->date;
            $todate = $request->date;
        }
        $user_booking = UserBooking::where('customer_id',$request->customer_id)
                                    ->where('service_provider_id',$request->service_provider_id)
                                    ->where('service_type',$request->service_type)
                                    ->where('schedule_id',$request->schedule_id)
                                    ->where('date','>=',$date)
                                    ->where('to_date','<=',$todate)
                                    ->where('status',1)
                                    ->where('start_time','>=',$request->start_time)
                                    ->where('end_time','<=',$request->end_time)
                                    ->get();

        if($request->service_type == "schedule_calendar"){
                $service_schedule = ServiceSchedule::findOrFail($request->schedule_id);
                if(count(($user_booking)) >= $service_schedule->clients_per_session){
                    return response()->json(['status' => 'failed','message' => 'Clients per session exceeded']);
                }

        // if(count($user_booking))
        }
        if($user_booking->count() == 0){
      
           
            $bookings = new UserBooking;
            $bookings->customer_id           = $request->customer_id;
            $bookings->service_provider_id   =  $request->service_provider_id;
            $bookings->service_type          = $request->service_type;
            $bookings->schedule_id           = $request->schedule_id;
            $bookings->date                  = $date;
            $bookings->start_time            = $request->start_time;
            $bookings->end_time              = $request->end_time;
            $bookings->to_date               = $todate;
            $bookings->booking_id            = substr(uniqid(), -8);
            $bookings->save();

             //split whole sessions
            //  if($request->service_type == "schedule_calendar"){
                    $this->split_scheduleCalSessions($bookings);
                // }

            return response()->json(['status' => 'success','message' => 'Booking Details Added successfully']);
        }else{
            return response()->json(['status' => 'failed','message' => 'Slot Already booked!']);
        }
    }

    //split_scheduleCalSessions
    public function split_scheduleCalSessions($request){
        //check whether if session already splitted or not
        if($request->service_type == "schedule_calendar"){ 
            $all_sessions = All_session::where('service_provider_id',$request->service_provider_id)
                                        ->where('service_type',$request->service_type)
                                        ->where('schedule_id',$request->schedule_id)
                                        ->where('date','>=',$request->date)
                                        ->where('date','<=',$request->to_date)
                                        ->where('start_time',$request->start_time)
                                        ->where('end_time',$request->end_time)
                                        ->get();

            if($all_sessions->count() == 0){ 
                $service_schedule = ServiceSchedule::findOrFail($request->schedule_id);
                $days = json_decode($service_schedule->days);
                
                $currentDate = $request->date;
                $end_date = $request->to_date;
                $return_data = [];
                while (strtotime($currentDate) <= strtotime($end_date)) {
                
                      $daystring = date('D',strtotime($currentDate));
                      
                      if($daystring == "Sun" || $daystring == "sun"){
                         $day_num = 0;
                      }elseif($daystring == "Mon" || $daystring == "mon"){
                         $day_num = 1;
                      }elseif($daystring == "Tue" || $daystring == "tue"){
                        $day_num = 2;
                      }elseif($daystring == "Wed" || $daystring == "wed"){
                        $day_num = 3;
                      }elseif($daystring == "Thu" || $daystring == "thu"){ 
                        $day_num = 4;
                      }elseif($daystring == "Fri" || $daystring == "fri"){ 
                        $day_num = 5;
                      }elseif($daystring == "Sat" || $daystring == "sat"){ 
                        $day_num = 6;
                      }
                      if(in_array($day_num,$days)){
                   
                        $all_session = new All_session;
                        $all_session->service_provider_id = $request->service_provider_id;
                        $all_session->service_type = $request->service_type;
                        $all_session->schedule_id = $request->schedule_id;
                        $all_session->date = $currentDate;
                        $all_session->start_time = $request->start_time;
                        $all_session->end_time = $request->end_time;

                        $all_session->save();
                      }
                    // Increment the current date by 1 day
                    $currentDate = date("Y-m-d", strtotime($currentDate . "+1 day"));
                }
            }
        }else{

            $all_sessions = All_session::where('service_provider_id',$request->service_provider_id)
                                        ->where('service_type',$request->service_type)
                                        ->where('schedule_id',$request->schedule_id)
                                        ->where('date',$request->date)
                                        ->where('start_time',$request->start_time)
                                        ->where('end_time',$request->end_time)
                                        ->get();
            if($all_sessions->count() == 0){
                        $all_session = new All_session;
                        $all_session->service_provider_id = $request->service_provider_id;
                        $all_session->service_type = $request->service_type;
                        $all_session->schedule_id = $request->schedule_id;
                        $all_session->date = $request->date;
                        $all_session->start_time = $request->start_time;
                        $all_session->end_time = $request->end_time;
            
                        $all_session->save();
            }
        }
        
      
    }
    //general_schedules
    public function general_schedules(Request $request,$id,$month= null)
    {
        $user = User::findOrFail($id);
        //check type
        $open_calendar = OpenCalendar::where('user_id',$user->id)->first() ?? collect();
        $appointment = [];
        $month_session = [];
        //opencalendar
        if(count(get_object_vars($open_calendar)) > 0 && $open_calendar->count() > 0){
           
            //get total available time
            $time1 = new DateTime($open_calendar->start_time);
            $time2 = new DateTime($open_calendar->end_time);
            $diff = $time1->diff($time2);
            $available_hours = $diff->format('%H:%I');
            // dd($available_hours);
            $allow_booking_after = $open_calendar->allow_booking_after;
            // echo $allow_booking_after;die;
            $st_date = date('Y-m-d');
            $actual_end_date = date('Y-m-d',strtotime($st_date.'+6 days'));
            $end_dt =  date('Y-m-d',strtotime($st_date.'+'.($allow_booking_after - 1).'days'));
            $calendar_schedules = OpenCalendarSchedule::where('open_calendar_id',$open_calendar->id)
                                 ->where('user_id',$user->id)
                                 ->get();
        //    foreach($calendar_schedules as $cal_schedule){
        
            $appointment[] = array(
                'id'                  => $open_calendar->id,
                'allow_booking_after' => $open_calendar->allow_booking_after,
                'start_date'          => $st_date,
                'end_date'            => $end_dt,
                'actual_end_date'     => $actual_end_date,
                'start_time'          => $open_calendar->start_time,
                'end_time'            => $open_calendar->end_time,
                'charges'             => $calendar_schedules->first()->price,
                'paid_by'             => $open_calendar->paid_by,
                'type'                => 'open_calendar',
                'days'                => $this->getOpenCalGendays($open_calendar->id,$user->id,json_decode($open_calendar->days),$available_hours,$allow_booking_after)
            );
                
        //    }
        }else{
            // schedule calendar
        $schedules = ServiceSchedule::select('id','days','schedule_name','allow_booking_after','created_at','schedule_start_time','schedule_end_time','charges_per_session','clients_per_session','paid_by','charges_per')->where('user_id',$user->id)->get();

        // dd($schedules);
        $day_arr = [];
       
        foreach($schedules as $schedule)
        {
            $allow_booking_after = $schedule->allow_booking_after;
            $st_date = date('Y-m-d');
            $actual_end_date = date('Y-m-d',strtotime($st_date.'+6 days'));
            $end_dt =  date('Y-m-d',strtotime($st_date.'+'.($allow_booking_after - 1).'days'));
            //split monthly schedule or appoinment
            if($schedule->charges_per == 1){
                $appointment[] = array(
                    'id' => $schedule->id,
                    'schedule_name' => $schedule->schedule_name,
                    'allow_booking_after' => $schedule->allow_booking_after,
                    'start_date'    => $st_date,
                    'end_date'      => $end_dt,
                    'actual_end_date' => $actual_end_date,
                    'charges'       => $schedule->charges_per_session,
                    'start_time'    => $schedule->schedule_start_time,
                    'end_time'      => $schedule->schedule_end_time,
                    'paid_by'       => $schedule->paid_by,
                    'charges_per'   => $schedule->charges_per,
                    'type'          => 'schedule_calendar',
                    'days'          => $this->getdaystatus($schedule->id,json_decode($schedule->days),$schedule->clients_per_session,$allow_booking_after)
                );
            }else{
                $month_session[] = array(
                    'id' => $schedule->id,
                    'schedule_name' => $schedule->schedule_name,
                    'allow_booking_after' => $schedule->allow_booking_after,
                    'start_date'    => $st_date,
                    'end_date'      => $end_dt,
                    'actual_end_date' => $actual_end_date,
                    'charges'       => $schedule->charges_per_session,
                    'start_time'    => $schedule->schedule_start_time,
                    'end_time'      => $schedule->schedule_end_time,
                    'paid_by'       => $schedule->paid_by,
                    'charges_per'   => $schedule->charges_per,
                    'type'          => 'schedule_calendar',
                    'status'        => $this->checkMonthStatus($schedule->id,$schedule->clients_per_session,$month,$user->id)
                );
            }
          
        }
    }
         return response()->json(['appointment' => $appointment, 'month' => $month_session]);
    }
    

    public function getdaystatus($id,$days,$clients_per_session,$allow_booking_after)
    {
       
         $dates = [];
         $date = date('Y-m-d');

            for ($i=0; $i < 7 ; $i++) { 

                $dt = date('Y-m-d',strtotime($date.'+'.$i.'days'));
                $day = date('D',strtotime($dt));
                $day_num = date('N',strtotime($dt));

                if($day == 'Sun' || $day == 'sun')
                {
                    $day_num = 0;
                }
                $dates[] = array(
                    'date'    => $dt,
                    'day'     => $day,
                    'day_num' => $day_num,
                    'count'   => $i + 1
                );

            }
       
         foreach($dates as $dts){
            $slot_res = $this->getslotsAvailablestatus($id,$days,$dts['day_num'],$clients_per_session,$dts['count'],$allow_booking_after,$dts['date']);
            $result[$dts['day']] = $slot_res;
            
         }
         return $result;
       
    }
    
    //checkMonthStatus
    public function checkMonthStatus($schedule_id,$clients_per_session,$month,$userid){
        //fetch scheule worktime

       $schedule_worktime = ScheduleWorktime::where('schedule_id',$schedule_id)->get();
       
       $dates = $this->getMonthDate($month);
       $start_date = $dates['start']->format('Y-m-d');
       $end_date   = $dates['end']->format('Y-m-d');
       $next_start = $dates['next_start']->format('Y-m-d');
       $next_end   = $dates['next_end']->format('Y-m-d');

       $status = [];
       $startMonthName = date('F', strtotime($start_date));
       $nextMonthName = date('F', strtotime($next_start));
         $return_data = array( 

            $startMonthName => $this->getGeneralScheduleStatusByMonth($schedule_worktime,$dates,$userid,$clients_per_session,$start_date,$end_date),
            $nextMonthName  => $this->getGeneralScheduleStatusByMonth($schedule_worktime,$dates,$userid,$clients_per_session,$next_start,$next_end),

         );
        // print_r($return_data);die;
         ;
    //    for ($i=0; $i < 2; $i++) { 
        //   foreach($schedule_worktime as $worktime){
        //       $month_name = date('F', strtotime($start_date));
        //       $status[] = $this->getGeneralScheduleStatusByMonth($worktime,$dates,$userid,$clients_per_session);
        //   }
    //    }
      return $return_data;
      
       

    }

    //getGeneralScheduleStatusByMonth
    public function getGeneralScheduleStatusByMonth($schedule_worktime,$dates,$userid,$clients_per_session,$start_date,$end_date)
    {
        $status = "";
        foreach($schedule_worktime as $worktime){
            $user_bookings = UserBooking::where('service_provider_id',$userid)
                            ->where('service_type','schedule_calendar')
                            ->where('schedule_id',$worktime->schedule_id)
                            ->where('date', '>=',$start_date)
                            ->where('date', '<=',$end_date)
                            ->where('start_time',$worktime->start_time)
                            ->where('end_time',$worktime->end_time)
                            ->get();

            if(!empty($user_bookings)){
                if(count($user_bookings) < $clients_per_session){
                    $status = "Available";
                }
            }else{
                $status = "Not Available";
            }
        }

        if($status == "Available"){
            $status = $status;
        }else{
            $status = "Not Available";
        }
        
      
        

        return $status;
    }

    //add function to get month startdate and enddate from month number
    public function getMonthDate($month){
           $year = date('Y');
           $startdate = Carbon::create($year,$month,1)->startOfMonth();
           $enddate   = Carbon::create($year,$month,1)->endOfMonth();

           $next_month_start_date = Carbon::create($year,$month,1)->addMonth()->startOfMonth();
           $next_month_end_date   = Carbon::create($year,$month,1)->addMonth()->endOfMonth();
           return [
            'start'      => $startdate,
            'end'        => $enddate,
            'next_start' => $next_month_start_date,
            'next_end'   => $next_month_end_date
           ];
    }
    //getOpenCalGendays
    public function getOpenCalGendays($opencalid,$userid,$days,$available_hours,$allow_booking_after)
    {
         $dates = [];
         $date = date('Y-m-d');

            for ($i=0; $i < 7 ; $i++) { 

                $dt = date('Y-m-d',strtotime($date.'+'.$i.'days'));
                $day_name = date('D',strtotime($dt));
                $day_num = date('N',strtotime($dt));
                
                if($day_name == 'Sun' || $day_name == 'sun'){
                    $day_num = 0;
                }
                $dates[] = array(
                    'date'    => $dt,
                    'day'     => date('D',strtotime($dt)),
                    'day_num' => $day_num,
                    'count'   => $i + 1
                );

            }
            
            foreach($dates as $dts){
            $slot_res = $this->getOpenCalGeneralstatus($opencalid,$userid,$days,$dts['day_num'],$available_hours,$allow_booking_after,$dts['count'],$dts['date']);
            $result[$dts['day']] = $slot_res;
            
            }
         return $result;
    }

    //getOpenCalGeneralstatus
    public function getOpenCalGeneralstatus($opencalid,$userid,$days,$num,$available_hours,$allow_booking_after,$count,$date)
    {
        // for display only allowed booking days
        if($count > $allow_booking_after ){
            return 'Not Scheduled';
        }
        // $date = '2023-04-20';
         // check start_time greater than currenttime + 20 mins for today only
        // if($count == 1){
        // $open_calendar = OpenCalendar::where('user_id',$userid)
        //                  ->where('start_time','>',date('H:i:s',strtotime('+20 minutes')))
        //                  ->first();
        // }else{
        //     $open_calendar = OpenCalendar::where('user_id',$userid)->first();
        // }
        // check end time greater than currenttime  for today only
        if($count == 1){
        $open_calendar = OpenCalendar::where('user_id',$userid)
                         ->where('end_time','>',date('H:i:s'))
                         ->first();
        }else{
            $open_calendar = OpenCalendar::where('user_id',$userid)->first();
        }

        if(empty($open_calendar)){
            return 'Not Scheduled';
        }
        $calendarService = CalenderService::where('user_id',$userid)->first();
        $gap = $calendarService->gap_between_slots;
        $min_session = OpenCalendarSchedule::select('time_per_session')->where('open_calendar_id',$open_calendar->id)->min('time_per_session');
        
        if(in_array($num,$days)){
           $current_end_time = $open_calendar->start_time;
           $status_array = [];
        //    echo $current_end_time;die;
           while($current_end_time <= $open_calendar->end_time){
            
            $time1 = $current_end_time;
            $time2 = date('H:i:s',strtotime($current_end_time.'+ '.($min_session + $gap).' minutes'));
            $GenStatus = [];
            $GenStatus = UserBooking::where('service_provider_id',$userid)
                                    ->where('service_type','open_calendar')
                                    ->where('status',1)
                                    ->whereBetween('date',[$date,$date])
                                    ->where(function($query) use ($time1,$time2){
                                        $query->where(function($q) use ($time1, $time2) {
                                            $q->where('start_time', '<=', $time1)
                                              ->where('end_time', '>=', $time1);
                                        })
                                        ->orWhere(function($q) use ($time1, $time2) {
                                            $q->where('start_time', '<=', $time2)
                                              ->where('end_time', '>=', $time2);
                                        })
                                        ->orWhere(function($q) use ($time1, $time2) {
                                            $q->where('start_time', '>', $time1)
                                              ->where('end_time', '<', $time2);
                                        });
                                    })
                                  
                                    ->get();
                                    $timess[] = array(
                                        'st' => $time1,
                                        'et' => $time2
                                    );
            // $session = round(abs($st_time - $en_time)/60 , 2);
         
            if(count($GenStatus) == 0){
                $status_array[] = 'available';
              }
              $current_end_time =  date('H:i:s',strtotime($current_end_time.'+ '.($min_session + $gap).' minutes'));
           }
       
           if(in_array('available',$status_array)){
             return 'Available';
           }else{
            return 'Not Available';
           }
          

        }else{
            return 'Not Scheduled';
        }
    }
   
    public function getslotsAvailablestatus($id,$days,$day,$clients_per_session,$count,$allow_booking_after,$date){

        //to display only allowd booking after 
        if($count > $allow_booking_after)
        {
            return 'Not Scheduled';
        }
        $available_status = [];
        $status = 0;
        if(in_array($day,$days)){
            // check start_time greater than currenttime + 20 mins for today only
            if($count == 1){
                $work_time = ScheduleWorktime::select('schedule_worktime.start_time','schedule_worktime.end_time','service_schedules.charges_per_session')
                ->join('service_schedules','service_schedules.id' ,'=','schedule_worktime.schedule_id')
                ->where('schedule_worktime.schedule_id',$id)
                ->where('start_time','>',date('H:i:s',strtotime('+20 minutes')))
                ->get();
            }else{
                $work_time = ScheduleWorktime::select('schedule_worktime.start_time','schedule_worktime.end_time','service_schedules.charges_per_session')
                ->join('service_schedules','service_schedules.id' ,'=','schedule_worktime.schedule_id')
                ->where('schedule_worktime.schedule_id',$id)
                ->get();
            }
           
           
            if(count($work_time) == 0){
                return 'Not Scheduled';
            }
            // $start_date = date('Y-m-d');
            // $end_date = date('Y-m-d',strtotime('+6 days'));
            // dd($work_time);
            foreach($work_time as $time){
               
             if($count == 1){
                $available_status[] = UserBooking::where('schedule_id',$id)
                                                 ->where('date','<=',$date)
                                                 ->where('to_date','>=',$date)
                                                 ->where('status',1)
                                                 ->where('start_time','>=',date('H:i:s',strtotime('+20 minutes')))
                                                 ->where('end_time','<=',$time->end_time)
                                                ->where('service_type','!=','open_calendar')
                                                ->where('service_type','!=','discussion')
                                                ->get();
             }else{
                $available_status[] = UserBooking::where('schedule_id',$id)
                                                    //check bookings available in that particular date
                                                ->where('date','<=',$date)
                                                ->where('to_date','>=',$date)
                                                ->where('status',1)
                                                //for greater than current-time + 20 mins
                                                ->whereTime('start_time','>=',$time->start_time)
                                                // ->whereTime('start_time','>=',$time->start_time)
                                                ->whereTime('end_time','<=',$time->end_time)
                                                ->where('service_type','!=','open_calendar')
                                                ->where('service_type','!=','discussion')
                                                ->get();
             }
           
            }
           
            //check status
            foreach($available_status as $avail_state)
            {
                    // echo count($avail_state);
                    if(count($avail_state) < $clients_per_session){
                       $status += 1;
                    }
            }
           
            if($status <= 0){
                return 'Not Available';
            }else{
                return 'Available';
            }
            
            
            // dd(count($available_status));
           
        }else{
            return 'Not Scheduled';
        }
    }
   
    //opencalschedules by service provider id
    public function opencalschedules(Request $request)
    {
        $id = $request->service_provider_id;
        $time = $request->time;
        $date = $request->date;
        $open_calendar = OpenCalendar::where('user_id',$id)->first();
        $calendarService = CalenderService::where('user_id',$id)->first();
        $open_calendar_schedule = OpenCalendarSchedule::where('open_calendar_id',$open_calendar->id)->get();
        // dd($open_calendar_schedule);
        if($open_calendar_schedule->count() > 0)
        {
            $data = [];
            foreach($open_calendar_schedule as $schedule)
            {
                $session_wth_gap = $calendarService->gap_between_slots + $schedule->time_per_session;
                $end_time = date('H:i:s',strtotime($time.'+'.$session_wth_gap.' Minutes'));
              
                $user_booking = UserBooking::where('service_provider_id',$id)
                                ->where(function($query) use ($time,$date,$end_time){
                                        $query->where(function($q) use ($date,$time,$end_time){
                                                $q->where('date',$date)
                                                    ->where('start_time','<=',$time)
                                                    ->where('end_time','>=',$time);
                                        })
                                        ->orWhere(function($q) use ($date,$end_time){
                                            $q->where('date',$date)
                                            ->where('start_time','<=',$end_time)
                                            ->where('end_time','>=',$end_time);
                                        })
                                        ->orWhere(function($q) use ($date,$time,$end_time){
                                            $q->where('date',$date)
                                            ->where('start_time','>',$time)
                                            ->where('end_time','<',$end_time);
                                        });
                                })
                                ->get();
                // echo $end_time;die;
                $status = "";
                if($end_time <= $open_calendar->end_time){

                if(count($user_booking) > 0){
                    $status = "Not Available";
                }else{
                    $status = 'Available';
                }
                $data[] = array(
                      'time' => $schedule->time_per_session,
                      'price'    => $schedule->price,
                      'type'     => $schedule->type,
                      'status'   => $status
                );
             }
            }

        }else
        {
            $data = [];
        }
        // echo '<pre>';
        //  print_r($data);die;
        return response()->json($data);
     }

     //opencal_getminutes
     public function opencal_getminutes(Request $request)
     {
        $id = $request->service_provider_id;
        $time = $request->time;
        $date = $request->date;
        $minutes = [];
        $open_calendar = OpenCalendar::where('user_id',$id)->first();
        $min_session = OpenCalendarSchedule::select('time_per_session')->where('open_calendar_id',$open_calendar->id)->min('time_per_session');
        $calendarService = CalenderService::where('user_id',$id)->first();
        $gap = $calendarService->gap_between_slots;
        // dd($open_calendar);
        $cal_end    = date('H:i:s',strtotime($open_calendar->end_time.($min_session + $gap).' Minutes'));
        
        if($time < $open_calendar->start_time){
            $time = $open_calendar->start_time;
            $session_wth_gap = 300;
           
            // $end_time = date('H:i:s',strtotime($time.'+'.$session_wth_gap.' Minutes'));
            $st_time = date('H:00:00',strtotime($time));
            if($time == $st_time){
               $end_time = date('H:00:00',strtotime($time.'+ 1 Hour'));
            }else{
                $end_time = date('H:00:00',strtotime($st_time.'+1 Hour'));
            }
             
            $user_booking = UserBooking::where('service_provider_id',$id)
                            ->where(function($query) use ($time,$date,$end_time){
                                    $query->where(function($q) use ($date,$time,$end_time){
                                            $q->where('date',$date)
                                                ->where('start_time','<=',$time)
                                                ->where('end_time','>=',$time);
                                    })
                                    ->orWhere(function($q) use ($date,$end_time){
                                        $q->where('date',$date)
                                        ->where('start_time','<=',$end_time)
                                        ->where('end_time','>=',$end_time);
                                    })
                                    ->orWhere(function($q) use ($date,$time,$end_time){
                                        $q->where('date',$date)
                                        ->where('start_time','>',$time)
                                        ->where('end_time','<',$end_time);
                                    });
                            })
                            ->get();
                           
                            // dd($user_booking);
             if(count($user_booking) > 0)
             {
                  $diff_min = 0;
                  $total = '00:00:00';
                  $last_index = count($user_booking) - 1;
                  $current_end_time = "";
                //   echo $total;die;
                  foreach($user_booking as $k => $booking)
                  {
                     if($end_time >= $booking->end_time)  {
                        $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                        $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));

                        //Multiple of 5
                        $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                        $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);
                        
                        $gt_st_time = new DateTime($st_wht_gap);
                        $gt_e_time  = new DateTime($et_wth_gap);
                        $gt_interval = $gt_st_time->diff($gt_e_time);
                        $gt_diff    = $gt_interval->i;
                        if($gt_diff >= $min_session ){
                           //check slot endtime greater than cal_endtime
                            if($et_wth_gap <= $cal_end){

                                for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                    $minutes [] = date('H:i:s', $i);
                                }
                            }else{

                                for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                    $minutes [] = date('H:i:s', $i);
                                }
                            }
                        }else{
                        $minutes = [];
                        }
                       
                     }

                     if($k == 0 && $last_index != 0){
                        if($booking->start_time > $time){
                            $st_wht_gap = date('H:i:s',strtotime($time));
                            $et_wth_gap = date('H:i:s',strtotime($booking->start_time.'-'.$gap.' Minutes'));
                            // Multiple of 5
                            $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                            $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                            $gt_st_time = new DateTime($st_wht_gap);
                            $gt_e_time  = new DateTime($et_wth_gap);
                            $gt_interval = $gt_st_time->diff($gt_e_time);
                            $gt_diff    = $gt_interval->i;
                            if($gt_diff >= $min_session){
                               //check slot endtime greater than cal_endtime
                                if($et_wth_gap <= $cal_end){

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }else{

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }
                            }else{
                                $minutes = [];
                            }
                            

                        }
                    }elseif($k == 0 && $last_index == 0){

                        if($booking->start_time > $time){
                            $st_wht_gap = date('H:i:s',strtotime($time));
                            $et_wth_gap = date('H:i:s',strtotime($booking->start_time.'-'.$gap.' Minutes'));

                            // Multiple of 5
                            $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                            $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                            $gt_st_time = new DateTime($st_wht_gap);
                            $gt_e_time  = new DateTime($et_wth_gap);
                            $gt_interval = $gt_st_time->diff($gt_e_time);
                            $gt_diff    = $gt_interval->i;
                            if($gt_diff >= $min_session){
                               //check slot endtime greater than cal_endtime
                                if($et_wth_gap <= $cal_end){

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }else{

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }
                            }else{
                                $minutes = [];
                            }
                          

                        }

                        if($booking->end_time < $end_time){
                            $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                            $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));
                          
                            // Multiple of 5
                            $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                            $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                            $gt_st_time = new DateTime($st_wht_gap);
                            $gt_e_time  = new DateTime($et_wth_gap);
                            $gt_interval = $gt_st_time->diff($gt_e_time);
                            $gt_diff    = $gt_interval->i;
                            if($gt_diff >= $min_session){
                               //check slot endtime greater than cal_endtime
                                if($et_wth_gap <= $cal_end){

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }else{

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }
                            }else{
                                $minutes = [];
                            }
                            
                        }
                    }else{
                        if($booking->end_time < $end_time){
                            $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                            $et_wth_gap = date('H:i:s',strtotime($current_end_time.'-'.$gap.' Minutes'));
                            
                            // Multiple of 5    
                            $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);  
                            $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                            $gt_st_time = new DateTime($st_wht_gap);
                            $gt_e_time  = new DateTime($et_wth_gap);
                            $gt_interval = $gt_st_time->diff($gt_e_time);
                            $gt_diff    = $gt_interval->i;
                            if($gt_diff >= $min_session){
                               //check slot endtime greater than cal_endtime
                                if($et_wth_gap <= $cal_end){

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }else{

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }
                            }else{
                                $minutes = [];
                            }
                           
                        }
                    }

                    if($k == $last_index && $k != 0){
                        if($booking->end_time < $end_time){
                            $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                            $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));
                          
                            //Multiple of 5
                            $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                            $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                            $gt_st_time = new DateTime($st_wht_gap);
                            $gt_e_time  = new DateTime($et_wth_gap);
                            $gt_interval = $gt_st_time->diff($gt_e_time);
                            $gt_diff    = $gt_interval->i;
                            if($gt_diff >= $min_session){
                              //check slot endtime greater than cal_endtime
                                if($et_wth_gap <= $cal_end){

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }else{

                                    for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                        $minutes [] = date('H:i:s', $i);
                                    }
                                }
                            }else{
                                $minutes = [];
                            }
                            
                        }
                    }
                    
                    $current_end_time = $booking->start_time;
                    
                  }
                //  dd($minutes);
             }else{
                $st_wht_gap = date('H:i:s',strtotime($time));
                $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));
                
                //Multiple of 5
                $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                //check slot endtime greater than cal_endtime
                if($et_wth_gap <= $cal_end){

                    for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                        $minutes [] = date('H:i:s', $i);
                    }
                }else{

                    for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                        $minutes [] = date('H:i:s', $i);
                    }
                }
               
             }
            return response($minutes);
        }
        if($open_calendar->count() > 0)
        {
                 
                $session_wth_gap = 300;
                // $end_time = date('H:i:s',strtotime($time.'+'.$session_wth_gap.' Minutes'));
                $end_time = date('H:00:00',strtotime($time.'+ 1 Hour'));
                //  echo $end_time;die;
                $user_booking = UserBooking::where('service_provider_id',$id)
                                ->where(function($query) use ($time,$date,$end_time){
                                        $query->where(function($q) use ($date,$time,$end_time){
                                                $q->where('date',$date)
                                                    ->where('start_time','<=',$time)
                                                    ->where('end_time','>=',$time);
                                        })
                                        ->orWhere(function($q) use ($date,$end_time){
                                            $q->where('date',$date)
                                            ->where('start_time','<=',$end_time)
                                            ->where('end_time','>=',$end_time);
                                        })
                                        ->orWhere(function($q) use ($date,$time,$end_time){
                                            $q->where('date',$date)
                                            ->where('start_time','>',$time)
                                            ->where('end_time','<',$end_time);
                                        });
                                })
                                ->get();
                               
                                // dd($user_booking);
                 if(count($user_booking) > 0)
                 {
                      $diff_min = 0;
                      $total = '00:00:00';
                    //   echo $total;die;
                    //   foreach($user_booking as $booking)
                    //   {
                    //      if($end_time > $booking->end_time)  {
                    //         $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                    //         $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));
                    //         dd($et_wth_gap);
                    //         //check slot endtime greater than cal_endtime
                    //         if($et_wth_gap <= $cal_end){

                    //             for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 60) {
                    //                 $minutes [] = date('H:i:s', $i);
                    //             }
                    //             // dd($minutes);
                    //         }else{

                    //             for ($i = strtotime($st_wht_gap); $i <= strtotime($cal_end); $i += 60) {
                    //                 $minutes [] = date('H:i:s', $i);
                    //             }
                    //         }
                            
                    //      }
                    //   }
                    $diff_min = 0;
                    $total = '00:00:00';
                    $last_index = count($user_booking) - 1;
                    $current_end_time = "";
                    // dd($user_booking);
                    foreach($user_booking as $k => $booking)
                    {
                    //    if($end_time >= $booking->end_time)  {
                    //       $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                    //       $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));
  
                    //       $gt_st_time = new DateTime($st_wht_gap);
                    //       $gt_e_time  = new DateTime($et_wth_gap);
                    //       $gt_interval = $gt_st_time->diff($gt_e_time);
                    //       $gt_diff    = $gt_interval->i;
                    //       if($gt_diff >= $min_session ){
                    //          //check slot endtime greater than cal_endtime
                    //           if($et_wth_gap <= $cal_end){
  
                    //               for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 60) {
                    //                   $minutes [] = date('H:i:s', $i);
                    //               }
                    //           }else{
  
                    //               for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 60) {
                    //                   $minutes [] = date('H:i:s', $i);
                    //               }
                    //           }
                    //       }else{
                    //       $minutes = [];
                    //       }
                         
                    //    }
                    //    dd($last_index);;

                       if($k == 0 && $last_index != 0){

                       
                          if($booking->start_time > $time){
                              $st_wht_gap = date('H:i:s',strtotime($time));
                              $et_wth_gap = date('H:i:s',strtotime($booking->start_time.'-'.$gap.' Minutes'));
                              //Multiple of 5
                              $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                              $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                              $gt_st_time = new DateTime($st_wht_gap);
                              $gt_e_time  = new DateTime($et_wth_gap);
                              $gt_interval = $gt_st_time->diff($gt_e_time);
                              $gt_diff    = $gt_interval->i;
                              if($gt_diff >= $min_session){
                                 //check slot endtime greater than cal_endtime
                                  if($et_wth_gap <= $cal_end){
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }else{
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }
                              }else{
                                  $minutes = [];
                              }
                              
  
                          }
                      }elseif($k == 0 && $last_index == 0){
  
                          if($booking->start_time > $time){
                              $st_wht_gap = date('H:i:s',strtotime($time));
                              $et_wth_gap = date('H:i:s',strtotime($booking->start_time.'-'.$gap.' Minutes'));
  
                              //Multiple of 5
                              $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                              $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                              $gt_st_time = new DateTime($st_wht_gap);
                              $gt_e_time  = new DateTime($et_wth_gap);
                              $gt_interval = $gt_st_time->diff($gt_e_time);
                              $gt_diff    = $gt_interval->i;
                              if($gt_diff >= $min_session){
                                 //check slot endtime greater than cal_endtime
                                  if($et_wth_gap <= $cal_end){
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }else{
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }
                              }else{
                                  $minutes = [];
                              }
                            
  
                          }
  
                          if($booking->end_time < $end_time){
                              $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                              $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));
                            
                              //Multiple of 5
                              $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                              $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                              $gt_st_time = new DateTime($st_wht_gap);
                              $gt_e_time  = new DateTime($et_wth_gap);
                              $gt_interval = $gt_st_time->diff($gt_e_time);
                              $gt_diff    = $gt_interval->i;
                              if($gt_diff >= $min_session){
                                 //check slot endtime greater than cal_endtime
                                  if($et_wth_gap <= $cal_end){
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }else{
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }
                              }else{
                                  $minutes = [];
                              }
                              
                          }
                      }else{
                          if($booking->end_time < $end_time){
                              $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                              $et_wth_gap = date('H:i:s',strtotime($current_end_time.'-'.$gap.' Minutes'));
                              
                              //Multiple of 5
                              $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                              $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                              $gt_st_time = new DateTime($st_wht_gap);
                              $gt_e_time  = new DateTime($et_wth_gap);
                              $gt_interval = $gt_st_time->diff($gt_e_time);
                              $gt_diff    = $gt_interval->i;
                              if($gt_diff >= $min_session){
                                 //check slot endtime greater than cal_endtime
                                  if($et_wth_gap <= $cal_end){
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }else{
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }
                              }else{
                                  $minutes = [];
                              }
                             
                          }
                      }
  
                      if($k == $last_index && $k != 0){
                          if($booking->end_time < $end_time){
                              $st_wht_gap = date('H:i:s',strtotime($booking->end_time));
                              $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));
                              
                              //Multiple of 5
                              $st_wht_gap = $this->get_mins_multipleof($st_wht_gap);
                              $et_wth_gap = $this->get_mins_multipleof($et_wth_gap);

                              $gt_st_time = new DateTime($st_wht_gap);
                              $gt_e_time  = new DateTime($et_wth_gap);
                              $gt_interval = $gt_st_time->diff($gt_e_time);
                              $gt_diff    = $gt_interval->i;
                              if($gt_diff >= $min_session){
                                //check slot endtime greater than cal_endtime
                                  if($et_wth_gap <= $cal_end){
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }else{
  
                                      for ($i = strtotime($st_wht_gap); $i < strtotime($cal_end); $i += 300) {
                                          $minutes [] = date('H:i:s', $i);
                                      }
                                  }
                              }else{
                                  $minutes = [];
                              }
                              
                          }
                      }
                      
                      $current_end_time = $booking->start_time;
                      
                    }
                    //  dd($minutes);
                 }else{
                    
                    $st_wht_gap = date('H:i:s',strtotime($time));
                    $st_wht_gap = $this->get_mins_multipleof($time);
                    $et_wth_gap = date('H:i:s',strtotime($end_time.'-'.$gap.' Minutes'));
                      //check slot endtime greater than cal_endtime
                     
                      if($et_wth_gap <= $cal_end){

                        for ($i = strtotime($st_wht_gap); $i < strtotime($et_wth_gap); $i += 300) {
                            $minutes [] = date('H:i:s', $i);
                        }
                      }else{

                        for ($i = strtotime($st_wht_gap); $i <= strtotime($cal_end); $i += 300) {
                            $minutes [] = date('H:i:s', $i);
                        }
                      }
                  
                 }
            

        }else
        {
            $minutes = [];
        }
        // echo '<pre>';
        //  print_r($data);die;
        return response()->json($minutes);
     }

  
     public function get_mins_multipleof($start_time = null){
           
        $carbonTime = Carbon::parse($start_time);
        $multipleOf = 5;
        $reminder = $carbonTime->minute % $multipleOf;
        if($reminder == 0){
            return $carbonTime->format('H:i:s');
        }
        $carbonTime->addMinutes($multipleOf - $reminder);
        
        return $carbonTime->format('H:i:s');
     }

   //checktime_is_available
   public function checktime_is_available(Request $request)
   {
     $type = $request->type;
     if($type == "open_calendar")
     {
        if($request->date != "" && $request->from_time != "" && $request->session_time != "" && $request->service_provider_id != ""){
            $calendarService = CalenderService::where('user_id',$request->service_provider_id)->first();
            $gap = $calendarService->gap_between_slots;
            $from_time = $request->from_time;
            $to_time = date('H:i:s',strtotime($from_time.'+'.$request->session_time.' Minutes'));
            $to_time_wth_gap = date('H:i:s',strtotime($to_time.'+'.$gap.' Minutes'));
            // dd($to_time_wth_gap);
             $user_booking = UserBooking::where('service_provider_id',$request->service_provider_id)
                                          ->where('date',$request->date)
                                          ->where('status',1)
                                          ->where(function($query) use ($from_time,$to_time_wth_gap){
                                             $query->where(function($q) use ($from_time){
                                                $q->where('start_time','<',$from_time)
                                                  ->where('end_time','>',$from_time);
                                             })
                                             ->orWhere(function($q) use ($to_time_wth_gap){
                                                 $q->where('start_time','<',$to_time_wth_gap)
                                                   ->where('end_time','>',$to_time_wth_gap);
                                             })
                                             ->orWhere(function($q) use ($from_time,$to_time_wth_gap){
                                                 $q->where('start_time','>',$from_time)
                                                    ->where('end_time','<',$to_time_wth_gap);
                                             });
                                          })
                                          ->get();
            // dd($user_booking);
           if(count($user_booking) == 0)
           {
            $result = 'Available';
           }else{
            $result = 'Not Available';
           }
        }else{
            return response('Required fields are missing');
        }
     }else{
        if($request->service_provider_id != "" && $request->date != "" && $request->from_time != "" && $request->to_time != "" && $request->schedule_id != ""){
            $service_schedule = ServiceSchedule::findOrFail($request->schedule_id);
            $type = $service_schedule->charges_per;
            // dd($service_schedule);
            $clients_per_session = $service_schedule->clients_per_session;
            if($type == 1){
                //appoinment
                    $user_booking = UserBooking::where('service_provider_id',$request->service_provider_id)
                                                ->where('schedule_id',$request->schedule_id)
                                                ->where('date',$request->date)
                                                ->where('status',1)
                                                ->where('start_time','>=',$request->from_time)
                                                ->where('end_time','<=',$request->to_time)
                                                ->get();
                    
                    if(count($user_booking) < $clients_per_session){
                        $result = 'Available';
                    }else{
                        $result = 'Not Available';
                    }
            }else{
               //month
                     $date = $request->date;
                    $user_booking = UserBooking::where('service_provider_id',$request->service_provider_id)
                                                ->where('schedule_id',$request->schedule_id)
                                                ->where('start_time','>=',$request->from_time)
                                                ->where('end_time','<=',$request->to_time)
                                                ->where('status',1)
                                                ->where(function($query) use ($date){
                                                    $query->where(function($q) use ($date){
                                                        $q->where('date','<=',$date)
                                                          ->where('to_date','>=',$date);
                                                    })
                                                    ->orWhere(function($q) use ($date){
                                                         $q->where('date','>=',$date)
                                                           ->where('to_date','<=',$date);
                                                    });
                                                })
                                                
                                                ->get();
                    // dd($user_booking);
                    if(count($user_booking) < $clients_per_session){
                    $result = 'Available';
                    }else{
                    $result = 'Not Available';
                    }
            }
        }else{
            echo json_encode('Required fields are missing');
        }
     }

       return response()->json($result);
   }


   //discussion_slots 
   public function discussion_slots(Request $request,$id)
   {
      $user = User::findOrFail($id);
      $discussion_service = DiscussionService::where('user_id',$user->id)->first();
     
      if($discussion_service->count() > 0){
      $start_time = $discussion_service->start_time;
      $end_time = $discussion_service->end_time;

    
        $times[] =array(
            'id'           => $discussion_service->id,
             'start_date'  => date('Y-m-d'),
             'end_date'    => date('Y-m-d',strtotime('+6 days')),
             'actual_end_date' => date('Y-m-d',strtotime('+6 days')),
             'start_time'  => $start_time,
             'end_time'    => $end_time,
             'charges'     => $discussion_service->total_amount,
             'type'        => "discussion",
             'paid_by'     => 1,
             'days'        => $this->discussion_dates($start_time,$end_time,$user->id,json_decode($discussion_service->days))
        ); 
      
    }else{
        $times = [];
    }
// die;
    return response()->json($times);
     
   }

   //checkDiscussionServiceStatus
   public function discussion_dates($start_time,$end_time,$id,$days)
   {
     $dates = [];
     $date = date("Y-m-d");
     for ($i=0; $i < 7 ; $i++) { 
         $dt = date("Y-m-d",strtotime($date.'+'.$i.' days'));
         $day = date('D',strtotime($dt));
         $day_num = date('N',strtotime($dt));

         if($day == "Sun" || $day == "sun"){
            $day_num = 0;
         }
        $dates[] = array(
            'date'    => $dt,
            'day'     => $day,
            'day_num' => $day_num,
            'count'   => $i + 1
        );
       
     }

    foreach($dates as $d_date){
         $dis_status = $this->checkdiscussion_status($d_date,$id,$days,$start_time,$end_time,$d_date['count'],$d_date['day_num']);
         $result[$d_date['day']] = $dis_status;
    }

    return $result;
     
   }


   public function dicussion_details(Request $request,$id,$daystring){
       $discussion_service_id = $id;
       $day_num = $this->get_daynum_from_daystring($daystring);
       
       $discussion_service = DiscussionService::find($discussion_service_id);
       
       $todaystring = date('D',strtotime('today'));
       
       if($daystring == $todaystring || $daystring == strtolower($todaystring)){
          $date = date('Y-m-d');
       }else{
          $date = date('Y-m-d',strtotime('next '.$daystring));
       }
      
       $discussionData  = [];
       if(!empty($discussion_service)){
          $discussionData = array(
            'day'          => $daystring,
            'id'           => $discussion_service->id,
            'name'         => "",
            'start_time'   => $discussion_service->start_time,
            'end_time'     => $discussion_service->end_time,
            'date'         => $date,
            'days'         => json_decode($discussion_service->days),
            'clients_per_session' => 1,
            'charges_per_session' => $discussion_service->total_amount,
            'type'         => 'discussion',
            'paid_by'      => 1,
            'charges_per'  => 1,
            'slots'        => $this->detailed_discussion_slot_status($id,$date,$day_num)
          );

          
       }

       return response()->json($discussionData);
       
   }
   /**
    *  detailed_discussion_slot_status
    */

    public function detailed_discussion_slot_status($id,$date,$day_num){

        $discussion_service = DiscussionService::find($id);
        $start_time = $discussion_service->start_time;
        $end_time = $discussion_service->end_time;
        $days = json_decode($discussion_service->days);
        $interval = $discussion_service->time_per_session;
        $current_time = $start_time;
        $slots = [];

        if(in_array($day_num,$days)){

        while($current_time < $end_time){

            $current_end_time = date('H:i:s',strtotime($current_time.'+'.$interval.' minutes'));
            
             $user_bookings = UserBooking::where('service_provider_id',$discussion_service->user_id)
                                         ->where('service_type','discussion')
                                         ->where('date',$date)
                                         ->where('start_time','>=',$current_time)
                                         ->where('end_time','<=',$current_end_time)
                                         ->where('status',1)
                                         ->get();
            $total_bookings_count = $user_bookings->count();
            if($total_bookings_count > 0){
                $Available_status = "Not Available";
                $available_client_count = 0;
            }else{
                $Available_status = "Available";
                $available_client_count = 1;
            }

            $slots[] = array(
                'start_time'  => $current_time,
                'end_time'    => $current_end_time,
                'charges'     => $discussion_service->total_amount,
                'available_clients_count' => $available_client_count,
                'booked_clients_count'    => $total_bookings_count,
                'is_available'            => $Available_status
            );

            $current_time = date('H:i:s',strtotime($current_time.'+'.$interval.' minutes'));

        }

       
    } else{
        $slots = [];
    }

    return $slots;
   }
   //checkdiscussion_status
   public function checkdiscussion_status($date,$id,$days,$start_time,$end_time,$count,$num)
   {
    
      if(in_array($num,$days)){
        $discussion_service = DiscussionService::where('user_id',$id)->first();
        $interval = $discussion_service->time_per_session;
        $current_time = $start_time;
        $discussion_status = [];
       
        //start_time should be greater than current time + 20 mins for current date only
         if($count == 1){
          
            while($current_time < $end_time){

                $current_end_time = date('H:i:s',strtotime($current_time.'+'.$interval.' minutes'));
                
         
                        if($current_time >= date('H:i:s',strtotime('+20 Minutes'))){
                            
                        
                        $user_booking = UserBooking::where('service_provider_id',$id)
                                                ->where('service_type','discussion')
                                                ->where('date',$date)
                                                ->where('status',1)
                                                ->where('start_time','>=',$current_time)
                                                ->where('end_time','<=',$current_end_time)
                                                ->get();
                        //    dd($user_booking);
                            if($user_booking->count() == 0){
                                $discussion_status[] = 'Available';
                            }else{
                                $discussion_status[] = 'Not Available';
                            }

                        }else{
                            $status = "Not Scheduled";
                        }

                  
               $current_time = date('H:i:s',strtotime($current_time.'+'.$interval.' minutes'));

               if(in_array('Available',$discussion_status)){
                  $status = "Available";
               }else{
                $status = "Not Available";
               }
           }

         }else{
           
            while($current_time < $end_time){

                $current_end_time = date('H:i:s',strtotime($current_time.'+'.$interval.' minutes'));
                
         
                $user_booking = UserBooking::where('service_provider_id',$id)
                                            ->where('service_type','discussion')
                                            ->where('date',$date)
                                            ->where('status',1)
                                            ->where('start_time','>=',$current_time)
                                            ->where('end_time','<=',$current_end_time)
                                            ->get();

                if($user_booking->count() == 0){
                    $discussion_status[] = 'Available';
                }else{
                    $discussion_status[] = 'Not Available';
                }
                $current_time = date('H:i:s',strtotime($current_time.'+'.$interval.' minutes'));


               if(in_array('Available',$discussion_status)){
                    $status = "Available";
                }else{
                    $status = "Not Available";
                }
          }

         }

         return $status;

      }else{
        return 'Not Scheduled';
      }
   
   }

   //discussion_slot_status
   public function discussion_slot_status(Request $request)
   {
      $daystring = $request->daystring;
      $user = User::findOrFail($request->service_provider_id);
      $start_time = $request->start_time;
      $end_time = $request->end_time;
      $todaystr = date('D');

      if($daystring == $todaystr){
        $date = date('Y-m-d');
      }

      elseif($daystring == 'Mon' || $daystring == 'mon'){
        $date = date('Y-m-d',strtotime('next monday'));
      }elseif($daystring == 'Tue' || $daystring == 'tue'){
        $date = date('Y-m-d',strtotime('next tuesday'));
      }elseif($daystring == 'Wed' || $daystring == 'wed'){
        $date = date('Y-m-d',strtotime('next wednesday'));
      }elseif($daystring == 'Thu' || $daystring == 'thu'){
        $date = date('Y-m-d',strtotime('next thursday'));
      }elseif($daystring == 'Fri' || $daystring == 'fri'){
        $date = date('Y-m-d',strtotime('next friday'));
      }elseif($daystring == 'Sat' || $daystring == 'sat'){
        $date = date('Y-m-d',strtotime('next saturday'));
      }elseif($daystring == 'Sun' || $daystring == 'sun'){
        $date = date('Y-m-d',strtotime('next sunday'));
      }elseif($daystring == $todaystr)
      {
        $date = date('Y-m-d');
      }
      
      $user_booking = UserBooking::where('service_type','discussion')
                                 ->where('service_provider_id',$user->id)
                                 ->where('date',$date)
                                 ->where('status',1)
                                 ->where('start_time','>=',$start_time)
                                 ->where('end_time','<=',$end_time)
                                 ->get();
    //    dd($date);
      if($user_booking->count() > 0){
        $status = 'Not Available '.$date.'';
      }else{
        $status = 'Available '.$date.'';
      }
      return response()->json($status);
      
      

   }

   //get_user_bookings
   public function get_user_bookings(Request $request)
   {
    
      $type = $request->type;
      $id = $request->id;
      $user_data = [];
      
       if($type == "provider"){
          
           $schedule_ids = [];
           $current_date = date('Y-m-d');
           $past_seven_days = date('Y-m-d',strtotime('-6 days'));
        
           $user_booking = UserBooking::where('service_provider_id',$id)
                                      ->where('date','>=',$past_seven_days)
                                      ->orderBy('to_date','desc')
                                      ->get();
        //    dd($user_booking);
           $refund_request_count     = 0;
           $reschedule_request_count = 0;
           $available_slots_count    = 0;
         
           foreach($user_booking as $booking){
            $refund_request_count     = 0;
            $reschedule_request_count = 0;
            $available_slots_count    = 0;
            $price = 0;
            $user_profile = ModelsUserProfile::where('user_id',$id)->first();
            $offered_service = Category::where('id',$user_profile->service_offered)->pluck('category_name')->first();
          
            $service_category = Category::where('id',$user_profile->service_category)->pluck('category_name')->first();
            
            $user = User::findOrFail($booking->customer_id);
        
            //update schedule status
            if($booking->to_date <= date('Y-m-d') && $booking->end_time < date('H:i:s') && $booking->status != 2 && $booking->status != 3){
                UserBooking::where('id',$booking->id)
                ->update(['status' => 4]);
            }
        
            //find schedule status
            $schedule_status = "";
                if(strtotime($booking->to_date) >= time() && strtotime($booking->date) >= time()){
                    $schedule_status = "future";
                }elseif(strtotime($booking->to_date) <= time() && strtotime($booking->date) <= time()){
                    $schedule_status = "past";
                }else{
                    $schedule_status = "present";
                }

            //reschedule_request status
            $reschedule_request = UserBooking::where('service_provider_id',$id)
                                             ->where('schedule_id',$booking->schedule_id)
                                             ->where('date',$booking->date)
                                             ->where('start_time',$booking->start_time)
                                             ->where('end_time',$booking->end_time)
                                             ->where('reschedule_request',1)
                                             ->where('requested_by','provider')
                                             ->get();

            if(count($reschedule_request) > 0){
               $reschedule_request_status = 1;
            }else{
                $reschedule_request_status = 0;
            }
            //refund_request status
            $refund_request = UserBooking::where('service_provider_id',$id)
                                             ->where('schedule_id',$booking->schedule_id)
                                             ->where('date',$booking->date)
                                             ->where('start_time',$booking->start_time)
                                             ->where('end_time',$booking->end_time)
                                             ->where('refund_request',1)
                                             ->where('requested_by','provider')
                                             ->get();

            if(count($refund_request) > 0){
               $refund_request_status = 1;
            }else{
               $refund_request_status = 0;
            }

            if($booking->service_type == "open_calendar"){
                $open_calendar = OpenCalendar::findOrFail($booking->schedule_id);
                $bk_from = new DateTime($booking->start_time);
                $bk_to   = new DateTime($booking->end_time);
                $bk_interval = $bk_from->diff($bk_to);
                $bk_diff = $bk_interval->i;
                $open_calendar_schedule = OpenCalendarSchedule::where('open_calendar_id',$booking->schedule_id)
                                                               ->where('time_per_session',$bk_diff)->first();
                $price = $open_calendar_schedule->price;

                $refund_request_count = $booking->refund_request;
                $reschedule_request_count = $booking->reschedule_request;
                $available_slots_count = 0;

                //check bookings status is completed or not
                $status = "";
                if($booking->to_date == date('Y-m-d') &&  date('H:i:s') > $booking->end_time && $booking->status != 2 && $booking->status != 3){
                 
                   $status = COMPLETED;
                }else{
                  $status = $booking->status;
                }

                $user_data[] = array(
                    'id'           => $booking->id,
                    'customer_id'  => $booking->customer_id,
                    'booking_id'   => $booking->booking_id,
                    'service_provider_id' => $booking->service_provider_id,
                    'service_type' => $booking->service_type,
                    'schedule_name' => "",
                    'schedule_id'  => $booking->schedule_id,
                    'from_date'         => $booking->date,
                    'start_time'   => $booking->start_time,
                    'end_time'     => $booking->end_time,
                    'status'       => $status,
                    'to_date'      => $booking->to_date,
                    'days'         => $open_calendar->days,
                    'profile_pic'  => url('storage/profile_image/'.$user->profile_picture),
                    'user_name'    => $user->username,
                    'xmppid'       => $user->xmppid,
                    'offered_service' => $offered_service,
                    'service_category' => $service_category,
                    'price'        => $price,
                    'paid_by'      => $open_calendar->paid_by,
                    'refund_request_count' => intval($refund_request_count),
                    'reschedule_request_count' => intval($reschedule_request_count),
                    'clients_per_session'      => 1,
                    'available_slots_count'    => $available_slots_count,
                    'refund_request_status'    => $refund_request_status,
                    'reschedule_request_status' => $reschedule_request_status,
                    'schedule_status'           => $schedule_status,
                    'button'              => $this->checkStartBtnStatus($booking->service_provider_id,$booking->service_type,$booking->schedule_id,$booking->date,$booking->start_time,$booking->end_time)
                 );
                 
            }elseif($booking->service_type == "schedule_calendar"){
                 $user_data = $this->group_schedulecal_slots($id,$refund_request_status,$reschedule_request_status);
                // if(!in_array($booking->schedule_id,$schedule_ids)){
                    
                
                //     $service_schedule = ServiceSchedule::findOrFail($booking->schedule_id);
                //     $price = $service_schedule->charges_per_session;
                //     //get count of total booked slots for this schedule id
                //     $slot_booking = UserBooking::where('schedule_id',$booking->schedule_id)
                //                             ->where('service_provider_id',$id)
                //                             ->where('service_type','schedule_calendar')
                //                             ->where('schedule_id',$booking->schedule_id)
                //                             ->where('date',$booking->date)
                //                             ->where('start_time',$booking->start_time)
                //                             ->where('end_time',$booking->end_time)
                //                             ->get();
                //     // get refund request count & reschedule_request count
                //     $reschedule_request_count = UserBooking::where('schedule_id',$booking->schedule_id)
                //                             ->where('service_provider_id',$id)
                //                             ->where('service_type','schedule_calendar')
                //                             ->where('schedule_id',$booking->schedule_id)
                //                             ->where('date',$booking->date)
                //                             ->where('start_time',$booking->start_time)
                //                             ->where('end_time',$booking->end_time)
                //                             ->sum('reschedule_request');

                //     $refund_request_count = UserBooking::where('schedule_id',$booking->schedule_id)
                //                             ->where('service_provider_id',$id)
                //                             ->where('service_type','schedule_calendar')
                //                             ->where('schedule_id',$booking->schedule_id)
                //                             ->where('date',$booking->date)
                //                             ->where('start_time',$booking->start_time)
                //                             ->where('end_time',$booking->end_time)
                //                             ->sum('refund_request');
                   
                //     $available_slots_count =$service_schedule->clients_per_session -  count($slot_booking);
                //     $user_data[] = array(
                //         'id'           => $booking->id,
                //         'customer_id'  => $booking->customer_id,
                //         'schedule_name'=> $service_schedule->schedule_name,
                //         'service_provider_id' => $booking->service_provider_id,
                //         'service_type' => $booking->service_type,
                //         'schedule_id'  => $booking->schedule_id,
                //         'from_date'         => $booking->date,
                //         'start_time'   => $service_schedule->schedule_start_time,
                //         'end_time'     => $service_schedule->schedule_end_time,
                //         'status'       => $booking->status,
                //         'to_date'      => $booking->to_date ?? $booking->date,
                //         'profile_pic'  => url('storage/profile_image/'.$user->profile_picture),
                //         'user_name'    => $user->username,
                //         'offered_service' => $offered_service,
                //         'service_category' => $service_category,
                //         'price'        => $price,
                //         'paid_by'      => $service_schedule->paid_by,
                //         'refund_request_count' => $refund_request_count,
                //         'reschedule_request_count' => $reschedule_request_count,
                //         'clients_per_session' => $service_schedule->clients_per_session,
                //         'available_slots_count'    => $available_slots_count
                //     );
                //     $schedule_ids[]   = $booking->schedule_id;
                //     $schedule_dates[] = $booking->date;
                //     $schedule_from[]  = $booking->start_time;
                //     $schedule_to[]    = $booking->end_time;

                    // }
            }elseif($booking->service_type == "discussion"){
               
                $discussion_service = DiscussionService::where('user_id',$booking->service_provider_id)->first();
                $price = $discussion_service->total_amount;
                 //check bookings status is completed or not
                 $status = "";
                 if($booking->to_date == date('Y-m-d') &&  date('H:i:s') > $booking->end_time && $booking->status != 2 && $booking->status != 3){
                  
                    $status = COMPLETED;
                 }else{
                   $status = $booking->status;
                 }
                $user_data[] = array(
                    'id'           => $booking->id,
                    'customer_id'  => $booking->customer_id,
                    'booking_id'   => $booking->booking_id,
                    'service_provider_id' => $booking->service_provider_id,
                    'service_type' => $booking->service_type,
                    'schedule_name'=> "",
                    'schedule_id'  => $booking->schedule_id,
                    'from_date'         => $booking->date,
                    'start_time'   => $booking->start_time,
                    'end_time'     => $booking->end_time,
                    'status'       => $status,
                    'days'         => $discussion_service->days,
                    'to_date'      => $booking->to_date,
                    'profile_pic'  => url('storage/profile_image/'.$user->profile_picture),
                    'user_name'    => $user->username,
                    'xmppid'       => $user->xmppid,
                    'offered_service' => $offered_service,
                    'service_category' => $service_category,
                    'price'        => $price,
                    'paid_by'      => 1,
                    'refund_request_count' => intval($booking->refund_request),
                    'reschedule_request_count' => intval($booking->reschedule_request),
                    'clients_per_session'      => 1,
                    'available_slots_count'    => $available_slots_count,
                    'schedule_status'          => $schedule_status,
                    'button'                   => $this->checkStartBtnStatus($booking->service_provider_id,$booking->service_type,$booking->schedule_id,$booking->date,$booking->start_time,$booking->end_time)

                 );
            }
            
            
           }
           
        //    $user_booking = array_merge($user_booking,$user_data);
       }else{
           $past_seven_days = date('Y-m-d',strtotime('-6 days'));
           $user_booking = UserBooking::where('customer_id',$id)
                                        ->where('date','>=',$past_seven_days)
                                        ->orderBy('to_date','desc')
                                        ->get();
           
           
           foreach($user_booking as $booking){
            $price = 0;
            $user_profile = ModelsUserProfile::where('user_id',$booking->service_provider_id)->first();
            $offered_service = Category::where('id',$user_profile->service_offered)->pluck('category_name')->first();
            $service_category = Category::where('id',$user_profile->service_category)->pluck('category_name')->first();
            $user = User::findOrFail($booking->service_provider_id);

             //find schedule status
             $schedule_status = "";
             if(strtotime($booking->to_date) >= time() && strtotime($booking->date) >= time()){
                 $schedule_status = "future";
             }elseif(strtotime($booking->to_date) <= time() && strtotime($booking->date) <= time()){
                 $schedule_status = "past";
             }else{
                 $schedule_status = "present";
             }

            //refund_request_count
            $refund_request_counts = UserBooking::where('service_provider_id',$booking->service_provider_id)
                                                ->where('schedule_id',$booking->schedule_id)
                                                ->where('service_type',$booking->service_type)
                                                ->where('date',$booking->date)
                                                ->where('start_time',$booking->start_time)
                                                ->where('end_time',$booking->end_time)
                                                ->where('refund_request',1)
                                                ->where('requested_by','taker')
                                                ->count();
             //reschedule_request count
            $reschedule_request_count = UserBooking::where('service_provider_id',$booking->service_provider_id)
                                                ->where('schedule_id',$booking->schedule_id)
                                                ->where('service_type',$booking->service_type)
                                                ->where('date',$booking->date)
                                                ->where('start_time',$booking->start_time)
                                                ->where('end_time',$booking->end_time)
                                                ->where('reschedule_request',1)
                                                ->where('requested_by','taker')
                                                ->count();

            $days = null;
            if($booking->service_type == "open_calendar"){
                $open_calendar_schedule = OpenCalendarSchedule::findOrFail($booking->schedule_id);
                $open_calendar = OpenCalendar::findOrFail($open_calendar_schedule->open_calendar_id);
                // $days = $open_calendar->days;
                $daystring = date('D',strtotime($booking->date));
                $days[] = $this->get_daynum_from_daystring($daystring);
                $price = $open_calendar_schedule->price;
            }elseif($booking->service_type == "schedule_calendar"){
                $service_schedule = ServiceSchedule::findOrFail($booking->schedule_id);
                $price = $service_schedule->charges_per_session;
                $days = $service_schedule->days;
            }elseif($booking->service_type == "discussion"){
                $discussion_service = DiscussionService::where('user_id',$booking->service_provider_id)->first();
                $price = $discussion_service->total_amount;
                // $days = $discussion_service->days;
                $daystring = date('D',strtotime($booking->date));
                $days[] = $this->get_daynum_from_daystring($daystring);
            }

              //check bookings status is completed or not
              $status = "";
              if($booking->to_date == date('Y-m-d') &&  date('H:i:s') > $booking->end_time && $booking->status != 2 && $booking->status != 3){
               
                 $status = COMPLETED;
              }else{
                $status = $booking->status;
              }
             

            $user_data[] = array(
                'id'                       => $booking->id,
                'customer_id'              => $booking->customer_id,
                'booking_id'               => $booking->booking_id,
                'service_provider_id'      => $booking->service_provider_id,
                'service_type'             => $booking->service_type,
                'schedule_id'              => $booking->schedule_id,
                'from_date'                => $booking->date,
                'start_time'               => $booking->start_time,
                'end_time'                 => $booking->end_time,
                'status'                   => $status,
                'days'                     => $days,
                'to_date'                  => $booking->to_date ?? $booking->date,
                'profile_pic'              => url('storage/profile_image/'.$user->profile_picture),
                'user_name'                => $user->username,
                'xmppid'                   => $user->xmppid,
                'offered_service'          => $offered_service,
                'service_category'         => $service_category,
                'price'                    => $price,
                'reschedule_request_status'       => $booking->reschedule_request,
                'refund_request_status'           => $booking->refund_request,
                'refund_request_count'     => $refund_request_counts,
                'reschedule_request_count' => $reschedule_request_count,
                'schedule_status'          => $schedule_status,
                'button'                   => $this->checkJoinBtnStatus($booking->service_provider_id,$booking->service_type,$booking->schedule_id,$booking->date,$booking->start_time,$booking->end_time)
             );
           }
       }
       return response()->json($user_data);
   }
   
   //group_schedulecal_slots
   public function group_schedulecal_slots($id,$refund_request_status,$reschedule_request_status){
    
    $past_seven_days = date('Y-m-d',strtotime('-6 days'));

    $user_booking = UserBooking::where('service_provider_id',$id)
                               ->where('date','>=',$past_seven_days)
                               ->where('service_type','schedule_calendar')
                               ->orderBy('to_date','desc')
                               ->get();

    $bookings = collect($user_booking)->groupBy(function($booking){
              return $booking->schedule_id . $booking->date . $booking->start_time . $booking->end_time;
    })->values();

   
    foreach($bookings as $nestedcollection){

        foreach($nestedcollection as $booking){
            // $on_going = false;
            
            $current_date = date('Y-m-d');
            $start_timestamp = strtotime($booking->date);
            $end_timestamp = strtotime($booking->to_date) ?? $booking->date;
            $date_to_check_timestamp = strtotime($current_date);
            // dd($date_to_check_timestamp);
            if (($date_to_check_timestamp >= $start_timestamp) && ($date_to_check_timestamp <= $end_timestamp)) {
                $on_going = true;
            } else {
                $on_going = false;
            }
            $user_profile = ModelsUserProfile::where('user_id',$id)->first();
            $offered_service = Category::where('id',$user_profile->service_offered)->pluck('category_name')->first();
            $service_category = Category::where('id',$user_profile->service_category)->pluck('category_name')->first();
            $user = User::findOrFail($booking->customer_id);

            $service_schedule = ServiceSchedule::findOrFail($booking->schedule_id);
            
            /**
             *  find available days depending upon appointment & month
             */
            $bookingAvailableDays = [];
            if($service_schedule->charges_per == 1){
                 $daystring = date('D',strtotime($booking->date));
                 $day_num = $this->get_daynum_from_daystring($daystring);
                 
                $bookingAvailableDays = [$day_num];
                
            }else{
                $daystring = date('D',strtotime('today'));
                
                $day_num = $this->get_daynum_from_daystring($daystring);
                
                $all_sessions = All_session::where('schedule_id',$booking->schedule_id)
                                            ->where('service_provider_id',$booking->service_provider_id)
                                            ->where('date','>=',date('Y-m-d'))
                                            ->where('date','>=',$booking->date)
                                            ->where('date','<=',$booking->to_date)
                                            ->get();
                $session_daynum = [];
                if($all_sessions->count() > 0){
                  
                    foreach($all_sessions as $session){
                          
                         $session_daystring = "";
                         $session_daystring = date('D',strtotime($session->date));
                       
                         $session_daynum[] = $this->get_daynum_from_daystring($session_daystring);

                         $session_daynum = array_unique($session_daynum);
                    }

                   
                } 
                $bookingAvailableDays = $session_daynum;
            }
            // dd($booking->start_date);
                $price = $service_schedule->charges_per_session;
                //get count of total booked slots for this schedule id
                $slot_booking = UserBooking::where('schedule_id',$booking->schedule_id)
                                        ->where('service_provider_id',$id)
                                        ->where('service_type','schedule_calendar')
                                        ->where('schedule_id',$booking->schedule_id)
                                        ->where('date',$booking->date)
                                        ->where('start_time',$booking->start_time)
                                        ->where('end_time',$booking->end_time)
                                        ->get();
                // get refund request count & reschedule_request count
                $reschedule_request_count = UserBooking::where('schedule_id',$booking->schedule_id)
                                        ->where('service_provider_id',$id)
                                        ->where('service_type','schedule_calendar')
                                        ->where('schedule_id',$booking->schedule_id)
                                        ->where('date',$booking->date)
                                        ->where('start_time',$booking->start_time)
                                        ->where('end_time',$booking->end_time)
                                        ->sum('reschedule_request');

                $refund_request_count = UserBooking::where('schedule_id',$booking->schedule_id)
                                        ->where('service_provider_id',$id)
                                        ->where('service_type','schedule_calendar')
                                        ->where('schedule_id',$booking->schedule_id)
                                        ->where('date',$booking->date)
                                        ->where('start_time',$booking->start_time)
                                        ->where('end_time',$booking->end_time)
                                        ->sum('refund_request');

             $schedule_worktime = ScheduleWorktime::where('schedule_id',$booking->schedule_id)
                                                  ->where('start_time',$booking->start_time)
                                                  ->where('end_time',$booking->end_time)
                                                  ->first();
             $booking_id = "";
            //  $alphabet   = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            //  $randomchar = $alphabet[rand(0,strlen($alphabet)-1)] . rand(1,98);

             
             $schedule_cal_reschedule_request_count = Schedule_calendar_requests::where('service_provider_id',$booking->service_provider_id)
                                                           ->where('schedule_id',$booking->schedule_id)
                                                           ->where('date','>=',$booking->date)
                                                           ->where('date','<=',$booking->to_date)
                                                           ->where('start_time',$booking->start_time)
                                                           ->where('end_time',$booking->end_time)
                                                           ->where('status','pending')
                                                           ->where('request_type','reschedule')
                                                           ->count();
             if($schedule_worktime){
                $booking_id = "WRK".$schedule_worktime->id;
             }
             //find schedule status
             $schedule_status = "";
             if(strtotime($booking->to_date) >= time() && strtotime($booking->date) >= time()){
                 $schedule_status = "future";
             }elseif(strtotime($booking->to_date) <= time() && strtotime($booking->date) <= time()){
                 $schedule_status = "past";
             }else{
                 $schedule_status = "present";
             }

               //check bookings status is completed or not
               $status = "";
               if($booking->to_date == date('Y-m-d') &&  date('H:i:s') > $booking->end_time && $booking->status != 2 && $booking->status != 3){
                
                  $status = COMPLETED;
               }else{
                 $status = $booking->status;
               }
                
                $available_slots_count = count($slot_booking);
                $user_data[] = array(
                    'id'           => $booking->id,
                    'customer_id'  => $booking->customer_id,
                    'booking_id'   => $booking_id,
                    'schedule_name'=> $service_schedule->schedule_name,
                    'service_provider_id' => $booking->service_provider_id,
                    'service_type' => $booking->service_type,
                    'schedule_id'  => $booking->schedule_id,
                    'from_date'         => $booking->date,
                    'start_time'   => $booking->start_time,
                    'end_time'     => $booking->end_time,
                    'status'       => $status,
                    'days'         => $bookingAvailableDays,
                    'to_date'      => $booking->to_date ?? $booking->date,
                    'profile_pic'  => url('storage/profile_image/'.$user->profile_picture),
                    'user_name'    => $user->username,
                    'xmppid'       => "",
                    'offered_service' => $offered_service,
                    'service_category' => $service_category,
                    'price'        => $price,
                    'paid_by'      => $service_schedule->paid_by,
                    'on_going'     => $on_going,
                    'refund_request_count' => $refund_request_count,
                    // 'reschedule_request_count' => $reschedule_request_count, 
                    'reschedule_request_count' => $schedule_cal_reschedule_request_count,
                    'clients_per_session' => $available_slots_count,
                    'available_slots_count'      => $service_schedule->clients_per_session - $available_slots_count,
                    'refund_request_status'      => $refund_request_status,
                    'reschedule_request_status'  => $reschedule_request_status,
                    'schedule_status'            => $schedule_status,
                    'button'                     => $this->checkStartBtnStatus($booking->service_provider_id,$booking->service_type,$booking->schedule_id,$booking->date,$booking->start_time,$booking->end_time)

                );
              
                $ids[] = $booking->id;

            
            }
           
            
      }
      
     
      //rescheduled schedule calendar list
      $schedule_calendar_requests = Schedule_calendar_requests::where('service_provider_id',$id)
                                                            ->where('date','>=',$past_seven_days)
                                                            ->orderBy('date','desc')
                                                            ->get();
      // condition clause added for testing, need to rework
     if($schedule_calendar_requests->count() > 100000){
          foreach($schedule_calendar_requests as $schedule_cal_req){
              $cus_booking = UserBooking::find($schedule_cal_req->user_bookings_id);

              $scheduleWorktime = ScheduleWorktime::
                                                  where('schedule_id',$cus_booking->schedule_id)
                                                  ->where('start_time',$cus_booking->start_time)
                                                  ->where('end_time',$cus_booking->end_time)
                                                  ->first();
            // dd($scheduleWorktime);
              $bookingId = "";
              if($scheduleWorktime){
                $bookingId = "WRK".$scheduleWorktime->id;
              }
                   //find schedule status
             $schedulestatus = "";
             if(strtotime($cus_booking->to_date) >= time() && strtotime($schedule_cal_req->date) >= time()){
                 $schedulestatus = "future";
             }elseif(strtotime($cus_booking->to_date) <= time() && strtotime($schedule_cal_req->date) <= time()){
                 $schedulestatus = "past";
             }else{
                 $schedulestatus = "present";
             }

            //check bookings status is completed or not

            $sessionstatus = "";
            if($cus_booking->to_date == date('Y-m-d') &&  date('H:i:s') > $cus_booking->end_time && $cus_booking->status != 2 && $cus_booking->status != 3){
             
               $sessionstatus = COMPLETED;
            }else{
              $sessionstatus = $cus_booking->status;
            }


            $serviceschedule = ServiceSchedule::findOrFail($cus_booking->schedule_id);
            $user_info = User::findOrFail($cus_booking->customer_id);
            $userprofile = ModelsUserProfile::where('user_id',$id)->first();
            $offeredservice = Category::where('id',$userprofile->service_offered)->pluck('category_name')->first();
            $servicecategory = Category::where('id',$userprofile->service_category)->pluck('category_name')->first();
            $price_amount = $serviceschedule->charges_per_session;
            $current_date = date('Y-m-d');
            $start_timestamp = strtotime($schedule_cal_req->date);
            $end_timestamp = strtotime($cus_booking->to_date) ?? $schedule_cal_req->date;
            $date_to_check_timestamp = strtotime($current_date);
            
            if (($date_to_check_timestamp >= $start_timestamp) && ($date_to_check_timestamp <= $end_timestamp)) {
                $ongoing = true;
            } else {
                $ongoing = false;
            }
        //get count of total booked slots for this schedule id
        $slotbooking = UserBooking::where('schedule_id',$cus_booking->schedule_id)
                                    ->where('service_provider_id',$id)
                                    ->where('service_type','schedule_calendar')
                                    ->where('schedule_id',$cus_booking->schedule_id)
                                    ->where('date',$cus_booking->date)
                                    ->where('start_time',$cus_booking->start_time)
                                    ->where('end_time',$cus_booking->end_time)
                                    ->count();

        $availableslotscount = $slotbooking;

            $refundRequestCount = Schedule_calendar_requests::where('schedule_id',$schedule_cal_req->schedule_id)
                                                              ->where('service_provider_id',$id)
                                                              ->where('service_type','schedule_calendar')
                                                              ->where('schedule_id',$schedule_cal_req->schedule_id)
                                                              ->where('date',$schedule_cal_req->date)
                                                              ->where('start_time',$schedule_cal_req->start_time)
                                                              ->where('end_time',$schedule_cal_req->end_time)
                                                              ->where('request_type','refund_request')
                                                              ->count();
            $user_data[] = array(
                'id'           => $cus_booking->id,
                'customer_id'  => $cus_booking->customer_id,
                'booking_id'   => $bookingId,
                'schedule_name'=> $serviceschedule->schedule_name,
                'service_provider_id' => $schedule_cal_req->service_provider_id,
                'service_type' => $schedule_cal_req->service_type,
                'schedule_id'  => $schedule_cal_req->schedule_id,
                'from_date'         => $schedule_cal_req->date,
                'start_time'   => $schedule_cal_req->start_time,
                'end_time'     => $schedule_cal_req->end_time,
                'status'       => $sessionstatus,
                'days'         => $serviceschedule->days,
                'to_date'      => $cus_booking->to_date ?? $cus_booking->date,
                'profile_pic'  => url('storage/profile_image/'.$user_info->profile_picture),
                'user_name'    => $user_info->username,
                'xmppid'       => "",
                'offered_service' => $offeredservice,
                'service_category' => $servicecategory,
                'price'        => $price_amount,
                'paid_by'      => $serviceschedule->paid_by,
                'on_going'     => $ongoing,
                'refund_request_count' => $refundRequestCount,
                // 'reschedule_request_count' => $reschedule_request_count, 
                'reschedule_request_count' => $schedule_cal_reschedule_request_count,
                'clients_per_session' => $availableslotscount,
                'available_slots_count'      => $serviceschedule->clients_per_session - $availableslotscount,
                'refund_request_status'      => 0,
                'reschedule_request_status'  => 1,
                'schedule_status'            => $schedulestatus,
                'button'                     => $this->checkStartBtnStatus($cus_booking->service_provider_id,$cus_booking->service_type,$cus_booking->schedule_id,$cus_booking->date,$cus_booking->start_time,$cus_booking->end_time)

            );
           
          }
     }

      return $user_data;
   }

   //get_daynum_from_daystring
   public function get_daynum_from_daystring($daystring)
   {
      if($daystring == "Sun" || $daystring == "sun"){
         $day_num = 0;
      }elseif($daystring == "Mon" || $daystring == "mon"){
        $day_num = 1;
      }elseif($daystring == "Tue" || $daystring == "tue"){
        $day_num  = 2;
      }elseif($daystring == "Wed" || $daystring == "wed"){
        $day_num = 3;
      }elseif($daystring == "Thu" || $daystring == "thu"){
        $day_num = 4;
      }elseif($daystring == "Fri" || $daystring == "fri"){
        $day_num = 5;
      }elseif($daystring == "Sat" || $daystring == "sat"){
        $day_num = 6;
      }
      return $day_num;
   }
   //my_session API 
   public function my_session(Request $request)
   {
      $id = $request->id;
      $type = $request->type;
      
      if($type == "provider"){

         $open_calendar = OpenCalendar::where('user_id',$id)->first();
        //   dd($open_calendar);
         $final_result = [];
         if($open_calendar){
            $schedule_start_time = $open_calendar->start_time;
            $schedule_end_time = $open_calendar->end_time;

            $min_session = OpenCalendarSchedule::select('time_per_session')->where('open_calendar_id',$open_calendar->id)->min('time_per_session');

            $current_date = date('Y-m-d'); //current date
            $allow_booking_after = $open_calendar->allow_booking_after;
            $days = json_decode($open_calendar->days);
            $end_date = date('Y-m-d',strtotime('+'.($allow_booking_after - 1).' days'));
            $actual_end_date = date('Y-m-d',strtotime('+6 days'));
            $start_time = $open_calendar->start_time;
            $end_time   = $open_calendar->end_time;

            //multiple days

            $open_result = [];
            $final_result = [];
            $price = 0;
            
            // for ($i=0; $i < 7 ; $i++) { 
                
                $date = date('Y-m-d');
                $todate = date('Y-m-d',strtotime('+6 days'));
                $daystring = date('D',strtotime($date));
                $day_num = $this->get_daynum_from_daystring($daystring);
                
              
                $slots = [];
                // $date = date('Y-m-d',strtotime('+'.$i.' days'));
                
                
                if(in_array($day_num,$days)) {
                   
                // $date = date('Y-m-d',strtotime('tomorrow'));
                
                $user_booking  = UserBooking::where('service_provider_id',$id)
                                            ->where('service_type','open_calendar')
                                            ->whereDate('date','>=',$date)
                                            ->whereDate('to_date','<=',$todate)
                                            ->whereBetween('start_time',[$start_time,$end_time])
                                            ->whereBetween('end_time',[$start_time,$end_time])
                                            ->where(function($q1){
                                               $q1->where('status',1)
                                                  ->orWhere('status',3);
                                            })
                                            ->orderBy('start_time','asc')
                                            ->get();
                
               
                // dd($user_booking);
                if($user_booking->count() > 0){
                
                $last_index = count($user_booking) - 1;
                $current_end_time = "";
                $last_end_time = "";
                
                $last_index = count($user_booking) - 1;
                $times = [];
                foreach($user_booking as $k => $booking){   
                   
                   
                //     //update schedule status
                if($booking->to_date <= date('Y-m-d') && $booking->end_time < date('H:i:s') && $booking->status != 2 && $booking->status != 3){
                    UserBooking::where('id',$booking->id)
                    ->update(['status' => 4]);
                }
                    
                    $session_st_time = $start_time;
                    $session_end_time = $end_time;
                    $current_st_time = $booking->start_time;
                    $current_end_time = $booking->end_time;

                     $ch_st_time = new DateTime($current_st_time);
                     $ch_e_time = new DateTime($current_end_time);
                     $ch_interval = $ch_st_time->diff($ch_e_time);
                     $ch_diff = $ch_interval->i;
                     
                     $open_calendar_schedule = OpenCalendarSchedule::where('open_calendar_id',$open_calendar->id)
                                                                   ->where('user_id',$id)
                                                                   ->where('time_per_session',$ch_diff)
                                                                   ->first();
                    
                     if($open_calendar_schedule->count() > 0){
                        $price = $open_calendar_schedule->price;

                    }else{
                        $price = 0;
                     }
                    //  dd($price);
                    if($k == 0){
                        $open_result[] =  $this->getProvider_sessions_status($id,$date,$session_st_time,date('H:i:s',strtotime($current_st_time)),$allow_booking_after,$price);
                        // $final_result []= $this->open_cal_frame_response($session_st_time,date('H:i:s',strtotime($current_st_time)),"available",$date,$allow_booking_after,$id,$price);

                         //store first inex time
                        //  $final_result[] = $this->open_cal_frame_response($current_st_time,$current_end_time,"not",$date,$allow_booking_after,$id,$price);
                         $open_result[] =  $this->getProvider_sessions_status($id,$date,$current_st_time,$current_end_time,$allow_booking_after,$price);

                         
                          //end of the array
                          if($k == $last_index){
                            $d_st_time = new DateTime($current_end_time);
                            $d_e_time  = new DateTime($session_end_time);
                            $interval  = $d_st_time->diff($d_e_time);
                            $diff      = $interval->i;
      
                            if($diff >= $min_session){
                                // $final_result[] = $this->open_cal_frame_response($current_end_time,$session_end_time,"available",$date,$allow_booking_after,$id,$price);
                                $open_result[] =  $this->getProvider_sessions_status($id,$date,$current_end_time,$session_end_time,$allow_booking_after,$price);
                            }
                         }


                    }else{
                        $d_st_time = new DateTime($last_end_time);
                        $d_e_time  = new DateTime($current_st_time);
                        $interval = $d_st_time->diff($d_e_time);
                        $diff = $interval->i;
                         
                        if($diff >= $min_session){
                        //    $final_result[] = $this->open_cal_frame_response($last_end_time,$current_st_time,'available',$date,$allow_booking_after,$id,$price);
                           $open_result[] =  $this->getProvider_sessions_status($id,$date,$last_end_time,$current_st_time,$allow_booking_after,$price);
                        }
                           $open_result[] =  $this->getProvider_sessions_status($id,$date,$current_st_time,$current_end_time,$allow_booking_after,$price);
                        // $final_result[] =  $this->open_cal_frame_response($current_st_time,$current_end_time,"not",$date,$allow_booking_after,$id,$price);
                        

                         //end of the array
                         if($k == $last_index){
                            $d_st_time = new DateTime($current_end_time);
                            $d_e_time  = new DateTime($session_end_time);
                            $interval  = $d_st_time->diff($d_e_time);
                            $diff      = $interval->i;
      
                            if($diff >= $min_session){
                                $open_result[] =  $this->getProvider_sessions_status($id,$date,$current_end_time,$session_end_time,$allow_booking_after,$price);
                                // $final_result[] = $this->open_cal_frame_response($current_end_time,$session_end_time,"available",$date,$allow_booking_after,$id,$price);
                            
                            }
                         }
                    
                    }
                    $last_end_time = $booking->end_time;
                 }

                


                }
                // else{
                    
                //     // $final_result[] = $this->open_cal_frame_response($start_time,$end_time,"available",$date,$allow_booking_after,$id,$price);
                //     $open_result[] =  $this->getProvider_sessions_status($id,$date,$start_time,$end_time,$allow_booking_after,$price);
                // }
              }
            //   else{
            //     // $final_result[] = $this->open_cal_frame_response($start_time,$end_time,'not_scheduled',$date,$allow_booking_after,$id,$price);
            //     $open_result[] =  $this->getProvider_sessions_status($id,$date,$start_time,$end_time,$allow_booking_after,$price);
            //   }
           
            // }
            // die;
            // return response($open_result);
            $final_result = $open_result;
            // return response()->json($final_result);
                                        
            
         }else{

            //schedule calendar
            $service_schedule = ServiceSchedule::where('user_id',$id)->get();
            // dd($service_schedule);
            foreach($service_schedule as $schedule){

                  //split by chargesper month or Appointment
                  if($schedule->charges_per == 1){
                      
                    $schedule_worktime = ScheduleWorktime::where('schedule_id',$schedule->id)->get();
                    $gap = $schedule->gap_between_sessions;
                    $clients_per_session = $schedule->clients_per_session;
                    $allow_booking_after = $schedule->allow_booking_after;
                    $days = json_decode($schedule->days);
                    $current_date = date('Y-m-d');
                    $end_date = date('Y-m-d',strtotime('+'.($allow_booking_after - 1).' days'));
                    $actual_end_date = date('Y-m-d',strtotime('+6 days'));
                    
                    foreach($schedule_worktime as $k2 => $v){
                      $final_result[] = array(
                          'id'                    => $schedule->id,
                          'service_provider_id'   => $id,
                          'schedule_name'         => $schedule->schedule_name,
                          'start_date'            => $current_date,
                          'end_date'              => $end_date,
                          'actual_end_date'       => $actual_end_date,
                          'clients_per_session'   => $schedule->clients_per_session,
                          'schedule_start_time'   => $v->start_time,
                          'schedule_end_time'     => $v->end_time,
                          'charges_per_session'   => $schedule->charges_per_session,
                          'paid_by'               => $schedule->paid_by,
                          'charges_per'           => $schedule->charges_per,
                          'allow_booking_after'   => $schedule->allow_booking_after,
                          // 'days'                  => $days,
                          'slots'                 => $this->my_session_sch_cal_dates($id,$days,$allow_booking_after,$schedule->id,$clients_per_session,$v->start_time,$v->end_time)
                      );
                    }

                  }else{
                    $schedule_worktime = ScheduleWorktime::where('schedule_id',$schedule->id)->get();
                    $gap = $schedule->gap_between_sessions;
                    $clients_per_session = $schedule->clients_per_session;
                    $allow_booking_after = $schedule->allow_booking_after;
                    $days = json_decode($schedule->days);
                    $current_date = date('Y-m-d');
                    $end_date = date('Y-m-d',strtotime('+'.($allow_booking_after - 1).' days'));
                    $actual_end_date = date('Y-m-d',strtotime('+6 days'));
                    
                    foreach($schedule_worktime as $k2 => $v){
                      $final_result[] = array(
                          'id'                    => $schedule->id,
                          'service_provider_id'   => $id,
                          'schedule_name'         => $schedule->schedule_name,
                          'start_date'            => $current_date,
                          'end_date'              => $end_date,
                          'actual_end_date'       => $actual_end_date,
                          'clients_per_session'   => $schedule->clients_per_session,
                          'schedule_start_time'   => $v->start_time,
                          'schedule_end_time'     => $v->end_time,
                          'charges_per_session'   => $schedule->charges_per_session,
                          'paid_by'               => $schedule->paid_by,
                          'charges_per'           => $schedule->charges_per,
                          'allow_booking_after'   => $schedule->allow_booking_after,
                          // 'days'                  => $days,
                          'slots'                 => $this->my_session_sch_cal_dates($id,$days,$allow_booking_after,$schedule->id,$clients_per_session,$v->start_time,$v->end_time)
                      );
                    }
                  }

                 
                  

                 
            }
            
            //    return response()->json($final_result);
         }

         /**
          *  Discussion Schedule
          */
            $discussion_service = DiscussionService::where('user_id',$id)->first();
            $dis_result = [];
            
            if($discussion_service){
                $days = json_decode($discussion_service->days);
            
                if($discussion_service->count() > 0){
                    $start_time = $discussion_service->start_time;
                    $end_time = $discussion_service->end_time;
                    $gap = $discussion_service->time_per_session;
                    $current_time = $start_time;
                    $times = [];
                    while($current_time < $end_time){
                        $e_time = date('H:i:s',strtotime($current_time.'+'.$gap.' Minutes'));
                        $times[] = array(
                        'start_time'  => $current_time,
                        'end_time'    => $e_time
                        ); 
                        $current_time = $e_time;
                    }
    
                    foreach($times as $k => $time){
                        $dis_result[] = array(
                            'discussion_id'         => $discussion_service->id,
                            'schedule_name'         => "discussion",
                            'service_provider_id'   => $id,
                            'start_date'            => date("Y-m-d"),
                            'end_date'              => date('Y-m-d',strtotime('+6 days')),
                            'actual_end_date'       => date('Y-m-d',strtotime('+6 days')),
                            'clients_per_session'   => 1,
                            'schedule_start_time'   => $time['start_time'],
                            'schedule_end_time'     => $time['end_time'],
                            'charges_per_session'   => $discussion_service->total_amount,
                            'paid_by'               => 0,
                            'charges_per'           => 0,
                            'allow_booking_after'   => 0,
                            // 'days'                  => $days,
                            'slots'                 => $this->myses_discussion_date($id,$time['start_time'],$time['end_time'],$days)
                        );
                    }
                    // return response()->json($dis_result);
                }
               
            }
          
            $return_data = array(
                'schedule'   => $final_result,
                'discussion' => $dis_result
            );

            return response()->json($return_data);
         
      
      }else{
        
          $taker = [];
          $schedule_appointment = [];
          $discussion_appointment = [];
          $service_schedule_ids = [];
          for ($i=0; $i < 7; $i++) { 
             $today = date('Y-m-d')  ;
             $end_date = date('Y-m-d',strtotime('+6 days'));
             $date = date('Y-m-d',strtotime('+'.$i.' days'));

             $userBookings = UserBooking::where('customer_id',$id)
                                         ->where(function($q){
                                             $q->where('service_type','open_calendar')
                                               ->orWhere('service_type','schedule_calendar');
                                         })
                                         ->whereDate('date','<=',$date)
                                         ->whereDate('to_date','>=',$date)
                                         ->get();
            // dd($userBookings);
            if($userBookings->count() > 0){
                 
                foreach($userBookings as $key => $taker_booking){
                    
                    if($taker_booking->service_type == "schedule_calendar"){
                     /**
                      *  Split by appointment & month
                      */

                      $ServiceSchedule = ServiceSchedule::where('id',$taker_booking->schedule_id)->first();
                      $bookedAppointments = UserBooking::where('schedule_id',$ServiceSchedule->id)
                                                        ->where('customer_id',$id)
                                                        ->whereDate('date','<=',$date)
                                                        ->whereDate('to_date','>=',$date)
                                                        ->where('status','!=',RESCHEDULE_ACCEPTED)
                                                        ->where('status','!=',RESCHEDULE_REJECTED)
                                                        ->where('status','!=',COMPLETED)
                                                        ->count();

                      $availableClientCount = $ServiceSchedule->clients_per_session - $bookedAppointments;
                      if($ServiceSchedule->charges_per == 1){

                        
                        
                        //Appointment
                        $schedule_appointment[] = array(
                            'id'                    => $ServiceSchedule->id,
                            'service_provider_id'   => $taker_booking->service_provider_id,
                            'schedule_name'         => $ServiceSchedule->schedule_name,
                            'start_date'            => $date,
                            'end_date'              => date('Y-m-d',strtotime('+6 days')),
                            'actual_end_date'       => date('Y-m-d',strtotime('+6 days')),
                            'clients_per_session'   => $ServiceSchedule->clients_per_session ?? 0,
                            'schedule_start_time'   => $taker_booking->start_time,
                            'schedule_end_time'     => $taker_booking->end_time,
                            'charges_per_session'   => $ServiceSchedule->charges_per_session,
                            'paid_by'               => $ServiceSchedule->paid_by,
                            'charges_per'           => $ServiceSchedule->charges_per,
                            'allow_booking_after'   => $ServiceSchedule->allow_booking_after,
                            // 'days'                  => $days,
                            'slots'                 => $this->my_appointments($taker_booking->start_time,$taker_booking->end_time,$date,$bookedAppointments)
                            
                        );
                        
                      }else{
                        //Month
                      

                        
                        $sess_daystring = date('D',strtotime($date));
                        $sess_daynum    = $this->get_daynum_from_daystring($sess_daystring);
                        $session_days   = json_decode($ServiceSchedule->days);
                        
                        $monthly_available_status = "Not Scheduled";
                        if(in_array($sess_daynum,$session_days)){

                         $monthly_available_status = "Available";
                       
                        if(!in_array($ServiceSchedule->id,$service_schedule_ids)){

                      
                            $schedule_appointment[] = array(
                                'id'                    => $ServiceSchedule->id,
                                'service_provider_id'   => $taker_booking->service_provider_id,
                                'schedule_name'         => $ServiceSchedule->schedule_name,
                                'start_date'            => $date,
                                'end_date'              => date('Y-m-d',strtotime('+6 days')),
                                'actual_end_date'       => date('Y-m-d',strtotime('+6 days')),
                                'clients_per_session'   => $ServiceSchedule->clients_per_session ?? 0,
                                'schedule_start_time'   => $taker_booking->start_time,
                                'schedule_end_time'     => $taker_booking->end_time,
                                'charges_per_session'   => $ServiceSchedule->charges_per_session,
                                'paid_by'               => $ServiceSchedule->paid_by,
                                'charges_per'           => $ServiceSchedule->charges_per,
                                'allow_booking_after'   => $ServiceSchedule->allow_booking_after,
                                // 'days'                  => $days,
                                'slots'                 => $this->taker_booked_slots($taker_booking->start_time,$taker_booking->end_time,$date,$bookedAppointments,$monthly_available_status,$session_days)
                            );
                        }
                      }

                      $service_schedule_ids[] = $ServiceSchedule->id;
                        
                      }
                    }else{
                        // dd($taker_booking);
                        $openCalendar = OpenCalendar::find($taker_booking->schedule_id);
                        $calendarService = CalenderService::find($openCalendar->calendar_service_id);
                        $openCalendarSchedule = OpenCalendarSchedule::where('open_calendar_id',$openCalendar->id)->first();
                        // dd($calendarService);
                        $schedule_appointment[] = array(
                                            'id'                    => $openCalendar->id,
                                            'service_provider_id'   => $taker_booking->service_provider_id,
                                            'schedule_name'         => "open_calendar",
                                            'start_date'            => $date,
                                            'end_date'              => date('Y-m-d',strtotime('+6 days')),
                                            'actual_end_date'       => date('Y-m-d',strtotime('+6 days')),
                                            'clients_per_session'   => 1,
                                            'schedule_start_time'   => $taker_booking->start_time,
                                            'schedule_end_time'     => $taker_booking->end_time,
                                            'charges_per_session'   => $openCalendarSchedule->price,
                                            'paid_by'               => $openCalendar->paid_by,
                                            'charges_per'           => 0,
                                            'allow_booking_after'   => $openCalendar->allow_booking_after,
                                            // 'days'                  => $days,
                                            'slots'                 => $this->my_appointments($taker_booking->start_time,$taker_booking->end_time,$date,1)
                        );
                    }
                    
                }
            }

            
        //      //schedule & open calendar
        //      $customer_bookings = UserBooking::where('customer_id',$id)
        //                                      ->where(function($q){
        //                                         $q->where('service_type','open_calendar')
        //                                           ->orWhere('service_type','schedule_calendar');
        //                                      })
        //                                      ->where(function ($query) use ($date){
        //                                         $query->whereBetween('date',[$date,$date])
        //                                               ->orWhereBetween('to_date',[$date,$date]);
        //                                      })
                                            
        //                                      ->get();
        //         // dd($customer_bookings);
        //        if($userBookings){
                   
        //            foreach($userBookings as $key => $c_booking){

        //             //update schedule status
        //             if(strtotime($c_booking->to_date) <= time()){
        //                 if($c_booking->end_time <= date('H:i:s')){
        //                     if($c_booking->status != RESCHEDULE_ACCEPTED && $c_booking->status != RESCHEDULE_REJECTED){
        //                         UserBooking::where('id',$c_booking->id)
        //                                 ->update(['status' => 4]);
        //                     } 
                        
        //                 }
        //             }
                    
        //             $clients_per_session = 0;
        //             $booked_clients_count = 0;
        //             if($c_booking->service_type == "schedule_calendar"){
        //                 $taker_bookings = UserBooking::where('service_provider_id',$c_booking->service_provider_id)
        //                                              ->where('service_type','schedule_calendar')
        //                                              ->whereBetween('start_time',[$c_booking->start_time,$c_booking->end_time])
        //                                              ->whereBetween('end_time',[$c_booking->start_time,$c_booking->end_time])
        //                                              ->where(function($q1) use ($date){
        //                                                 $q1->whereBetween('date',[$date,$date])
        //                                                 ->orWhereBetween('to_date',[$date,$date]);
        //                                              })
        //                                              ->get();
        //                 $booked_clients_count = count($taker_bookings);

        //                 $service_schedules = ServiceSchedule::findOrFail($c_booking->schedule_id);
        //                 $clients_per_session = $service_schedules->clients_per_session;
        //             }else{
        //                 $clients_per_session  = 1;
        //                 $booked_clients_count = 1;
        //             }
        //             // dd($taker_bookings);
        //         $schedule_appointment[] = array(
        //                 'id'                    => $c_booking->id,
        //                 'schedule_name'         => "",
        //                 'start_date'            => $date,
        //                 'end_date'              => date('Y-m-d',strtotime('+6 days')),
        //                 'actual_end_date'       => date('Y-m-d',strtotime('+6 days')),
        //                 'clients_per_session'   => $clients_per_session,
        //                 'schedule_start_time'   => $c_booking->start_time,
        //                 'schedule_end_time'     => $c_booking->end_time,
        //                 'charges_per_session'   => 0,
        //                 'paid_by'               => 0,
        //                 'charges_per'           => 0,
        //                 'allow_booking_after'   => 0,
        //                 // 'days'                  => $days,
        //                 'slots'                 => $this->my_appointments($c_booking->start_time,$c_booking->end_time,$date,$booked_clients_count)
                        
        //         );
        //     }
        //   }
                   
            //discussion schedules
            $discussion_bookings = UserBooking::where('customer_id',$id)
                                            ->where('service_type','discussion')
                                            ->where(function ($query) use ($date){
                                                $query->whereBetween('date',[$date,$date])
                                                ->orWhereBetween('to_date',[$date,$date]);
                                            })
                                            ->where(function($q1){
                                                $q1->where('status',1)
                                                   ->orWhere('status',3);
                                             })
                                            ->get();

                                foreach($discussion_bookings as $key => $d_booking){

                                    //update schedule status
                                    if($d_booking->to_date <= date('Y-m-d') && $d_booking->end_time < date('H:i:s') && $d_booking->status != 2 && $d_booking->status != 3){
                                        UserBooking::where('id',$d_booking->id)
                                        ->update(['status' => 4]);
                                    }
                                   
                                    $DiscussionService = DiscussionService::where('user_id',$d_booking->service_provider_id)->first();

                                        $booked_clients_count = 0;
                                        $discussion_appointment[] = array(
                                            'discussion_id'     => $DiscussionService->id,
                                        'schedule_name'         => "discussion",
                                        'service_provider_id'   => $d_booking->service_provider_id,
                                        'start_date'            => $date,
                                        'end_date'              => date('Y-m-d',strtotime('+6 days')),
                                        'actual_end_date'       => date('Y-m-d',strtotime('+6 days')),
                                        'clients_per_session'   => 1,
                                        'schedule_start_time'   => $d_booking->start_time,
                                        'schedule_end_time'     => $d_booking->end_time,
                                        'charges_per_session'   => $DiscussionService->total_amount,
                                        'paid_by'               => 0,
                                        'charges_per'           => 1,
                                        'allow_booking_after'   => 0,
                                        // 'days'                  => $days,
                                        'slots'                 => $this->my_appoint_discussion_date($d_booking->start_time,$d_booking->end_time,$date,$booked_clients_count)
                                        );
                                }
          }

        $appointments = array(
            'schedule'   => $schedule_appointment,
            'discussion' => $discussion_appointment
        );
         return response()->json($appointments);

      }
      
   }
  

   public function taker_booked_slots($start_time,$end_time,$current_date,$booked_clients_count,$monthly_available_status,$days){

        for ($i=0; $i < 7; $i++) { 

            $today = date('Y-m-d');
            $date  = date('Y-m-d',strtotime('+'.$i.' days'));
            $end_date = date('Y-m-d',strtotime('+6 days'));
            $daystring = date('D',strtotime($date));
            $day_num = $this->get_daynum_from_daystring($daystring);
            if(in_array($day_num,$days)){

                $my_appointments[] = array(
                    $daystring  => array(
                        'status'     => $monthly_available_status,
                        'available_clients_count' => $booked_clients_count,
                        'date'       => $date,
                    )
                );
                // $my_appointments[] = $this->my_appointment_status($start_time,$end_time,$daystring,$booked_clients_count);
            }else{
                $my_appointments[] = array(
                    $daystring => array(
                        'status' => 'Not Scheduled',
                        'available_clients_count' => 0,
                        'date'  => $date
                    )
                );
            }
            
        }

        return $my_appointments;
   }
   /**
    *  getProvider_sessions_status
    */
    public function getProvider_sessions_status($id,$date,$start,$end,$allow_booking_after,$price){

        $open_calendar = OpenCalendar::where('user_id',$id)->first();

         $slots = [];
         for($i = 0; $i<7; $i++){

        

           
            $today = date('Y-m-d');
            $end_date = date('Y-m-d',strtotime('+'.($allow_booking_after - 1).' days'));
            $actual_end_date = date('Y-m-d',strtotime('+6 days'));

            $sess_date = date('Y-m-d',strtotime($date.'+'.$i.' days'));
            $daystring = date('D',strtotime($sess_date));
            $day_num = $this->get_daynum_from_daystring($daystring);
            
            if(in_array($day_num,json_decode($open_calendar->days))){
                // dd($open_calendar->days);
            $user_booking = UserBooking::where('service_provider_id',$id)
                                        ->where('date',$sess_date)
                                        ->whereBetween('start_time',[$start,$end])
                                        ->whereBetween('end_time',[$start,$end])
                                        ->where('service_type','open_calendar')
                                        ->where(function($q1) use ($start,$end){
                                            $q1->where('status',1)
                                               ->orWhere('status',3);
                                        })
                                        ->get();
            
            if(count($user_booking) > 0){
                $status = 'Not Available';
                $available_clients_count = 1;

            }else{
                $status = 'Available';
                $available_clients_count = 0;
            }
        }else{
            $status = "Not Scheduled";
            $available_clients_count = 0;
        }
           $slots[] = array(
              $daystring => array(
                'status'   => $status,
                'available_clients_count' => $available_clients_count,
                'date'     => $sess_date
              )
           );
            // $slots[$daystring] = array(
                
            // );

            

         }

         $result = array(
            'id'              => $open_calendar->id,
            'schedule_name'   => "open_calendar",
            'service_provider_id' => $id,
            'start_date'      => $today,
            'end_date'        => $end_date,
            'actual_end_date' => $actual_end_date,
            'clients_per_session' => 1,
            'schedule_start_time' => $start,
            'schedule_end_time'   => $end,
            'charges_per_session' => $price,
            'paid_by'             => $open_calendar->paid_by,
            'charges_per'         => 1,
            'allow_booking_after' => $allow_booking_after,
            'slots'               => $slots

        );
         return $result;

        echo date('Y-m-d',strtotime($date.'+1 day'));die;
    }
   //my_appointments
   public function my_appointments($start_time,$end_time,$current_date,$booked_clients_count){
      
    for ($i=0; $i < 7; $i++) { 

        $today = date('Y-m-d');
        $date  = date('Y-m-d',strtotime('+'.$i.' days'));
        $end_date = date('Y-m-d',strtotime('+6 days'));
        $daystring = date('D',strtotime($date));
        // echo $current_date;die;
        if($date == $current_date){
            $my_appointments[] = $this->my_appointment_status($start_time,$end_time,$daystring,$booked_clients_count,$date);
        }else{
            $my_appointments[] = array(
                $daystring => array(
                    'status' => 'Not Scheduled',
                    'available_clients_count' => 0
                )
            );
        }
        
    }

    return $my_appointments;
   }

   //my_appoint_discussion_date
   public function my_appoint_discussion_date($start_time,$end_time,$current_date,$booked_clients_count){
   
    for ($i=0; $i < 7; $i++) { 

        $today = date('Y-m-d');
        $date  = date('Y-m-d',strtotime('+'.$i.' days'));
        $end_date = date('Y-m-d',strtotime('+6 days'));
        $daystring = date('D',strtotime($date));

        if($date == $current_date){
            $my_appointments[] = $this->my_appointment_status($start_time,$end_time,$daystring,$booked_clients_count,$date);
        }else{
            $my_appointments[] = array(
                $daystring => array(
                    'status' => 'Not Scheduled',
                    'available_clients_count' => 1,
                    'date'   => $date
                )
            );
        }
        
    }

    return $my_appointments;
   }

   //my_appointment_status
   public function my_appointment_status($start_time,$end_time,$daystring,$booked_clients_count,$date){
        $data = array(
            $daystring  => array(
                'status'     => "Available",
                'available_clients_count' => $booked_clients_count,
                'date'       => $date
            )
        );

        return $data;
   }
   //myses_discussion_date
   public function myses_discussion_date($id,$start_time,$end_time,$days)
   {
      for ($i=0; $i < 7; $i++) { 
        $today = date('Y-m-d');
        $date = date('Y-m-d',strtotime('+'.$i.' days'));
        $daystring = date('D',strtotime($date));
        $day_num = $this->get_daynum_from_daystring($daystring);

        if(in_array($day_num,$days)){
            $result[] = $this->myses_discussion_status($id,$date,$start_time,$end_time,$daystring);

        }else{
            $result[] = array(
                $daystring => array(
                    'status' => "Not Scheduled",
                    'available_clients_count' => 1,
                    'date'   => $date
                )
                );
        }
      }
       return $result;
   }
   //myses_discussion_status
   public function myses_discussion_status($id,$date,$start_time,$end_time,$daystring)
   {
      $result = [];
      $user_booking = UserBooking::where('service_provider_id',$id)
                                  ->where('service_type','discussion')
                                  ->where('start_time','>=',$start_time)
                                  ->where('end_time','<=',$end_time)
                                  ->get();
      if(count($user_booking) == 0){
         $result = array(
            $daystring => array(
                'status' => "Available",
                'available_clients_count' => 0,
                'date'   => $date
            )
         );
      }else{
        $result = array(
            $daystring => array(
                'status' => "Not Available",
                'available_clients_count' => 1,
                'date'   => $date
            )
         );
      }
      return $result;
   }
  //open_cal_frame_response
  public function open_cal_frame_response($start_time,$end_time,$status,$current_date,$allow_booking_after,$id,$price)
  {
            $open_calendar = OpenCalendar::where('user_id',$id)->first();
            $end_date = date('Y-m-d',strtotime('+'.($allow_booking_after - 1).' days'));
            $actual_end_date = date('Y-m-d',strtotime('+6 days'));
            $today = date("Y-m-d");
            $clients_per_session = 0;
            if($status == "available"){
                $status = "Available";
                $clients_per_session = 1;
            }elseif($status == "not"){
                $status = "Not Available";
            }elseif($status == "not_scheduled"){
                $status = "Not Scheduled";
            }
            $slots = [];
            for ($i=0; $i < 7; $i++) { 
                $date = date('Y-m-d',strtotime('+'.$i.' days'));
                $daystring = date('D',strtotime($date));
                
                if($date == $current_date){
                    $slots[] = array(
                                $daystring          => array(
                                    "status"        => $status,
                                    "available_clients_count" => $clients_per_session
                                )
                        );
                }else{
                    $slots[] = array(
                            $daystring          => array(
                                "status"        => "Not Available",
                                "available_clients_count" => 0
                            )
                    
                    );
                }
            
            }
                $open_result = array(
                    'schedule_name'         => "",
                    'start_date'            => $today,
                    'end_date'              => $end_date,
                    'actual_end_date'       => $actual_end_date,
                    'clients_per_session'   => $clients_per_session,
                    'schedule_start_time'   => $start_time,
                    'schedule_end_time'     => $end_time,
                    'charges_per_session'   => $price,
                    'paid_by'               => $open_calendar->paid_by,
                    'charges_per'           => "1",
                    'allow_booking_after'   => $allow_booking_after,
                    'slots'                 => $slots
                    
                );
        //   dd($open_result);
            return $open_result;
}

   //my_session_sch_cal_status
   public function my_session_sch_cal_dates($id,$days,$allow_booking_after,$schedule_id,$clients_per_session,$start_time,$end_time)
   {
       
    $schedule_worktime = ScheduleWorktime::where('schedule_id',$schedule_id)->get();

    for ($i=0; $i < 7; $i++) { 

        $date = date('Y-m-d',strtotime('+'.$i.' days'));
        $daystring = date('D',strtotime($date));
        $day_num = $this->get_daynum_from_daystring($daystring);
        $day_count = $i;
        $data[] = array(
           $daystring => $this->my_session_sch_cal_status($id,$days,$allow_booking_after,$schedule_id,$clients_per_session,$i,$day_num,$date,$start_time,$end_time,$day_count)
        );
       
    }

        return $data;
   }

   //my_session_sch_cal_status
   public function my_session_sch_cal_status($id,$days,$allow_booking_after,$schedule_id,$clients_per_session,$i,$day_num,$date,$start_time,$end_time,$day_count)
   {
       $schedule_worktime = ScheduleWorktime::where('schedule_id',$schedule_id)->get();
       /**
        *  Allow booking after commented
        */
        //  if($i < $allow_booking_after){
            
           
          
        if(in_array($day_num,$days)){
         
                // $day_num = 1;
                $user_booking = UserBooking::where('service_provider_id',$id)
                                        ->where('service_type','schedule_calendar')
                                        ->where('schedule_id',$schedule_id)
                                        ->whereDate('date','<=',$date)
                                        ->whereDate('to_date','>=',$date)
                                        ->where('status',1)
                                        ->where('start_time','>=',$start_time)
                                        ->where('end_time','<=',$end_time)
                                        ->get();
                
            
                $count = count($user_booking);
            //   dd($day_count);
                if($count < $clients_per_session){
                    $status = "Available";
                }else{
                    $status = "Not Available";
                }
                
                //check start_time greater than current time for current date only @day_count = 1
                if($day_count == 0 && $start_time < date('H:i:s')){
                    $status  = "Not Scheduled";
                }
                $result = array(
                'status' => $status,
                'available_clients_count' => $count,
                'date'   => $date
                );
                // return response()->json($sch_result);

        

        }else{

            $result = array(
                'status' => 'Not Scheduled',
                'available_clients_count' => 0,
                'date'   => $date
            );
        }
        // }else{
            
        //     $result = array(
        //         'status' => "Not Scheduled",
        //         'available_clients_count' => 0
        //     );
        // }

            return $result;
   }

   /**
    *  Get Avaialable days for re-schedule
    */
    public function reschedule_available_days(Request $request)
    {
        $provider_id = $request->service_provider_id;
        $start_time  = $request->start_time;
        $end_time    = $request->end_time;
        $schedule_id = $request->schedule_id;

        if($provider_id != "" && $start_time != "" && $end_time != ""){
            //find session duration
            $session_st_time  = new DateTime($start_time);
            $session_end_time = new DateTime($end_time);
            $session_interval = $session_st_time->diff($session_end_time);
            $session_time     = $session_interval->i;
            
            $date       = date('Y-m-d');
            $start_date = $date;
            $end_date   = date('Y-m-d',strtotime('+6 days'));
            
            //first find it's open-cal or schedule-cal
            $open_calendar = OpenCalendar::find($schedule_id);
            $available_days = [];
            if(!empty($open_calendar)){

                     for ($i=0; $i < 7; $i++) { 
                        $date      = date('Y-m-d',strtotime('+'.$i.' days'));
                        $daystring = date('D',strtotime($date));
                        $day_num   = $this->get_daynum_from_daystring($daystring);
                        //check date is in provider's available days
                        if(in_array($day_num,json_decode($open_calendar->days))){

                        $user_booking = UserBooking::where('service_provider_id',$provider_id)
                                                   ->where('service_type','open_calendar')
                                                   ->where('date',$date)
                                                   ->where('status',1)
                                                   ->whereBetween('start_time',[$open_calendar->start_time,$open_calendar->end_time])
                                                   ->whereBetween('end_time',[$open_calendar->start_time,$open_calendar->end_time])
                                                   ->get();
                        if(count($user_booking) > 0){
                            //check available time is greater than session duration
                            $current_end_time = "";
                            $session_status = "";
                            $last_index = count($user_booking);
                            foreach($user_booking as $k1 => $user_booking){
                     
                                //if result has only one record
                                if($k1 == 0 && $last_index == 0){
                                    //open_cal start_time to bookign st_tym diff
                                    $s1_start_time = new DateTime($open_calendar->start_time);
                                    $s1_end_time   = new DateTime($user_booking->start_time);
                                    $s1_interval   = $s1_start_time->diff($s1_end_time);
                                    $s1_diff       = $s1_interval->i;

                                    //booking->end_time to open_cal->end_time  diff
                                    $sl_start_time = new DateTime($user_booking->end_time);
                                    $sl_end_time   = new DateTime($open_calendar->end_time);
                                    $sl_interval   = $sl_start_time->diff($sl_end_time);
                                    $sl_diff       = $sl_interval->i;

                                    //between booking's from time to to_time diff
                                    $sb_start_time = new DateTime($user_booking->start_time);
                                    $sb_end_time   = new DateTime($user_booking->end_time);
                                    $sb_interval   = $sb_start_time->diff($sb_end_time);
                                    $sb_diff       = $sb_interval->i;

                                    //check diff is greater than or equal to session duration
                                    if($s1_diff >= $session_time || $sl_diff >= $session_time || $sb_diff >= $session_time){
                                        $available_days[] = $daystring;
                                    }
                                }else{
                                    if($k1 == 0){
                                        //open_cal->start_time to booking->start_time diff
                                       $s1_start_time = new DateTime($open_calendar->start_time);
                                       $s1_end_time   = new DateTime($user_booking->start_time);
                                       $s1_interval   = $s1_start_time->diff($s1_end_time);
                                       $s1_diff       = $s1_interval->i;
                                       if($s1_diff >= $session_time){
                                         $session_status = "available";
                                       }
                                    }elseif($k1 == $last_index){
                                        //booking->end_time to open_cal->end_time diff
                                       $sl_start_time = new DateTime($user_booking->end_time);
                                       $sl_end_time   = new DateTime($open_calendar->end_time);
                                       $sl_interval   = $sl_start_time->diff($sl_end_time);
                                       $sl_diff       = $sl_interval->i;
                                       if($sl_diff >= $session_time){
                                         $session_status = "available";
                                       }
                                    }else{
                                        //between previous slot's end_time to next slot start_time
                                       $sb_start_time = new DateTime($current_end_time);
                                       $sb_end_time   = new DateTime($user_booking->start_time);
                                       $sb_interval   = $sb_start_time->diff($sb_end_time);
                                       $sb_diff       = $sb_interval->i;
                                       if($sb_diff >= $session_time){
                                         $session_status = "available";
                                       }
                                    }
                                    $current_end_time = $user_booking->end_time;
                                    if($session_status == "available"){
                                        $available_days[] = $daystring;
                                    }
                                }
                            }
                        }else{
                            $available_days[] = $daystring;
                        }
                      }
                     }
            }else{
                $service_schedules = ServiceSchedule::find($schedule_id);
                $schedule_worktime = ScheduleWorktime::where('schedule_id',$schedule_id);

                //check which schedule match with postponded session duration
                // foreach($schedule_worktime as $work_times){

                // }
                $available_days = [];
                for ($i=0; $i < 7; $i++) { 
                    $date      = date('Y-m-d');
                    $daystring = date('D',strtotime($date));
                    $day_num   = $this->get_daynum_from_daystring($daystring);
                     //check date is in provider's available days
                     if(in_array($day_num,json_decode($service_schedules->days))){

                         foreach($schedule_worktime as $k2 => $work_time){
                              $user_bookings = UserBooking::where('service_provider_id',$provider_id)
                                                          ->where('service_type','schedule_calendar')
                                                          ->where('schedule_id',$schedule_id)
                                                          ->where('date',$date)
                                                          ->where('status',1)
                                                          ->whereBetween('start_time',[$work_time->start_time,$work_time->end_time])
                                                          ->whereBetween('end_time',[$work_time->start_time,$work_time->end_time])
                                                          ->get();
                              if(count($user_bookings) == 0){
                                $available_days[] = $daystring;
                              }
                         }
                     }
                }
            }

                  return response()->json($available_days);
        }else{
             return response()->json(['status' => 'failed','message' => 'Required fields are missing']);
        }
    }

    //get_client_list
    public function get_client_list(Request $request)
    {
        if($request->service_provider_id != "" && $request->schedule_id != "" && $request->date && $request->start_time != "" && $request->end_time != "" && $request->type != ""){
          $data = [];
       if($request->type == "list"){
            $user_booking = UserBooking::where('service_provider_id',$request->service_provider_id)
                                        // ->where('service_type','schedule_calendar')
                                        ->where('schedule_id',$request->schedule_id)
                                        ->where('date',$request->date)
                                        ->where('start_time',$request->start_time)
                                        ->where('end_time',$request->end_time)
                                        ->get();
            if($user_booking){
                foreach($user_booking as $booking){

                    $schedule_status = "";
                    if(strtotime($booking->date) >= time()){
                        $schedule_status = "future";
                    }elseif(strtotime($booking->date) <= time()){
                        $schedule_status = "past";
                    }elseif($booking->date == date('Y-m-d')){
                        $schedule_status = "present";
                    }
                    $user = User::find($booking->customer_id);
                
                    $data[] = array(
                        'name'                 => $user->name,
                        'username'             => $user->username,
                        'profile_pic'          => url('storage/profile_image/'.$user->profile_picture),
                        'xmppid'               => $user->xmppid,
                        'booking_id'           => $booking->booking_id,
                        'service_provider_id'  => $booking->service_provider_id,
                        'customer_id'          => $booking->customer_id,
                        'service_type'         => $booking->service_type,
                        'schedule_id'          => $booking->schedule_id,
                        'date'                 => $booking->date,
                        'start_time'           => $booking->start_time,
                        'end_time'             => $booking->end_time,
                        'to_date'              => $booking->to_date,
                        'request_type'         => $booking->request_type,
                        'reschedule_request'   => $booking->reschedule_request,
                        'refund_request'       => $booking->refund_request,
                        'schedule_status'      => $schedule_status,
                        'requested_by'         => $booking->requested_by
                    );
                }
            }
       }elseif($request->type == "refund_request"){
            $user_booking = UserBooking::where('service_provider_id',$request->service_provider_id)
                                        // ->where('service_type','schedule_calendar')
                                        ->where('schedule_id',$request->schedule_id)
                                        ->where('date',$request->date)
                                        ->where('start_time',$request->start_time)
                                        ->where('end_time',$request->end_time)
                                        ->where('refund_request',1)
                                        ->get();
                    
             if($user_booking){
                foreach($user_booking as $booking){

                    $schedule_status = "";
                    if(strtotime($booking->date) >= time()){
                        $schedule_status = "future";
                    }elseif(strtotime($booking->date) <= time()){
                        $schedule_status = "past";
                    }elseif($booking->date == date('Y-m-d')){
                        $schedule_status = "present";
                    }
                    $user = User::find($booking->customer_id);
                
                    $data[] = array(
                        'name'                 => $user->name,
                        'username'             => $user->username,
                        'profile_pic'          => url('storage/profile_image/'.$user->profile_picture),
                        'xmppid'               => $user->xmppid,
                        'booking_id'           => $booking->booking_id,
                        'service_provider_id'  => $booking->service_provider_id,
                        'customer_id'          => $booking->customer_id,
                        'service_type'         => $booking->service_type,
                        'schedule_id'          => $booking->schedule_id,
                        'date'                 => $booking->date,
                        'start_time'           => $booking->start_time,
                        'end_time'             => $booking->end_time,
                        'to_date'              => $booking->to_date,
                        'request_type'         => $booking->request_type,
                        'reschedule_request'   => $booking->reschedule_request,
                        'refund_request'       => $booking->refund_request,
                        'schedule_status'      => $schedule_status,
                        'requested_by'         => $booking->requested_by
                    );
                }
            }
       }elseif($request->type == "reschedule_request"){
            $user_booking = UserBooking::where('service_provider_id',$request->service_provider_id)
                                        ->where('service_type','schedule_calendar')
                                        ->where('schedule_id',$request->schedule_id)
                                        ->where('date','>=',$request->date)
                                        ->where('date','<=',$request->date)
                                        ->where('start_time',$request->start_time)
                                        ->where('end_time',$request->end_time)
                                        // ->where('reschedule_request',1)
                                        ->get();
            
            //for appointment & discussion
            $customer_bookings = UserBooking::where('service_provider_id',$request->service_provider_id)
                                              ->where('service_type','!=','schedule_calendar')
                                              ->where('schedule_id',$request->schedule_id)
                                              ->where('date','>=',$request->date)
                                              ->where('date','<=',$request->date)
                                              ->where('start_time',$request->start_time)
                                              ->where('end_time',$request->end_time)
                                              ->where('reschedule_request',1)
                                              ->get();
          
            $schedule_calendar_requests = Schedule_calendar_requests::where('service_provider_id',$request->service_provider_id)
                                                                    ->where('schedule_id',$request->schedule_id)
                                                                    ->where('date','>=',$request->date)
                                                                    ->where('start_time',$request->start_time)
                                                                    ->where('end_time',$request->end_time)
                                                                    ->where('request_type','reschedule')
                                                                    ->where('status','pending')
                                                                    ->get();
                // dd($schedule_calendar_requests);
     
            foreach($user_booking as $booking){
                
                $schedule_calendar_requests = Schedule_calendar_requests::where('user_bookings_id',$booking->id)->where('status','pending')->get();
               
                if($schedule_calendar_requests){

                    foreach($schedule_calendar_requests as $schedule_calendar_request){

                        $schedule_status = "";
                        if(strtotime($schedule_calendar_request->date) >= time()){
                            $schedule_status = "future";
                        }elseif(strtotime($schedule_calendar_request->date) <= time()){
                            $schedule_status = "past";
                        }elseif($schedule_calendar_request->date == date('Y-m-d')){
                            $schedule_status = "present";
                        }
                        $user = User::find($schedule_calendar_request->customer_id);
                    
                        $data[] = array(
                            'name'                 => $user->name,
                            'username'             => $user->username,
                            'profile_pic'          => url('storage/profile_image/'.$user->profile_picture),
                            'xmppid'               => $user->xmppid,
                            'booking_id'           => $booking->booking_id,
                            'service_provider_id'  => $booking->service_provider_id,
                            'customer_id'          => $booking->customer_id,
                            'service_type'         => $booking->service_type,
                            'schedule_id'          => $booking->schedule_id,
                            'date'                 => $schedule_calendar_request->date,
                            'start_time'           => $booking->start_time,
                            'end_time'             => $booking->end_time,
                            'to_date'              => $schedule_calendar_request->date,
                            'request_type'         => $schedule_calendar_request->request_type,
                            'reschedule_request'   => $schedule_calendar_request->status,
                            'refund_request'       => $schedule_calendar_request->status,
                            'schedule_status'      => $schedule_status,
                            'requested_by'         => $schedule_calendar_request->requested_by
                        );
                    }
                }
               
            }

            //for appointments & discussions
            if($customer_bookings){
         
                foreach($customer_bookings as $customer_booking){

                    $schedule_status = "";
                    if(strtotime($customer_booking->date) >= time()){
                        $schedule_status = "future";
                    }elseif(strtotime($customer_booking->date) <= time()){
                        $schedule_status = "past";
                    }elseif($customer_booking->date == date('Y-m-d')){
                        $schedule_status = "present";
                    }
                    $user = User::find($customer_booking->customer_id);
                
                    $data[] = array(
                        'name'                 => $user->name,
                        'username'             => $user->username,
                        'profile_pic'          => url('storage/profile_image/'.$user->profile_picture),
                        'xmppid'               => $user->xmppid,
                        'booking_id'           => $customer_booking->booking_id,
                        'service_provider_id'  => $customer_booking->service_provider_id,
                        'customer_id'          => $customer_booking->customer_id,
                        'service_type'         => $customer_booking->service_type,
                        'schedule_id'          => $customer_booking->schedule_id,
                        'date'                 => $customer_booking->date,
                        'start_time'           => $customer_booking->start_time,
                        'end_time'             => $customer_booking->end_time,
                        'to_date'              => $customer_booking->to_date,
                        'request_type'         => $customer_booking->request_type,
                        'reschedule_request'   => $customer_booking->reschedule_request,
                        'refund_request'       => $customer_booking->refund_request,
                        'schedule_status'      => $schedule_status,
                        'requested_by'         => $customer_booking->requested_by
                    );
                }
     
            }
        }

            return response()->json($data); 
        }else{
            return response()->json(['status' => 'failed','message' => 'Required fields are missing']);
        }
    }

    //global_search
    public function global_search(Request $request,$keyword)
    {
         $sp = User::select('users.name', 'users.id', 'user_profile.rating', 'user_profile.skill_set', 'c1.category_name as category_name','c2.category_name as service_offered_name')->distinct();
         $user = Auth::user();
          // get total booked duration
        $sp->addSelect([
            'total_duration' => \App\Models\ServiceBooking::select(DB::raw('sum(duration)'))
                ->whereColumn('provider_id', 'users.id')
                // ->where('status', 1)
                ->limit(1)
        ]);


        // get total clients
        $sp->addSelect([
            'total_clients' => \App\Models\ServiceBooking::select(DB::raw('count(distinct user_id)'))
                ->whereColumn('provider_id', 'users.id')
                // ->where('status', 1)
                ->limit(1)
        ]);

         //identify providers
         $sp->whereHas('profile',function($query){
            $query->whereNotNull('service_offered')
                  ->where('service_offered','!=',"")
                  ->where('service_offered','!=',0);
         });

    
        //join
        $sp->join('user_profile','user_profile.user_id','=','users.id');
        $sp->join('categories as c1', 'c1.id', '=', 'user_profile.service_category');
        $sp->join('categories as c2', 'c2.id', '=', 'user_profile.service_offered');
        $sp->join('cities', 'cities.id', '=', 'user_profile.city');
        $sp->join('states', 'states.id', '=', 'user_profile.state');
        $sp->join('user_languages' , 'user_languages.user_id', '=', 'users.id');
        $sp->join('languages', 'languages.id', '=' , 'user_languages.language_id');
        // $sp->leftjoin('discussion_services','discussion_services.user_id', '=' ,'users.id');
        // $sp->leftjoin('open_calendar','open_calendar.user_id', '=', 'users.id');
        // $sp->leftjoin('service_schedules','service_schedules.user_id' ,'=' ,'users.id');
        
        // $sp->where(function($query) {
        //     $query->where('service_schedules.days', 'LIKE', '%3%')
        //           ->orWhere('service_schedules.days', 'LIKE', '%3,%')
        //           ->orWhere('service_schedules.days', 'LIKE', '%,3%')
        //           ->orWhere('service_schedules.days', 'LIKE', '%[3]%');
        // });
        $sp->Where(function($q) use ($keyword){
            $q->where('users.name','LIKE','%'.$keyword.'%')
                ->orWhere('username','LIKE','%'.$keyword.'%')
                ->orWhere('phone','LIKE','%'.$keyword.'%')
                ->orWhere('email','LIKE','%'.$keyword.'%')
                ->orWhere('cities.name', 'like', '%'.$keyword.'%')
                ->orWhere('languages.language', 'like', '%'.$keyword.'%')
                ->orWhere('states.name', 'like', '%'.$keyword.'%')
                ->orWhere('c1.category_name', 'like', '%'.$keyword.'%')
                ->orWhere('user_profile.skill_set','LIKE','%'.$keyword.'%');
               
        });  
        
        $data =  $sp->paginate(5);
        // return $data;
        foreach ($data as $key => $value) {

            if ($value->id == $user->id) {
                // add a new property to the object
                $value->own_profile = true;
            } else {
                $value->own_profile = false;
            }

            $details = $this->serviceProvidersById($request, $value->id);
            $value->details = $details->getData();
        }

    

        return response()->json($data);
    }

    //cancel_booking
    public function cancel_booking(Request $request)
    {
        $date = $request->date;
        $start_time = $request->start_time;
        $end_time   = $request->end_time;
        $schedule_id = $request->schedule_id;
        $service_provider_id = $request->service_provider_id;
        $customer_id = $request->customer_id;
        if($request->requested_by == "provider"){+

            //reschedule
            UserBooking::where('service_provider_id',$service_provider_id)
                       ->where('date',$date)
                       ->where('start_time',$start_time)
                       ->where('end_time',$end_time)
                       ->where('schedule_id',$schedule_id)
                       ->update(['refund_request' => 1,'requested_by' => 'provider','status' => 3]);

                       $status  = 'success';
                       $message = 'Schedule cancelled successfully';
        }else{
           
            //service taker
            $user_booking = UserBooking::where('service_provider_id',$service_provider_id)
                                       ->where('customer_id',$customer_id)
                                       ->where('date',$date)
                                       ->where('start_time',$start_time)
                                       ->where('end_time',$end_time)
                                       ->where('schedule_id',$schedule_id)
                                       ->first();
            if($user_booking){
                
                $from_time = new DateTime($user_booking->start_time);
                $end_time  = new DateTime(date('H:i:s'));
                $interval  = $from_time->diff($end_time);
                $diff      = $interval->h;
                
                if(strtotime($user_booking->date) >= time() || $user_booking->date == date('Y-m-d')){
                    if($diff >= 6){
                        $booking = UserBooking::where('service_provider_id',$service_provider_id)
                                                ->where('customer_id',$customer_id)
                                                ->where('date',$date)
                                                ->where('start_time',$start_time)
                                                ->where('end_time',$end_time)
                                                ->where('schedule_id',$schedule_id)
                                                ->update(['refund_request' => 1,'status' => 3 ,'requested_by' => 'taker']);
                        $status  = 'success';
                        $message = 'Schedule cancelled successfully';
                    }else{
                        $booking = UserBooking::where('service_provider_id',$service_provider_id)
                                                ->where('customer_id',$customer_id)
                                                ->where('date',$date)
                                                ->where('start_time',$start_time)
                                                ->where('end_time',$end_time)
                                                ->where('schedule_id',$schedule_id)
                                                ->update(['refund_request' => 1,'requested_by' => 'taker']);
                        $status  = 'success';
                        $message = 'Cancel request sent!';
                    }
                }else{
                    $status  = 'failed';
                    $message = 'Time limit exceeded for cancellation';
                }
            }else{
                $status = "warning";
                $message = "Slot not found";
            }
            
        }

        return response()->json(['status' => $status, 'message' => $message]);
    }

    /**
     *  individual_cancel for service provider
     */
    public function individual_cancel(Request $request)
    {
        $date                = $request->date;
        $start_time          = $request->start_time;
        $end_time            = $request->end_time;
        $schedule_id         = $request->schedule_id;
        $service_provider_id = $request->service_provider_id;
        $customer_id         = $request->customer_id;
        
        if($date != "" && $start_time != "" && $end_time != "" && $schedule_id != "" && $service_provider_id != "" && $customer_id != ""){

          //check already requested by taker
          $user_booking    = UserBooking::where('service_provider_id',$service_provider_id)
                                        ->where('date',$date)
                                        ->where('start_time',$start_time)
                                        ->where('end_time',$end_time)
                                        ->where('customer_id',$customer_id)
                                        ->where('schedule_id',$schedule_id)
                                        ->first();
          if($user_booking){
             if($user_booking->requested_by == "taker"){

                $cancel_schedule =   UserBooking::where('service_provider_id',$service_provider_id)
                                            ->where('date',$date)
                                            ->where('start_time',$start_time)
                                            ->where('end_time',$end_time)
                                            ->where('schedule_id',$schedule_id)
                                            ->where('customer_id',$customer_id)
                                            ->update(['refund_request' => 1,'status' => 3]);
             }else{
                
                $cancel_schedule =   UserBooking::where('service_provider_id',$service_provider_id)
                                            ->where('date',$date)
                                            ->where('start_time',$start_time)
                                            ->where('end_time',$end_time)
                                            ->where('schedule_id',$schedule_id)
                                            ->where('customer_id',$customer_id)
                                            ->update(['refund_request' => 1,'requested_by' => 'provider','status' => 3]);
             }

             if($cancel_schedule){

                $status  = 'success';
                $message = 'Schedule cancelled successfully';
             }

          }else{
            $status   = 'failed';
            $message  = 'Schedule not found!';
           }

        }else{
            $status  = "failed";
            $message = 'Required fields are missing';
        }
        return response()->json(['status' => $status, 'message' => $message]);
    }

    /**
     *  send_reschedule_request from service taker side
     */
    public function send_reschedule_request(Request $request,$id)
    {
        
        $user_booking = UserBooking::find($id);
        /**
         *  if service type is schedule calender then insert in `schedule_calendar_requests` table
         */
        if($user_booking->service_type == "schedule_calendar"){
            
            $check_schedulecal_request = Schedule_calendar_requests::where('user_bookings_id',$user_booking->id)
                                                                    ->where('customer_id',$user_booking->customer_id)
                                                               ->first();
            $create_schedulecal_req = false;

            if(!empty($check_schedulecal_request)){
                 
                if($check_schedulecal_request->status == RESCHEDULE_REJECTED){
                    $create_schedulecal_req = true;
                }
            }else{
                $create_schedulecal_req = true;
            }

            if($create_schedulecal_req == true){
                $schedulecal_req = new Schedule_calendar_requests();
                $schedulecal_req->user_bookings_id      = $user_booking->id;
                $schedulecal_req->service_provider_id   = $user_booking->service_provider_id;
                $schedulecal_req->customer_id           = $user_booking->customer_id;
                $schedulecal_req->service_type          = $user_booking->service_type;
                $schedulecal_req->schedule_id           = $user_booking->schedule_id;
                $schedulecal_req->date                  = $user_booking->date;
                $schedulecal_req->start_time            = $user_booking->start_time;
                $schedulecal_req->end_time              = $user_booking->end_time;
                $schedulecal_req->status                = RESCHEDULE_REQUESTED;
                $schedulecal_req->request_type          = "reschedule";
                $schedulecal_req->requested_by          = "taker";
                $schedulecal_req->save();

                return response()->json(['status' => 'success','message' => 'Reschedule request sent!']);
            }else{
                return response()->json(['status' => 'failed','message' => 'Oops already requested!']);
            }
        }else{

        if($user_booking){
            $user_booking->reschedule_request = RESCHEDULE_REQUESTED;
            $user_booking->requested_by = "taker";
            $user_booking->save();
    
            return response()->json(['status' => 'success','message' => 'Reschedule request sent!']);
        }else{
            return response()->json(['status' => 'failed','message' => 'Oops slot not found!']);

        }
      }
    }

    /**
     *  check_available_time for send reschedule request
     */
    public function check_available_time(Request $request)
    {
        if($request->id != "" && $request->start_time != "" && $request->date != "")
        {
            if(strtotime($request->date) < time()){
                return response()->json(['status' => 'warning','message' => 'past days not allowed']);
            }
            if($request->date == date('Y-m-d')){
                if($request->start_time < date('H:i:s')){
                    return response()->json(['status' => 'warning','message' => 'past days not allowed']);
                }
            }
            $old_booking = UserBooking::find($request->id);
            
            //check session time
            if($old_booking){
               $st_time = strtotime($old_booking->start_time);
               $en_time = strtotime($old_booking->end_time);
               $session = round(abs($st_time - $en_time)/60 , 2);
               
               $start_time = $request->start_time;
               $end_time   = date('H:i:s',strtotime($request->start_time.'+'.$session.' minutes'));
               

               $user_booking = UserBooking::where('service_provider_id',$old_booking->service_provider_id)
                                          ->where('date',$request->date)
                                          ->where(function($query) use ($start_time,$end_time){
                                            $query->where(function($q) use ($start_time, $end_time) {
                                                $q->where('start_time', '<=', $start_time)
                                                  ->where('end_time', '>=', $start_time);
                                            })
                                            ->orWhere(function($q) use ($start_time, $end_time) {
                                                $q->where('start_time', '<=', $end_time)
                                                  ->where('end_time', '>=', $end_time);
                                            })
                                            ->orWhere(function($q) use ($start_time, $end_time) {
                                                $q->where('start_time', '>', $start_time)
                                                  ->where('end_time', '<', $end_time);
                                            });
                                          })
                                          ->get();

                if(count($user_booking) == 0){
                    $status  = "success";
                    $message = "Available";
                }else{
                    $status  = "failed";
                    $message = "Not Available";
                }
            }else{
                $status = "failed";
                $message = "slot not found";
            }
        }else{
            $status = "warning";
            $message = "Required fields are missing";
        }

         return response()->json(['status' => $status, 'message' => $message]);
    }


    /**
     *  provider_send_reschedule_request
     */
    public function provider_send_reschedule_request(Request $request)
    {
        if($request->user_bookings_id != "" && $request->date != "" && $request->start_time != ""){

            if(strtotime($request->date) < time()){
                return response()->json(['status' => 'warning','message' => 'past days not allowed']);
            }
            if($request->date == date('Y-m-d')){
                if($request->start_time > date('H:i:s')){
                    return response()->json(['status' => 'warning','message' => 'past time not allowed']);
                }
            }


        $old_booking = UserBooking::find($request->user_bookings_id);
       
        if($old_booking){
            $st_time = strtotime($old_booking->start_time);
            $en_time = strtotime($old_booking->end_time);
            $session = round(abs($st_time - $en_time)/60 , 2);
            
            $start_time = $request->start_time;
            $end_time   = date('H:i:s',strtotime($request->start_time.'+'.$session.' minutes'));
          
            if($old_booking->service_type == "schedule_calendar"){
                 $check_duplicate = ModelsRequest::where('user_bookings_id',$request->user_bookings_id)
                                                ->where('date',$request->date)
                                                ->where('start_time',$start_time)
                                                ->where('end_time',$end_time)
                                                ->where('requested_by','provider')
                                                ->where('service_provider_id',$old_booking->service_provider_id)
                                                ->where('customer_id',$old_booking->customer_id)
                                                ->get();
                    
                    //if request not created ,then allow to create
                    if(count($check_duplicate) == 0){
                        $re_request = new ModelsRequest;
                        $re_request->user_bookings_id = $request->user_bookings_id;
                        $re_request->date             = $request->date;
                        $re_request->start_time       = $start_time;
                        $re_request->end_time         = $end_time; 
                        $re_request->requested_by     = "provider";
                        $re_request->status           = 1;
                        $re_request->service_provider_id = $old_booking->service_provider_id;
                        $re_request->customer_id      = $old_booking->customer_id;
                        $re_request->save();

                        $status  = "success";
                        $message = "Request sent";
                    }else{
                        $status  = "warning";
                        $message = "Already requested";
                    }
            }else{
                $check_request = ModelsRequest::where('user_bookings_id',$request->user_bookings_id)
                                            ->where('date',$request->date)
                                            ->where('start_time',$start_time)
                                            ->where('end_time',$end_time)
                                            ->where('requested_by','provider')
                                            ->where('status',1)
                                            ->get();    
                    if(count($check_request) == 0){

                        $newrequest = new ModelsRequest;
                        $newrequest->user_bookings_id    = $request->user_bookings_id;
                        $newrequest->service_provider_id = $old_booking->service_provider_id;
                        $newrequest->customer_id         = $old_booking->customer_id;
                        $newrequest->date                = $request->date;
                        $newrequest->start_time          = $start_time;
                        $newrequest->end_time            = $end_time;
                        $newrequest->requested_by	     = 'provider';
                        $newrequest->status              = 1;
                        $newrequest->save();

                        //update status
                        $old_booking->reschedule_request = 1;
                        $old_booking->requested_by       = 'provider';
                        $old_booking->save();

                        $status  = "success";
                        $message = "Request sent";
                    }else{
                        $status  = "warning";
                        $message = "Already requested";
                    }
            }
      
       }else{
            $status = "failed";
            $message = "Slot not found";
       }
      }else{
            $status  = "warning";
            $message = "Required fields are missing";
      }

      return response()->json(['status' => $status, 'message' => $message]);
    }

    /**
     *  get_request_list
     */
    public function get_request_list(Request $request)
    {
        if($request->id != "" && $request->type != ""){
            $result = [];
            $schedule_name = "";
            if($request->type == "provider"){
 
               $all_requests = ModelsRequest::where('service_provider_id',$request->id)
                                             ->where('status',1)->get();
               if($all_requests){
                 foreach($all_requests as $v){
                    $user_booking = UserBooking::find($v->user_bookings_id);
                    if($user_booking){

                        
                        if($user_booking->service_type == "schedule_calendar"){
                            $service_schedule = ServiceSchedule::find($user_booking->schedule_id);
                            $schedule_name = $service_schedule->schedule_name;
                        }

                        $result[] = array(
                            'id'                 => $v->id,
                            'user_bookings_id'   => $v->user_bookings_id,
                            'schedule_name'      => $schedule_name,
                            'service_type'       => $user_booking->service_type,
                            'new_date'           => $v->date,
                            'new_start_time'     => $v->start_time,
                            'new_end_time'       => $v->end_time,
                            'exist_date'         => $user_booking->date,
                            'exist_start_time'   => $user_booking->start_time,
                            'exist_end_time'     => $user_booking->end_time,
                            'requested_by'       => $v->requested_by,
                            'service_provider_id' => $v->service_provider_id,
                            'customer_id'        => $v->customer_id
                        );
                    }
                   
                 }
               }
            }else{

               $all_requests = ModelsRequest::where('customer_id',$request->id)->where('status',1)->get();
               if($all_requests){
                foreach($all_requests as $v){
                   $user_booking = UserBooking::find($v->user_bookings_id);
                   if($user_booking){
  
                   if($user_booking->service_type == "schedule_calendar"){
                       $service_schedule = ServiceSchedule::find($user_booking->schedule_id);
                       $schedule_name = $service_schedule->schedule_name;
                   }
                   $result[] = array(
                    'id'                 => $v->id,
                    'user_bookings_id'   => $v->user_bookings_id,
                    'schedule_name'      => $schedule_name,
                    'service_type'       => $user_booking->service_type,
                    'new_date'           => $v->date,
                    'new_start_time'     => $v->start_time,
                    'new_end_time'       => $v->end_time,
                    'exist_date'         => $user_booking->date,
                    'exist_start_time'   => $user_booking->start_time,
                    'exist_end_time'     => $user_booking->end_time,
                    'requested_by'       => $v->requested_by,
                    'service_provider_id' => $v->service_provider_id,
                    'customer_id'        => $v->customer_id
                );
                }
                   
                }
              }
            }
            return response()->json($result);
        }else{
            return response()->json(['status' => 'failed' ,'message' => "Required fields are missing"]);
        }
    }

    /**
     *  accept_request
     */
    public function accept_request(Request $request,$id)
    {
        if($id){
            $req = ModelsRequest::find($id);
            $req->status = 2;
            $req->save();
            
            
            $user_booking = UserBooking::find($req->user_bookings_id);
            if($user_booking->service_type == "schedule_calendar"){
                 
                $schedule_cal_req = Schedule_calendar_requests::where('user_bookings_id',$user_booking->id)
                                                              ->where('service_provider_id',$user_booking->service_provider_id)
                                                              ->where('customer_id',$user_booking->customer_id)
                                                              ->where('schedule_id',$user_booking->schedule_id)
                                                            //   ->where('date',$req->date)
                                                            //   ->where('start_time',$req->start_time)
                                                            //   ->where('end_time',$req->end_time)
                                                              ->where('request_type','reschedule')
                                                              ->first();
                if($schedule_cal_req){
                    
                    $schedule_cal_req->status = "Accepted";
                    $schedule_cal_req->save();
                    return response()->json(['status' => 'success' ,'message' => 'Rescheduled successfully']);
                }else{
                    return response()->json(['status' => 'failed' ,'message' => 'Request not found!']);
                }
            }else{
                $user_booking->date = $req->date;
                $user_booking->start_time = $req->start_time;
                $user_booking->end_time   = $req->end_time;
                $user_booking->status     = 1;
                $user_booking->reschedule_request = 2;
                $user_booking->schedule_status = 'rescheduled';
                $user_booking->save();
                
                return response()->json(['status' => 'success' ,'message' => 'Rescheduled successfully']);
            }
           
        }else{
            return response()->json(['status' => 'failed' ,'message' => 'Request not found!']);
        }
    }

    // checkTotalClientsCount
    //schedulecal_booking_list
    public function schedulecal_booking_list(Request $request,$id=null){
      
        if($request->id != ""){ 
            $current_monthend = Carbon::create(date('Y'),date('m'),1)->endOfMonth();
            $currentMonthEndDate = $current_monthend->format('Y-m-d');
            $user_booking_id = $request->id;
            $booking = UserBooking::find($user_booking_id);
            
            //get days from service schedule table
            $service_schedule = ServiceSchedule::find($booking->schedule_id);
            $days = json_decode($service_schedule->days);
            //get remaining session session details for shedule calendar
           $remaining_sessions = $this->GetRamainingSessionDetails($booking->date,$booking->to_date,$days,$booking->start_time,$booking->end_time);

            $user_bookings = UserBooking::where('service_provider_id',$request->id)
                                        ->where('service_type','schedule_calendar')
                                        ->where('date','>=',date('Y-m-d'))
                                        ->where('start_time','>=',date('H:i:s'))
                                        ->where('to_date','<=',$currentMonthEndDate)
                                        ->get();
             return response()->json($remaining_sessions);
        }else{
            return response()->json(['status' => 'failed' ,'message' => 'Required fields are missing']);
        }
    }

    public function GetRamainingSessionDetails($start_date,$end_date,$days,$start_time,$end_time){
        // echo date('m',strtotime($start_date));die;
        $month_number = intval(date('m',strtotime($start_date)));
        $currentMonthNum = intval(date('m'));
        if($month_number == $currentMonthNum){
            $start_date = date('Y-m-d',strtotime('tomorrow'));
         
        }
        $currentDate = $start_date;
      
        $day_count = 0;
        $return_data = [];
        while (strtotime($currentDate) <= strtotime($end_date)) {
        
              $daystring = date('D',strtotime($currentDate));
              
              if($daystring == "Sun" || $daystring == "sun"){
                 $day_num = 0;
              }elseif($daystring == "Mon" || $daystring == "mon"){
                 $day_num = 1;
              }elseif($daystring == "Tue" || $daystring == "tue"){
                $day_num = 2;
              }elseif($daystring == "Wed" || $daystring == "wed"){
                $day_num = 3;
              }elseif($daystring == "Thu" || $daystring == "thu"){ 
                $day_num = 4;
              }elseif($daystring == "Fri" || $daystring == "fri"){ 
                $day_num = 5;
              }elseif($daystring == "Sat" || $daystring == "sat"){ 
                $day_num = 6;
              }
              if(in_array($day_num,$days)){
                $day_count += 1;
                $return_data[] = array(
                    'date' => $currentDate,
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'day_name' => date('l',strtotime($currentDate)),
                    );
              }
            // Increment the current date by 1 day
            $currentDate = date("Y-m-d", strtotime($currentDate . "+1 day"));
        }

         return $return_data;
    }

    //user_profile
    public function user_profile(Request $request){
        $xmppid = $request->xmppid;
     
        if($xmppid != ""){
            foreach($xmppid as $v){
                $user = User::where('xmppid',$v)->first();
                if(!empty($user)){
                    $return_data[] = array(
                    'userid'    =>  $user->id,
                    'name'      => $user->name,
                    'username'  => $user->username,
                    'email'     => $user->email,
                    'profile_pic'  => url('storage/profile_image/'.$user->profile_picture),
                    'last_login' => $user->last_login
                    );
                }
            }
           

            if(!empty($return_data) && count($return_data) > 0){
                return response()->json(['status' => 'success' ,'data' => $return_data]);
            }else{
                return response()->json(['status' => 'failed' ,'message' => 'User not found']);
            }
        }else{
            return response()->json(['status' => 'failed' ,'message' => 'Required fields are missing']);
        }
    }

    //checkStartBtnStatus
    public function checkStartBtnStatus($service_provider_id,$service_type,$schedule_id,$date,$start_time,$end_time){
            
            $all_session = All_session::where('service_provider_id',$service_provider_id)
                                      ->where('schedule_id',$schedule_id)
                                      ->where('service_type',$service_type)
                                      ->where('date',$date)
                                      ->where('start_time',$start_time)
                                      ->where('end_time',$end_time)
                                      ->first();
          
           if(!empty($all_session)){
            //   $today = date('Y-m-d');
            // $grace_time = Carbon::create(date('Y'),date('m'),date('d'),date('H'),date('i'),date('s'))->addMinutes(-10)->format('H:i:s');
            $st_time = DateTime::createFromFormat('Y-m-d H:i:s', $date.' '.$start_time);
            $grace_time = Carbon::createFromFormat('Y-m-d H:i:s', $date.' '.$start_time)->addMinutes(-10);
            $e_time  = DateTime::createFromFormat('Y-m-d H:i:s', $date.' '.$end_time);
            $current_time = Carbon::now();
           
           
            if($current_time >= $grace_time && $current_time < $e_time){  
            // if($current_time >= $grace_time && $current_time < $e_time){
                return 'enable';
            }else{
                return 'disable';
            }
            //   if($all_session->date == $today && strtotime($start))
           }else{
                return 'disable';
           }
    }

    //checkJoinBtnStatus
    public function checkJoinBtnStatus($service_provider_id,$service_type,$schedule_id,$date,$start_time,$end_time){
        $all_session = All_session::where('service_provider_id',$service_provider_id)
                                    ->where('schedule_id',$schedule_id)
                                    ->where('service_type',$service_type)
                                    ->where('date',$date)
                                    ->where('start_time',$start_time)
                                    ->where('end_time',$end_time)
                                    ->first();
        // dd($all_session);
        $status = "disable";
        if($all_session){
            if(!empty($all_session->status)){
                if($status != "completed"){
                    $status = "enable";
                }
            }
        }
    
        return $status;
    }

    //provider_session_status_update
    public function provider_session_status_update(Request $request){

        if($request->service_provider_id != "" || $request->schedule_id != "" || $request->service_type != "" || $request->date != "" || $request->start_time != "" || $request->end_time != "" || $request->status != ""){
      
         $all_session = All_session::where('service_provider_id',$request->service_provider_id)
                                   ->where('schedule_id',$request->schedule_id)
                                   ->where('service_type',$request->service_type)
                                   ->where('date',$request->date)
                                   ->where('start_time',$request->start_time)
                                   ->where('end_time',$request->end_time)
                                   ->first();
         if($all_session){
            $all_session->status = $request->status;
            $all_session->save();

            return response()->json(['status' => 'success' ,'message' => 'Status updated successfully']);
         }else{
            return response()->json(['status' => 'failed' ,'message' => 'Session not found']);
         }
               
        }else{
            return response()->json(['status' => 'failed' ,'message' => 'Required fields are missing']);
        }
    }

    //upload_file
    public function upload_file(Request $request){

        $foler_path = public_path('media');
      
        if(!Storage::exists($foler_path)){
            Storage::makeDirectory($foler_path, 0755, true);
        }
        
        if($request->file('file')){
            $file = $request->file('file');
            $originalName = $file->getClientOriginalName();
            $filenameWithoutExtension = pathinfo($originalName, PATHINFO_FILENAME);
            $timestamp = now()->format('Ymd_His');
            $fileName = $timestamp . '_' . Str::slug($filenameWithoutExtension);
            $extension = $file->getClientOriginalExtension();
            $finalFileName = $fileName . '.' . $extension;
            $upload_path = $foler_path . '/' . $finalFileName;
            //  echo $finalFileName;die;
            $return_name = url('storage/media/'.$finalFileName);
            // echo $return_name;die;
           if($filepath = $file->storeAs('public/media', $finalFileName)){
               return response()->json(['status' => 'success' ,'message' => 'File uploaded successfully','filepath' => $return_name]);
           }else{
              return response(['status' => 'failed' ,'message' => 'File upload failed']);
           }
            // $path = file()
        }else{
            return response(['status' => 'failed' ,'message' => 'File not found']);
        }
    }

    
    /**
     *  Schedule calendar send reschedule request by service taker
     */
    public function schedule_cal_send_reschedule_request(Request $request){
        if($request->user_bookings_id != "" && $request->date != "" && $request->request_type != "" && $request->requested_by != "" && $request->start_time != "" && $request->end_time != ""){
            $user_booking = UserBooking::find($request->user_bookings_id);
            
            if($request->requested_by == "taker" && $request->request_type == "reschedule"){

            //check if reschedule request is already created
            $schedule_cal_request = Schedule_calendar_requests::where('user_bookings_id',$request->user_bookings_id)
                                                              ->where('service_provider_id',$user_booking->service_provider_id)
                                                              ->where('customer_id',$user_booking->customer_id)
                                                              ->where('service_type','schedule_calendar')
                                                              ->where('schedule_id',$user_booking->schedule_id)
                                                              ->where('date',$request->date)
                                                              ->where('start_time',$request->start_time)
                                                              ->where('end_time',$request->end_time)
                                                              ->where('requested_by','taker')
                                                              ->first();
                                    
                    if(empty($schedule_cal_request)){
                        $reschedule_request = new Schedule_calendar_requests;
                        $reschedule_request->user_bookings_id      = $request->user_bookings_id;
                        $reschedule_request->service_provider_id   = $user_booking->service_provider_id;
                        $reschedule_request->customer_id           = $user_booking->customer_id;
                        $reschedule_request->service_type          = 'schedule_calendar';
                        $reschedule_request->schedule_id           = $user_booking->schedule_id;
                        $reschedule_request->date                  = $request->date;
                        $reschedule_request->start_time            = $request->start_time;
                        $reschedule_request->end_time              = $request->end_time;
                        $reschedule_request->status                = 'pending';
                        $reschedule_request->request_type          = $request->request_type;
                        $reschedule_request->requested_by          = $request->requested_by;
                        $reschedule_request->save();

                        return response(['status' => 'success' ,'message' => 'Reschedule request send successfully','request_info' => $reschedule_request]);
                    }else{
                        return response(['status' => 'failed' ,'message' => 'Reschedule request already send or Slot Not Available']);
                    }

           }else{
                     return response(['status' => 'failed' ,'message' => 'Invalid request || Unknown request type']);
           }
        }else{
            return response(['status' => 'failed' ,'message' => 'Required fields are missing']);
        }
    }


    /**
     *  Schedule Calendar Accept request
     */
     public function schedule_cal_accept_request(Request $request){


        if($request->id != "" && $request->status != ""){

            if($request->status == "accept"){
               $schedule_cal_request = Schedule_calendar_requests::find($request->id);
               $schedule_cal_request->status = "accepted";
               $schedule_cal_request->save();

               return response(['status' => 'success', 'message' => 'Request accepted successfully']);

            }elseif($request->status == "reject"){
                $schedule_cal_request = Schedule_calendar_requests::find($request->id);
                $schedule_cal_request->status = "rejected";
                $schedule_cal_request->save();

                return response(['status' => 'success', 'message' => 'Request rejected successfully']);
            }else{
                //ignore unkown status
                return response(['status' => 'failed','message' => 'Invalid status']);
            }
        }else{
            return response(['status' => 'failed','message' => 'Required fields are missing']);
        }
     }


     /**
      *  Store rating & feedbacks of completed sessions 
      *  using user_bookings primary key (id)
      */

      public function store_rating_feedbacks(Request $request){
             if($request->id != "" && $request->rating != "" && $request->feedback != ""){

                $user_booking = UserBooking::find($request->id);

                if($user_booking){

                    $user_booking->rating = $request->rating;
                    $user_booking->review = $request->feedback;
                    $user_booking->reviewed_at = date('Y-m-d H:i:s');
                    $user_booking->save();

                    //update average rating in user profile 
                    $bookings = UserBooking::where('service_provider_id',$user_booking->service_provider_id)->where('rating','!=',null)->get();
                    
                    if($bookings->count() > 0){ 

                        $points = 0;
                        foreach($bookings as $booking){ 
                            $points = $points + $booking->rating;
                        }

                        $average_rating = $points / $bookings->count();

                        
                        $userprofile = ModelsUserProfile::where('user_id',$user_booking->service_provider_id)->first();
                        $userprofile->rating = $average_rating;
                        $userprofile->save();
                    }
                    return response(['status' => 'success', 'message' => 'Rating & Feedback stored successfully']);
                }else{

                    return response(['status' => 'failed', 'message' => 'User booking not found']);
                }
               
             }else{

                return response(['status' => 'failed', 'message' => 'Required fields are missing']);
             }
      }
      
      /**
       *  fetch list of all ratings & feedbacks of sessions 
       *   based on service provider id
       */

      public  function fetch_all_ratings_feedbacks(Request $request){
          
        if($request->service_provider_id != ""){

            $ratings = UserBooking::where('service_provider_id',$request->service_provider_id)
                                        ->where('rating','!=',null)
                                        ->get();
            if($ratings->count() > 0){

                $points = 0;
                $users = [];

                $provider_profile = User::find($request->service_provider_id);
                $pro_profile = array(
                    'user_name'        => $provider_profile->username,
                    'profile_picture'  => url('storage/profile_image/'.$provider_profile->profile_picture),
                );
                foreach($ratings as $rating){

                    $points = $points + $rating->rating;
                    $user = User::find($rating->customer_id);
                    if($rating->service_type == "schedule_calendar"){
                        $service_schedule = ServiceSchedule::find($rating->schedule_id);
                        $schedule_name = $service_schedule->schedule_name;
                    }elseif($rating->service_type == "open_calendar"){
                       $schedule_name = 'Open Calendar Schedule';
                    }else{
                        $schedule_name = 'Discussion Service';
                    }
                   
                    $users[] = array(
                        'user_id'          => $user->id,
                        'user_name'        => $user->name,
                        'profile_picture'  => url('storage/profile_image/'.$user->profile_picture),
                        'schedule_name'    => $schedule_name,
                        'rating'           => $rating->rating,
                        'feedback'         => $rating->review,
                        'reviewed_at'      => $rating->reviewed_at,
                    );
                }
               
                $average_rating = $points;

                return response(['status' => 'success', 'message' => 'Ratings & Feedback fetched successfully','provider_profile' => $pro_profile,'average_rating' => $average_rating,'ratings' => $users]);
                
            }else{

                return response(['status' => 'failed', 'message' => 'No ratings & feedback found']);
            }
            
            
        }else{

            return response(['status' => 'failed', 'message' => 'Required fields are missing']);
        }
      }



      /**
       *  slot_detailed_view
       */
      public function slot_detailed_view(Request $request){
        
           $service_provider_id = $request->service_provider_id;
           $customer_id         = $request->customer_id;
           $date                = $request->date;
           $schedule_id         = $request->schedule_id;
           $start_time          = $request->start_time;
           $end_time            = $request->end_time;
           $type                = $request->type;
           $service_type        = $request->service_type;

           if($service_provider_id != "" && $date != "" && $schedule_id != "" && $start_time != "" && $end_time != "" && $type != "" && $service_type != ""){

               
             if($type == "taker")  {
                if($customer_id == ""){

                    return response(['status' => 'failed', 'message' => 'Required fields are missing']);
                    
                }else{

                    if($service_type == "discussion"){

                        $user_booking = UserBooking::where('service_provider_id',$service_provider_id)
                                                    ->where('customer_id',$customer_id)
                                                    ->whereDate('date','<=',$date)
                                                    ->whereDate('to_date','>=',$date)
                                                    // ->where('schedule_id',$schedule_id)
                                                    ->where('start_time',$start_time)
                                                    ->where('end_time',$end_time)
                                                    ->first();
                    }else{
                        $user_booking = UserBooking::where('service_provider_id',$service_provider_id)
                                                    ->where('customer_id',$customer_id)
                                                    ->whereDate('date','<=',$date)
                                                    ->whereDate('to_date','>=',$date)
                                                    ->where('schedule_id',$schedule_id)
                                                    ->where('start_time',$start_time)
                                                    ->where('end_time',$end_time)
                                                    ->first();
                    }
                   
                }
             }else{
                 
                if($service_type == "discussion"){
                    $user_booking = UserBooking::where('service_provider_id',$service_provider_id)
                                                ->whereDate('date','<=',$date)
                                                ->whereDate('to_date','>=',$date)
                                                // ->where('schedule_id',$schedule_id)
                                                ->where('start_time',$start_time)
                                                ->where('end_time',$end_time)
                                                ->first();
                }else{
                    $user_booking = UserBooking::where('service_provider_id',$service_provider_id)
                                                ->whereDate('date','<=',$date)
                                                ->whereDate('to_date','>=',$date)
                                                ->where('schedule_id',$schedule_id)
                                                ->where('start_time',$start_time)
                                                ->where('end_time',$end_time)
                                                ->first();
                }
               
             }
             
             
            if(!empty($user_booking)){
                 
                $user_profile = ModelsUserProfile::where('user_id',$service_provider_id)->first();
                $offered_service = Category::where('id',$user_profile->service_offered)->pluck('category_name')->first();
                $service_category = Category::where('id',$user_profile->service_category)->pluck('category_name')->first();
                $user = User::findOrFail($user_booking->customer_id);

                //find schedule status
                $schedule_status = "";
                if(strtotime($user_booking->to_date) >= time() && strtotime($user_booking->date) >= time()){
                    $schedule_status = "future";
                }elseif(strtotime($user_booking->to_date) <= time() && strtotime($user_booking->date) <= time()){
                    $schedule_status = "past";
                }else{
                    $schedule_status = "present";
                }

                // schedule calendar

                if($user_booking->service_type == "schedule_calendar"){

                    $slot_booking = UserBooking::where('service_provider_id',$service_provider_id)
                                                ->where('customer_id',$user_booking->customer_id)
                                                ->whereDate('date','<=',$date)
                                                ->whereDate('to_date','>=',$date)
                                                ->where('schedule_id',$schedule_id)
                                                ->where('start_time',$start_time)
                                                ->where('end_time',$end_time)
                                                ->get();

                    $service_schedule = ServiceSchedule::find($user_booking->schedule_id);

                    $current_date = date('Y-m-d');
                    $start_timestamp = strtotime($user_booking->date);
                    $end_timestamp = strtotime($user_booking->to_date) ?? $user_booking->date;
                    $date_to_check_timestamp = strtotime($current_date);
                    // dd($date_to_check_timestamp);
                    if (($date_to_check_timestamp >= $start_timestamp) && ($date_to_check_timestamp <= $end_timestamp)) {
                        $on_going = true;
                    } else {
                        $on_going = false;
                    }
                  
                    
                    $schedule_worktime = ScheduleWorktime::where('schedule_id',$user_booking->schedule_id)
                                                        ->where('start_time',$user_booking->start_time)
                                                        ->where('end_time',$user_booking->end_time)
                                                        ->first();
                    $booking_id = "";

                    if($schedule_worktime){
                        $booking_id = "WRK".$schedule_worktime->id;
                     }
                     
        
                       //check bookings status is completed or not
                       $status = "";
                       if($user_booking->to_date == date('Y-m-d') &&  date('H:i:s') > $user_booking->end_time && $user_booking->status != 2 && $user_booking->status != 3){
                        
                          $status = COMPLETED;
                       }else{
                         $status = $user_booking->status;
                       }

                    /**
                     *  find available days depending upon appointment & month
                     */
                    $bookingAvailableDays = [];
                    if($service_schedule->charges_per == 1){
                        $daystring = date('D',strtotime($user_booking->date));
                        $day_num = $this->get_daynum_from_daystring($daystring);
                        
                        $bookingAvailableDays = [$day_num];
                        
                    }else{
                        $daystring = date('D',strtotime('today'));
                        
                        $day_num = $this->get_daynum_from_daystring($daystring);
                        
                        $all_sessions = All_session::where('schedule_id',$user_booking->schedule_id)
                                                    ->where('service_provider_id',$user_booking->service_provider_id)
                                                    ->where('date','>=',date('Y-m-d'))
                                                    ->where('date','>=',$user_booking->date)
                                                    ->where('date','<=',$user_booking->to_date)
                                                    ->get();
                        $session_daynum = [];
                        if($all_sessions->count() > 0){
                        
                            foreach($all_sessions as $session){
                                
                                $session_daystring = "";
                                $session_daystring = date('D',strtotime($session->date));
                            
                                $session_daynum[] = $this->get_daynum_from_daystring($session_daystring);

                                $session_daynum = array_unique($session_daynum);
                            }

                        
                        } 
                        $bookingAvailableDays = $session_daynum;
                    }

                    /**
                     *  Get refund_request_count
                     */
                    $refund_request_count = Schedule_calendar_requests::where('user_bookings_id',$user_booking->id)
                                                                        ->where('request_type',REQUEST_TYPE_REFUND)
                                                                        ->get()->count();
                    /**
                     *  Get schedule_cal_reschedule_request_count
                     */

                     $schedule_cal_reschedule_request_count = Schedule_calendar_requests::where('user_bookings_id',$user_booking->id)
                                                                                        ->where('request_type',REQUEST_TYPE_RESCHEDULE)
                                                                                        ->get()->count();
                    
                    /**
                     *  Get Refund request status
                     *  */                       
                    if($refund_request_count > 0){
                        $refund_request_status = 1;
                    }else{
                        $refund_request_status = 0;
                    }    
                    
                    /**
                     *  Get Reschedule request status
                     */
                    if($schedule_cal_reschedule_request_count > 0){
                        $reschedule_request_status = 1;
                    }else{
                        $reschedule_request_status = 0;
                    }

                    $user_data = array(
                        'id'           => $user_booking->id,
                        'customer_id'  => $user_booking->customer_id,
                        'booking_id'   => $booking_id,
                        'schedule_name'=> $service_schedule->schedule_name,
                        'service_provider_id' => $user_booking->service_provider_id,
                        'service_type' => $user_booking->service_type,
                        'schedule_id'  => $user_booking->schedule_id,
                        'from_date'         => $user_booking->date,
                        'start_time'   => $user_booking->start_time,
                        'end_time'     => $user_booking->end_time,
                        'status'       => $status,
                        'days'         => $bookingAvailableDays,
                        'to_date'      => $user_booking->to_date ?? $user_booking->date,
                        'profile_pic'  => url('storage/profile_image/'.$user->profile_picture),
                        'user_name'    => $user->username,
                        'xmppid'       => "",
                        'offered_service' => $offered_service,
                        'service_category' => $service_category,
                        'price'        => $service_schedule->charges_per_session,
                        'paid_by'      => $service_schedule->paid_by,
                        'on_going'     => $on_going,
                        'refund_request_count' => $refund_request_count,
                        // 'reschedule_request_count' => $reschedule_request_count, 
                        'reschedule_request_count' => $schedule_cal_reschedule_request_count,
                        'clients_per_session' => count($slot_booking),
                        'available_slots_count'      => $service_schedule->clients_per_session - count($slot_booking),
                        'refund_request_status'      => $refund_request_status,
                        'reschedule_request_status'  => $reschedule_request_status,
                        'schedule_status'            => $schedule_status,
                        'button'                     => $this->checkStartBtnStatus($user_booking->service_provider_id,$user_booking->service_type,$user_booking->schedule_id,$user_booking->date,$user_booking->start_time,$user_booking->end_time)
    
                    );
                  
                    return response(['status' => 'success', 'message' => 'Booking details', 'data' => $user_data]);

                }elseif($user_booking->service_type == "open_calendar"){ 
                    
                    $open_calendar = OpenCalendar::findOrFail($user_booking->schedule_id);
                    $bk_from = new DateTime($user_booking->start_time);
                    $bk_to   = new DateTime($user_booking->end_time);
                    $bk_interval = $bk_from->diff($bk_to);
                    $bk_diff = $bk_interval->i;
                    $open_calendar_schedule = OpenCalendarSchedule::where('open_calendar_id',$user_booking->schedule_id)
                                                                   ->where('time_per_session',$bk_diff)->first();
                    if(empty($open_calendar_schedule)){
                        $price = 0;
                    }
                    else{
                        $price = $open_calendar_schedule->price;    
                    }
                    
                    
                    if($user_booking->refund_request != 0){
                        $Refund_req_count = 1;
                    }else{
                        $Refund_req_count = 0;
                    }

                    $refund_request_count = $user_booking->refund_request;
                    $reschedule_request_count = $user_booking->reschedule_request;
                    $available_slots_count = 0;
                    
                    //Find daynum
                    $daystring = date('D',strtotime($user_booking->date));
                    $day_num = [$this->get_daynum_from_daystring($daystring)];
                    //check bookings status is completed or not
                    $status = "";
                    if($user_booking->to_date == date('Y-m-d') &&  date('H:i:s') > $user_booking->end_time && $user_booking->status != 2 && $user_booking->status != 3){
                     
                       $status = COMPLETED;
                    }else{
                      $status = $user_booking->status;
                    }
                    if($user_booking->reschedule_request != 0){
                         $Reschedule_reqCount = 1;
                    }else{
                        $Reschedule_reqCount = 0;
                    }
                    $user_data = array(
                        'id'           => $user_booking->id,
                        'customer_id'  => $user_booking->customer_id,
                        'booking_id'   => $user_booking->booking_id,
                        'schedule_name'=> "",
                        'service_provider_id' => $user_booking->service_provider_id,
                        'service_type' => $user_booking->service_type,
                        'schedule_id'  => $user_booking->schedule_id,
                        'from_date'         => $user_booking->date,
                        'start_time'   => $user_booking->start_time,
                        'end_time'     => $user_booking->end_time,
                        'status'       => $status,
                        'days'         => $day_num,
                        'to_date'      => $user_booking->to_date ?? $user_booking->date,
                        'profile_pic'  => url('storage/profile_image/'.$user->profile_picture),
                        'user_name'    => $user->username,
                        'xmppid'       => "",
                        'offered_service' => $offered_service,
                        'service_category' => $service_category,
                        'price'        => $price,
                        'paid_by'      => $open_calendar->paid_by,
                        'refund_request_count' => $refund_request_count,
                        // 'reschedule_request_count' => $reschedule_request_count, 
                        'reschedule_request_count' => $Reschedule_reqCount,
                        'clients_per_session' => 1,
                        'available_slots_count'      => 0,
                        'refund_request_status'      => $user_booking->refund_request,
                        'reschedule_request_status'  => $Refund_req_count,
                        'schedule_status'            => $schedule_status,
                        'button'                     => $this->checkStartBtnStatus($user_booking->service_provider_id,$user_booking->service_type,$user_booking->schedule_id,$user_booking->date,$user_booking->start_time,$user_booking->end_time)
    
                    );

                    return response(['status' => 'success', 'message' => 'Booking details', 'data' => $user_data]);

                }elseif($user_booking->service_type == "discussion"){

                    $DiscussionService = DiscussionService::where('user_id',$user_booking->service_provider_id)->first();
                    //check bookings status is completed or not
                    $status = "";
                    if($user_booking->to_date == date('Y-m-d') &&  date('H:i:s') > $user_booking->end_time && $user_booking->status != 2 && $user_booking->status != 3){
                    
                        $status = COMPLETED;
                    }else{
                    $status = $user_booking->status;
                    }
                    if($user_booking->reschedule_request != 0){
                        $Reschedule_reqCount = 1;
                    }else{
                        $Reschedule_reqCount = 0;
                    }


                    /**
                     *  get refund request count
                     */
                    if($user_booking->refund_request != 0){
                        $Refund_req_count = 1;
                    }else{
                        $Refund_req_count = 0;
                    }

                    $user_data = array(
                        'id'           => $user_booking->id,
                        'customer_id'  => $user_booking->customer_id,
                        'booking_id'   => $user_booking->booking_id,
                        'schedule_name'=> "discussion",
                        'service_provider_id' => $user_booking->service_provider_id,
                        'service_type' => $user_booking->service_type,
                        'schedule_id'  => $user_booking->schedule_id,
                        'from_date'         => $user_booking->date,
                        'start_time'   => $user_booking->start_time,
                        'end_time'     => $user_booking->end_time,
                        'status'       => $status,
                        'days'         => $DiscussionService->days,
                        'to_date'      => $user_booking->to_date ?? $user_booking->date,
                        'profile_pic'  => url('storage/profile_image/'.$user->profile_picture),
                        'user_name'    => $user->username,
                        'xmppid'       => "",
                        'offered_service' => $offered_service,
                        'service_category' => $service_category,
                        'price'        => 0,
                        'paid_by'      => 1,
                        'refund_request_count' => $Refund_req_count,
                        // 'reschedule_request_count' => $reschedule_request_count, 
                        'reschedule_request_count' => $Reschedule_reqCount,
                        'clients_per_session' => 1,
                        'available_slots_count'      => 0,
                        'refund_request_status'      => $user_booking->refund_request,
                        'reschedule_request_status'  => $user_booking->reschedule_request,
                        'schedule_status'            => $schedule_status,
                        'button'                     => $this->checkStartBtnStatus($user_booking->service_provider_id,$user_booking->service_type,$user_booking->schedule_id,$user_booking->date,$user_booking->start_time,$user_booking->end_time)
    
                    );

                    return response(['status' => 'success', 'message' => 'Booking details', 'data' => $user_data]);
                }
                 
            }else{
                return response(['status' => 'failed', 'message' => 'Slot not available']);
            }
               
           }else{
               
               return response(['status' => 'failed', 'message' => 'Required fields are missing']);
           }
      }
      

}
