HEX
Server: Apache/2.4.46 (Ubuntu)
System: Linux localhost 5.11.0-49-generic #55-Ubuntu SMP Wed Jan 12 17:36:34 UTC 2022 x86_64
User: root (0)
PHP: 7.4.16
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/html/sarvodayahospital/app/Http/Controllers/AppointmentController.php
<?php

namespace App\Http\Controllers;

use App\AppointmentBook;
use App\BookingData;
use App\ccAvenue;
use App\ccAvenueCrypto;
use App\listCity;
use App\listUsers;
use App\Mail\AppointmentConfirm;
use App\Models\Appointment;
use App\Models\Country;
use App\Models\Doctor;
use App\Models\Feedback;
use App\Models\Hospital;
use App\Models\Patient;
use App\Models\PatientMember;
use App\Slots;
use App\Sms;
use Carbon\Carbon;
use ErrorException;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Http;

class AppointmentController extends Controller
{
    public function index(Request $request)
    {
        //pass
    }

    /**
     * This method shows login page in appointment.
     *
     * @param Request $request request variable
     *
     * @return View view view pages
     */
    public function login(Request $request)
    {
        $doctor_id = session()->get('patient.doctor_id');
        $doctor = Doctor::where('id', $doctor_id)->first();
        if (is_null($doctor)) {
            return redirect()->route('doctors');
        }
        $phone = session()->get('patient.Phone');

        $user = Auth::user();
        $this->destroyInSession();
        if (is_null($user)) {
            //$this->destroyInSession();
            session()->put('patient.Phone', $phone);
            session()->put('patient.doctor_id', $doctor_id);

            return view('pages.appointment-login', compact('doctor'));
        } else {
            return redirect()->route('appointment.patient-select');
        }
    }

    /**
     * Generate OTP and send to specified mobile number.
     *
     * @param Request $request Request variables
     *
     * @return Response
     */
    public function generate(Request $request)
    {
        /* Validate Data */
        $request->validate(
            [
                'Phone' => 'required',
            ]
        );

        /* Generate An OTP */
        $sms = new Sms();
        $otp = rand(1000, 9999);
        $addSeconds = config('sarvodaya.sms_resend_interval');
        $now = carbon::now()->addSecond($addSeconds);
        session()->put('patient.otp', $otp);
        session()->put('patient.Phone', $request->Phone);
        session()->put('patient.otp_expire_at', $now);
        $status = $sms->sendOTP($otp, $request->Phone);
        return $status;
    }

    /**
     * Validate login with OTP and redirect to specified page.
     *
     * @param Request $request Request variables
     *
     * @return View
     */
    public function loginWithOtp(Request $request)
    {
        /* Validation */
        $request->validate(
            [
                'Phone' => 'required',
                'otp' => 'required',
            ]
        );
        $otp_expire_at = session()->get('patient.otp_expire_at');
        $now = carbon::now();
        if ($now->gt($otp_expire_at)) {
            //$this->generate($request);
            return response()->json(['Your OTP expired, please click on resend otp.'], 401);
        }

        $sphone = session()->get('patient.Phone');
        $sotp = (int) session()->get('patient.otp');
        $otp = explode(',', $request->otp);
        $otp = implode('', $otp);
        $phone = $request->Phone;

        if (($sotp == $otp) && ($phone == $sphone)) {
            session()->forget('patient.otp');
            session()->forget('patient.otp_expire_at');
            session()->put('patient.should_login', true);
            return response()->json(['message' => route('appointment.should-login')], 200);
        } else {
            return response()->json(['Your OTP is not correct.'], 401);
        }
    }

    public function shouldLogin(Request $request)
    {
        $shouldlogin = session()->get('patient.should_login');
        if (!$shouldlogin) {
            return redirect()->route('appointment.login');
        }
        session()->forget('patient.should_login');
        //check API user or not
        $hospitals = Hospital::get();
        foreach ($hospitals as $h) {
            $arrayfacilityGUID[] = $h->FacilityGUID;
        }

        $phone = session()->get('patient.Phone');

        $listUsers = new listUsers();
        $resp = $listUsers->getUsers($phone);
        $data = json_decode($resp, false);

        //check Patient
        $patient = Patient::where('Phone', $phone)->first();

        if ($data->success) {
            if (is_null($patient)) {
                $patient = Patient::create(
                    [
                        'FirstName' => $data->data[0]->personName,
                        //'LastName' => $request->LastName,
                        //'Email' => $request->Email,
                        'Phone' => $request->session()->get('patient.Phone'),
                        'Gender' => (($data->data[0]->gender) == 'M') ? '1' : '2',
                        'DOB' => Carbon::parse($data->data[0]->formattedDOB)->format('Y-m-d'),
                        'published_at' => Carbon::now(),
                    ]
                );
            }
            Auth::login($patient);
            session()->regenerate();
            return redirect()->route('appointment.patient-select');
        } else {
            if (is_null($patient)) {
                return redirect()->route('appointment.patients-detail');
            } else {
                Auth::login($patient);
                session()->regenerate();

                return redirect()->route('appointment.patient-select');
            }
        }
    }

    /**
     * This method shows patient details page in appointment.
     *
     * @param Request $request request variable
     *
     * @return View view view pages
     */
    public function getPatientsDetail(Request $request)
    {
        $doctor_id = session()->get('patient.doctor_id');
        $doctor = Doctor::where('id', $doctor_id)->first();
        if (is_null($doctor)) {
            return redirect()->route('doctors');
        }
        $phone = session()->get('patient.Phone');

        $countries = Country::query()->with('states')->get();

        if (is_null($phone) || ($phone == '')) {
            return redirect()->route('appointment.login');
        }
        return view('pages.appointment-patients-detail', compact('doctor', 'phone', 'countries'));
    }

    /**
     * This method save patient details in DB.
     *
     * @param Request $request request variable
     *
     * @return View view view pages
     */
    public function savePatientsDetail(Request $request)
    {
        $doctor_id = session()->get('patient.doctor_id');
        $doctor = Doctor::where('id', $doctor_id)->first();
        if (is_null($doctor)) {
            return redirect()->route('doctors');
        }

        $user = Auth::user();
        if (is_null($user)) {
            /* Validation */
            $request->validate(
                [
                    'FirstName' => ['required', 'string', 'max:255'],
                    'LastName' => ['string', 'max:255', 'nullable'],
                    'DOB' => ['required'],
                    'gender' => ['required'],
                    'Email' => ['email:rfc,dns', 'nullable'],
                    'Phone' => ['required', 'numeric', 'digits:10', 'unique:patients'],
                ]
            );

            $patient = Patient::create(
                [
                    'FirstName' => $request->FirstName,
                    'LastName' => $request->LastName,
                    'Email' => $request->Email,
                    'Phone' => $request->session()->get('patient.Phone'),
                    'Gender' => $request->gender,
                    'DOB' => Carbon::parse($request->DOB)->format('Y-m-d'),
                    'published_at' => Carbon::now(),
                ]
            );
            auth()->login($patient, true);
        }
        session()->put('patient.FName', $request->FirstName);
        session()->put('patient.LName', $request->LastName);
        session()->put('patient.FullName', $request->FirstName . ' ' . $request->LastName);
        session()->put('patient.Email', $request->Email);
        session()->put('patient.Gender', $request->gender);
        session()->put('patient.DOB', $request->DOB);
        session()->put('patient.mrn', '');
        session()->put('patient.country', $request->country);
        session()->put('patient.countryName', $request->countryName);
        session()->put('patient.state', $request->state);
        session()->put('patient.stateName', $request->stateName);
        session()->put('patient.city', $request->city);
        session()->put('patient.cityName', $request->cityName);
        session()->put('patient.address', $request->address);
        session()->put('patient.pin', $request->pin);
        session()->put('patient.prefix', $request->prefix);

        session()->regenerate();
        if ($request->api_new_user == 1) {
            return redirect()->route('appointment.slot-select');
        } else {
            return redirect()->route('appointment.patient-select');
        }
    }

    /**
     * Select patient from Memebers data.
     *
     * @param Request $request Request data
     *
     * @return View
     */
    public function patientSelect(Request $request)
    {
        $change = $request->change ? true : false;
        $user = Auth::user();
        if (is_null($user)) {
            return redirect()->route('appointment.login');
        }
        $doctor_id = session()->get('patient.doctor_id');
        $doctor = Doctor::where('id', $doctor_id)->first();
        if (is_null($doctor)) {
            return redirect()->route('doctors');
        }

        $phone = session()->get('patient.Phone');
        //$phone = '9657494757'; //session()->get('patient.Phone');
        if (is_null($phone) || ($phone == '')) {
            return redirect()->route('appointment.logout');
        }
        foreach ($doctor->hospitals as $h) {
            $arrayfacilityGUID[] = $h->FacilityGUID;
        }

        $listUsers = new listUsers();

        //$arrayfacilityGUID = ['ce968cc1-9305-4933-a875-QA', 'a59a4397-8d03-464f-8b97-e1a3fcb4d215'];
        $resp = $listUsers->getUsers($phone, collect($arrayfacilityGUID)->filter()->unique()->values());
        $data = json_decode($resp, false);

        if ($data->success) {
            return view('pages.appointment-patient-select', compact('data', 'doctor', 'phone'));
        } else {
            if (session()->has('patient.FullName') && session()->has('patient.Gender') && session()->has('patient.DOB') && ($change == false)) {
                return redirect()->route('appointment.slot-select');
            } else {
                return redirect()->route('appointment.patients-detail');
            }
        }
    }

    /**
     * View page to select slots.
     *
     * @param Request $request Request data
     *
     * @return View
     */
    public function slotSelect(Request $request)
    {
        $user = Auth::user();

        if (is_null($user)) {
            return redirect()->route('appointment.login');
        }

        $doctor_id = session()->get('patient.doctor_id');
        $doctor = Doctor::query()
            ->with('mednetInformation.hospital')
            ->where('id', $doctor_id)
            ->first();

        if (is_null($doctor)) {
            return redirect()->route('doctors');
        }

        //Recheck if session corrupted
        if ((session()->has('patient.FullName'))
            && (session()->has('patient.Gender'))
            && (session()->has('patient.Phone'))
        ) {
            $hospitals = Hospital::all();

            return view('pages.appointment-slot-select', compact('user', 'doctor', 'hospitals'));
        } else {
            return redirect()->route('appointment.patient-select');
        }
    }

    /**
     * Get slots data from server through Ajax.
     *
     * @param Request $request Request data
     *
     * @return Json
     */
    public function getSlots(Request $request)
    {
        $today = 'No Slots Available';
        $tomorrow = 'No Slots Available';
        $future = [];
        if (request()->ajax()) {
            // $doctor = Doctor::find($request->doctorID);
            // $hospital = Hospital::find($request->facility);

            $doctor = Doctor::whereHas('mednetInformation', function ($query) {
                $query->where(['Hospital' => request()->facility, 'DoctorID' => request()->doctorID]);
            })->with('mednetInformation')->first();

            $hospital = Hospital::find(request()->facility);

            if (!$doctor) {
                return json_encode(
                    [
                        'today' => $today,
                        'tomorrow' => $tomorrow,
                        'future' => $future,
                    ]
                );
            }

            $doctorIDOfSelectedHospital = collect($doctor->mednetInformation)->where('Hospital', request()->facility)->pluck('DoctorID');

            // if (!$request->fromDate) {
            //     $fromDate = \Carbon\Carbon::today()->format('d-m-Y');
            // } else {
            //     $fromDate = $request->fromDate;
            // }

            $fromDate = $request->fromDate ?? \Carbon\Carbon::today()->format('d-m-Y');

            $noOfDays = config('sarvodaya.max_slot_calendar');
            $slots = new Slots();
            $response = $slots->fetchSlots($doctorIDOfSelectedHospital[0], $hospital->FacilityGUID, $fromDate, $noOfDays);
            $data = json_decode($response, false);

            if ($data->success == true) {
                foreach ($data->data as $as) {
                    if ($as->appointmentDate == $fromDate) { //if ($as->appointmentDate == Carbon::today()->format('d-m-Y')) {
                        if ($as->slotsList != []) {
                            $today = $this->getSlotHTML($as->slotsList, $as->appointmentDate);
                        }
                    } elseif ($as->appointmentDate == Carbon::now()->addDay()->format('d-m-Y')) {
                        if ($as->slotsList != []) {
                            $tomorrow = $this->getSlotHTML($as->slotsList, $as->appointmentDate);
                        }
                    } else {
                        if ($as->slotsList != []) {
                            $future[] = $as->appointmentDate;
                        }
                    }
                }
            }
        }

        return json_encode(
            [
                'today' => $today,
                'tomorrow' => $tomorrow,
                'future' => $future,
            ]
        );
    }

    /**
     * Book slots and payment gateway integration.
     *
     * @param Request $request Request data
     *
     * @return mixed
     */
    public function bookSlots(Request $request)
    {
        info($request->all());

        $user = Auth::user();
        if (is_null($user)) {
            return redirect()->route('appointment.login');
        }

        /* Validation */
        $request->validate(
            [
                'slots' => ['required', 'numeric'],
                'facility' => ['required', 'numeric'],
                'did' => ['required', 'numeric'],
                'PersonID' => ['required', 'numeric'],
                'price' => ['required', 'numeric'],
            ]
        );

        try {

            $doctor = Doctor::whereHas('mednetInformation', function ($query) {
                $query->where(['Hospital' => request()->facility, 'DoctorID' => request()->PersonID]);
            })->with('mednetInformation')->first();

            $discount = collect($doctor->mednetInformation)->where('Hospital', request()->facility)->first();
            $discountOnline = $discount->OnlineDiscount;
            $discountOffline = $discount->OfflineDiscount;


            //$discount = config('sarvodaya.online_discount');
            $amt = Crypt::decryptString($request->payment_data);
            $amount = ($request->payment_type == 'price_online') ?
                $amt - ($amt * $discountOnline / 100) : $amt - ($amt * $discountOffline / 100);
        } catch (DecryptException $exception) {
            return Redirect::back()->withErrors(
                ['message' => 'Pre Initiating failed. Please try again later.']
            );
        }

        // $facilityGUID = Hospital::find($request->facility)->FacilityGUID;
        $hospital = Hospital::find($request->facility);

        if (!$hospital->FacilityGUID) {
            return Redirect::back()->withErrors(
                ['message' => 'Hospital not found. Please try again later.']
            );
        }

        try {
            $trans_id = (int) (microtime(true) * 1000);

            $appointment = $this->saveAppointmentinDB($request, $trans_id, $amount);
            if ($appointment) {
                $order_id = 'SHBC' . str_pad($appointment->id, 6, '0', STR_PAD_LEFT);
            } else {
                return Redirect::back()->withErrors(
                    ['message' => 'Appointment Init failed. Please try again later.']
                );
            }
            $doctor = Doctor::find($request->did);
            if (!is_null($doctor->doctorPhoto)) {
                $doctorPhoto = $doctor->doctorPhoto->url;
            } elseif ($doctor->gender->Gender == 'Male') {
                $doctorPhoto = asset('img/default-doctor-male.jpg');
            } else {
                $doctorPhoto = asset('img/default-doctor-female.jpg');
            }

            $p_age = session()->get('patient.DOB');
            $today = Carbon::today();
            if (Carbon::parse($p_age)->lt($today)) {
                $patient_age = Carbon::parse($p_age)->diffForHumans(null, true);
            } else {
                $patient_age = '1 day';
            }

            session()->put('book.patient_age', $patient_age); //Carbon::parse($patient_age)->diffForHumans(null, true)
            session()->put('book.booking_date', $request->date);
            session()->put('book.booking_time', $request->time);
            session()->put('OrderID', $order_id);
            session()->put('book.doctor_name', $doctor->DoctorName);
            session()->put('book.doctor_department', $doctor->CurrentDesignation);
            session()->put('book.doctor_hospital', $hospital->HospitalName);
            session()->put('book.doctor_photo', $doctorPhoto);
            session()->put('patient.facilityGUID', $hospital->FacilityGUID);
            session()->put('book.slot', $request->slots);
            session()->put('book.hospital_help_line', $hospital->LandlineNumber);
            session()->put('book.patient_email', $request->Email);

            $paymentRedirectURL = route('appointment.thank-you-post'); //"https://www.sarvodayahospital.com/thank-you-for-your-appointment";

            if (($request->payment_type) == 'price_online') {
                $request->session()->put('patient.ccAvenue.mobile_number', session()->get('patient.Phone'));
                $request->session()->put('patient.ccAvenue.billing_name', session()->get('patient.FullName'));
                $request->session()->put('patient.ccAvenue.billing_tel', session()->get('patient.Phone'));
                $request->session()->put('patient.ccAvenue.billing_email', session()->get('patient.Email'));
                $request->session()->put('patient.ccAvenue.billing_country', 'India');
                $request->session()->put('patient.ccAvenue.language', 'EN');
                $request->session()->put('patient.ccAvenue.cancel_url', $paymentRedirectURL);
                $request->session()->put('patient.ccAvenue.redirect_url', $paymentRedirectURL);
                $request->session()->put('patient.ccAvenue.currency', 'INR');
                $request->session()->put('patient.ccAvenue.amount', $amount);
                $request->session()->put('patient.ccAvenue.order_id', $order_id);
                $request->session()->put('patient.ccAvenue.tid', $trans_id);
                $request->session()->put('patient.ccAvenue.merchant_id', config('sarvodaya.ccAvenueMerchantId'));

                $turl = URL::temporarySignedRoute(
                    'ccavenue.html',
                    now()->addMinutes(1),
                    ['patient' => $user->id]
                );

                return redirect()->away($turl);
            } else {
                $booking = $this->populateBookingData();
                $res = $this->bookMySlot($booking, $hospital->FacilityGUID, $hospital->HospitalShortName);

                if ($res) {

                    # Call Billing API (Now Useless)
                    $billingData = [
                        "companyName" => $hospital->MednetCompanyName,
                        "mrn" => $booking->mrn ?? "",
                        "departmentName" => "MEDICAL ONCOLOGY AND HAEMATOLOGY", //$doctor->CurrentDesignation ?? "",
                        "doctorRegistrationNumber" => "DMC - 18813", //$doctor->RegNumber ?? "",
                        "paymentMode" => "CASH",
                        "paymentTxnNo" => "",
                        "paymentBankName" => "",
                        "paymentModeSrcRefType" => "",
                        "orderTokenNumber" => "",
                        "totalAmount" => $amount,
                        "billAmount" => $amount,
                        "prefix" => $booking->prefix ?? "Mr.",
                        "name" => $booking->patientName,
                        "gender" => $booking->gender ?? "",
                        "dateOfBirth" => $booking->dob ?? "",
                        "mobileNumber" => $booking->mobilePhone ?? "",
                        "aadharID" => "",
                        "country" => $booking->country ?? "India",
                        "state" => $booking->state ?? "",
                        "city" => $booking->city ?? "",
                        "pincode" => $booking->pincode ?? "",
                        "street1" => $booking->address ?? "",
                        "appointmentDate" => $request->date,
                        "appointmentimeOnly" => $request->time,
                        "registrationDate" => Carbon::now()->format('d-m-Y'), //"21-07-2023",
                        "registrationDateTiming" => Carbon::now()->format('h:m A'), //"06:15 PM",
                        "serviceList" => [
                            [
                                "serviceName" => "CONSULTATION FEES",
                                "rate" => $amount,
                                "renderByRegistrationNumber" => "DMC - 18813", //$doctor->RegNumber ?? "",
                                "amount" => $amount
                            ]
                        ]
                    ];

                    $appointment->OrderID = $order_id;
                    $appointment->published_at = Carbon::now();
                    $appointment->save();

                    return redirect()->route('appointment.thank-you');
                } else {
                    return Redirect::back()->withErrors(
                        ['message' => 'Slot booking error. Please try other slot.']
                    );
                }
            }
        } catch (ErrorException $exception) {
            return Redirect::back()->withErrors(
                ['message' => 'Booking Initiating failed. Please try again later.']
            );
        }
    }

    public function thankYou(Request $request)
    {
        if (session()->get('OrderID')) {
            // $bookingId = (int) explode('SHBC', session()->get('OrderID'))[1];
            // $appointment = Appointment::find($bookingId);
            //check booking date yy-mm-dd
            $order_status = 'hospital';
            $book = [
                'patient_mrn' => session()->get('patient.mrn'),
                'patient_name' => session()->get('patient.FullName'),
                'patient_age' => session()->get('book.patient_age'),
                'patient_gender' => session()->get('patient.Gender'),
                'patient_mobile' => session()->get('patient.Phone'),
                'booking_date' => session()->get('book.booking_date'),
                'booking_time' => session()->get('book.booking_time'),
                'OrderID' => session()->get('OrderID'),
                'doctor_name' => session()->get('book.doctor_name'),
                'doctor_department' => session()->get('book.doctor_department'),
                'doctor_hospital' => session()->get('book.doctor_hospital'),
                'doctor_photo' => session()->get('book.doctor_photo'),
                'appointment_id' => session()->get('book.slot'),
            ];
            $user = Auth::user();

            if (session()->has('book.patient_email')) {
                $this->ccmail(
                    session()->get('OrderID'),
                    session()->get('book.booking_date'),
                    session()->get('book.booking_time'),
                    session()->get('book.doctor_name'),
                    session()->get('book.doctor_hospital'),
                    session()->get('book.patient_email'),
                    session()->get('book.hospital_help_line')
                );
            } else {
                if ($user->Email) {
                    $this->ccmail(
                        session()->get('OrderID'),
                        session()->get('book.booking_date'),
                        session()->get('book.booking_time'),
                        session()->get('book.doctor_name'),
                        session()->get('book.doctor_hospital'),
                        $user->Email,
                        session()->get('book.hospital_help_line')
                    );
                }
            }
            $sms = new Sms();
            $status = $sms->sendConfirmation(
                session()->get('book.patient_mobile'),
                session()->get('book.patient_name'),
                session()->get('book.doctor_name'),
                session()->get('book.booking_date') . ' ' . session()->get('book.booking_time'),
                session()->get('book.doctor_hospital'),
                session()->get('OrderID'),
                session()->get('book.hospital_help_line')
            );
            //$this->destroyInSession();
            if (($order_status == 'hospital') || ($order_status == "Success")) {
                return view('pages.appointment-thanks', compact('order_status', 'book'));
            } else {
                return redirect()->route('appointment.payment-failed');
            }
        } else {
            return redirect()->route('doctors');
        }
    }

    public function thankYouCC(Request $request)
    {
        $order_status = '';
        $encResponse = $request->encResp;
        $data = [];
        $this->destroyInSession();
        if ($encResponse) {
            $ccACrypto = new ccAvenueCrypto();
            $workingKey = config('sarvodaya.ccAvenueWorkingKey');
            $rcvdString = $ccACrypto->decrypt($encResponse, $workingKey);
            $order_status = '';
            $decryptValues = explode('&', $rcvdString);
            $dataSize = sizeof($decryptValues);

            for ($i = 0; $i < $dataSize; ++$i) {
                $information = explode('=', $decryptValues[$i]);
                $data[$information[0]] = urldecode($information[1]);
                if ($i == 3) {
                    $order_status = $information[1];
                }
            }
            $order_id = $data['order_id'];
            $bookingId = (int) explode('SHBC', $order_id)[1];

            //UPDATE APPOINTMENT TABLE
            $appointment = Appointment::where('id', $bookingId)->update(
                [
                    'TrackingID' => $data['tracking_id'],
                    'TransactionStatus' => $order_status,
                    'TransactionData' => json_encode($decryptValues),
                    'OrderID' => $order_id,
                ]
            );

            if ($order_status == 'Success') {
                $appointment = Appointment::find($bookingId);
                $user = Patient::find($appointment->patient);
                $hospital = Hospital::find($appointment->hospital);
                $doctor = Doctor::find($appointment->doctor);

                $mednetDoctor = Doctor::whereHas('mednetInformation', function ($query) use($appointment) {
                    $query->where(['Hospital' => $appointment->hospital, 'DoctorID' => $appointment->PersonID]);
                })->with('mednetInformation', function ($query) use($appointment) {
                    $query->where(['Hospital' => $appointment->hospital, 'DoctorID' => $appointment->PersonID]);
                })->first();

                if (!is_null($doctor->doctorPhoto)) {
                    $doctorPhoto = $doctor->doctorPhoto->url;
                } elseif ($doctor->gender->Gender == 'Male') {
                    $doctorPhoto = asset('img/default-doctor-male.jpg');
                } else {
                    $doctorPhoto = asset('img/default-doctor-female.jpg');
                }

                //Populate Booking data
                $booking = $this->populateBookingDataCC(
                    $appointment->BookingDate,
                    $appointment->BookingTime,
                    $appointment->slots,
                    $appointment->patient_mobile,
                    $appointment->patient_name,
                    $appointment->patient_mrn,
                    $appointment->patient_gender,
                    $appointment->patient_dob
                );

                /*//to check for injection in between the transaction hacking attempt
                if ($appointment->Price!=$data['amount']){
                    $order_status = 'NotBooked';
                    return view('pages.appointment-thanks', compact('order_status', 'data'));
                }*/

                $res = $this->bookMySlot($booking, $hospital->FacilityGUID, $hospital->HospitalShortName);
                if ($res) {
                    //update Appointment table once again
                    $appointment->published_at = Carbon::now();
                    $appointment->save();
                    $today = Carbon::today();
                    if (Carbon::parse($appointment->patient_dob)->lt($today)) {
                        $patient_age = Carbon::parse($appointment->patient_dob)->diffForHumans(null, true);
                    } else {
                        $patient_age = '1 day';
                    }

                    $book = [
                        'patient_name' => $appointment->patient_name,
                        'patient_age' => $patient_age,
                        'patient_gender' => $appointment->patient_gender,
                        'patient_mobile' => $appointment->patient_mobile,
                        'booking_date' => $appointment->BookingDate,
                        'booking_time' => $appointment->BookingTime,
                        'OrderID' => $order_id,
                        'doctor_name' => $doctor->DoctorName,
                        'doctor_department' => $doctor->CurrentDesignation,
                        'doctor_hospital' => $hospital->HospitalName,
                        'doctor_photo' => $doctorPhoto,
                        'appointment_id' => $appointment->slots,
                    ];
                    if ($user->Email) {
                        $this->ccmail(
                            $order_id,
                            $appointment->BookingDate,
                            $appointment->BookingTime,
                            $doctor->DoctorName,
                            $hospital->HospitalName,
                            $user->Email,
                            $hospital->LandlineNumber
                        );
                    }
                    $sms = new Sms();
                    $status = $sms->sendConfirmation(
                        $appointment->patient_mobile,
                        $appointment->patient_name,
                        $doctor->DoctorName,
                        $appointment->BookingDate . ' ' . $appointment->BookingTime,
                        $hospital->HospitalName,
                        $order_id,
                        $hospital->LandlineNumber
                    );

                    # Call Billing API
                    if($hospital->id == 1) {
                        info('Only Sector 8 ka billing generate hoga');
                        $billingData = [
                            "companyName" => $hospital->MednetCompanyName,
                            "mrn" => $booking->mrn ?? "",
                            "departmentName" => $mednetDoctor->mednetInformation[0]->DepartmentName ?? "", //"PULMONOLOGY", //$doctor->CurrentDesignation ?? "",
                            "doctorRegistrationNumber" => $doctor->RegNumber ?? "", //"DMC - 18813", //$doctor->RegNumber ?? "",
                            "paymentMode" => "ONLINE",
                            "paymentTxnNo" => $data['tracking_id'],
                            "paymentBankName" => "",
                            "paymentModeSrcRefType" => "",
                            "orderTokenNumber" => $order_id,
                            "totalAmount" => (int)$appointment->Price,
                            "billAmount" => (int)$appointment->Price,
                            "prefix" => "Mr.",
                            "name" => $appointment->patient_name,
                            "gender" => $appointment->patient_gender == 1 ? "Male" : ( $appointment->patient_gender == 2 ? "Female" : "Other" ),
                            "dateOfBirth" => $appointment->patient_dob ?? "",
                            "mobileNumber" => $appointment->patient_mobile ?? "",
                            "aadharID" => "",
                            "country" => $appointment->CountryName ?? "",
                            "state" => $appointment->StateName ?? "",
                            "city" => $appointment->CityName ?? "",
                            "pincode" => $appointment->Pincode ?? "",
                            "street1" => $appointment->StreetAddress ?? "",
                            "appointmentDate" => Carbon::parse($appointment->BookingDate)->format('d-m-Y'),
                            "appointmentimeOnly" => $appointment->BookingTime,
                            "registrationDate" => Carbon::now()->format('d-m-Y'), //"21-07-2023",
                            "registrationDateTiming" => Carbon::now()->format('h:m A'), //"06:15 PM",
                            "serviceList" => [
                                [
                                    "serviceName" => "CONSULTATION FEES",
                                    "rate" => (int)$appointment->Price,
                                    "renderByRegistrationNumber" => $doctor->RegNumber ?? "", //"DMC - 18813"
                                    "amount" => (int)$appointment->Price
                                ]
                            ]
                        ];

                        $bilingURL = "http://mednet.sarvodayahospital.com:4040/mednet/ws/patientBillingWS/createPatientBill";
                        $billingresponse = Http::post($bilingURL, $billingData)->json();

                        info('------ ONLINE APOINTMENT BOOKING -----');
                        info($billingresponse);
                        info($billingData);
                        info('------ END ONLINE APOINTMENT BOOKING -----');

                        if(is_null($billingresponse)) {
                            info("Bill not generate");
                        }

                        // Update bill number if propery has bill number
                        $appointment->billNumber = (!is_null($billingresponse) && array_key_exists('billNumber', $billingresponse)) ? $billingresponse['billNumber'] : "Bill not generate";
                        $appointment->save();
                    }

                    return view('pages.appointment-thanks', compact('order_status', 'book'));
                } else {
                    $order_status = 'NotBooked';
                }
            }
        }
        if (($order_status == 'hospital') || ($order_status == "Success")) {
            return view('pages.appointment-thanks', compact('order_status', 'book'));
        } else {
            return redirect()->route('appointment.payment-failed');
        }
        //return view('pages.appointment-thanks', compact('order_status', 'data'));
    }

    public function paymentFailed()
    {
        return view('pages.payment-cancelled');
    }

    /**
     * Select doctor if not login then goto login page else
     * goto patient select page.
     *
     * @param Request $request request variable
     *
     * @return View view view pages
     */
    public function doctorSelect(Request $request)
    {
        if (!$request->doctor_id) {
            return Redirect::back()->withErrors(
                ['message' => 'No doctor selected']
            );
        }

        $doctor = Doctor::find($request->doctor_id);

        session()->put('patient.doctor_id', $request->doctor_id);
        session()->put('patient.doctor_reg_no', $doctor->RegNumber);

        $user = Auth::user();

        if (is_null($user)) {
            return redirect()->route('appointment.login');
        } else {
            session()->forget('patient.facilityGUID');
            //session()->forget('patient.FullName');
            //session()->forget('patient.Gender');
            //session()->forget('patient.DOB');
            return redirect()->route('appointment.patient-select');
        }
    }

    /**
     * getSlotHTML generates the HTML slots.
     *
     * @param object $timeSlotList    Slot object
     * @param Date   $appointmentDate Date format dd-mm-yyyy
     *
     * @return HTML
     */
    public function getSlotHTML($timeSlotList, $appointmentDate)
    {
        $html = '';
        foreach ($timeSlotList as $sl) {
            foreach ($sl->timeSlotList as $sl) {
                if ($sl->status == 'OPEN') {
                    $mdate = $appointmentDate . ' ' . $sl->appointmentTime;
                    $newdate = Carbon::parse($mdate);
                    $currentDateTime = Carbon::now();
                    if ($newdate->gt($currentDateTime)) {
                        $html .=
                            '<div class="col-md-3 col-6 mb-3">
                            <div class="button">
                                <input type="radio" class="slot-lists" id="a' . $sl->appointmentID . '" name="slots" value="' . $sl->appointmentID . '" data-slot-date="' . $appointmentDate . '" data-slot-time="' . $sl->appointmentTime . '" />
                                <label class="btn btn-default slot-lists-label" for="a' . $sl->appointmentID . '">' . $sl->appointmentTime . '</label>
                            </div>
                        </div>';
                    }
                }
            }
        }

        return $html;
    }

    /**
     * Logout section.
     *
     * @return null
     */
    public function logout()
    {
        $this->destroyInSession();
        session()->forget('patient.Phone');
        session()->forget('patient.doctor_id');
        Session::flush();
        Auth::logout();

        return redirect()->route('appointment.login');
    }

    /**
     * Relogin section.
     *
     * @return null
     */
    public function relogin()
    {
        $doc = session()->get('patient.doctor_id');
        $this->destroyInSession();
        session()->forget('patient.Phone');
        session()->forget('patient.doctor_id');
        Session::flush();
        Auth::logout();
        session()->put('patient.doctor_id', $doc);
        return redirect()->route('appointment.login');
    }

    /**
     * Generate OTP and send to specified mobile number.
     *
     * @param Request $request Request variables
     *
     * @return Response
     */
    public function resendOtp(Request $request)
    {
        /* Generate An OTP */
        $sms = new Sms();

        $now = Carbon::now();
        $sphone = session()->get('patient.Phone');
        $otp = rand(1000, 9999);

        //$otp_expire_at = $request->session()->get('patient.otp_expire_at');
        $otp_expire_at = session()->get('patient.otp_expire_at');

        if ($now->gt($otp_expire_at)) {
            $addSeconds = config('sarvodaya.sms_resend_interval');
            session()->put('patient.otp_expire_at', carbon::now()->addSecond($addSeconds));
            session()->put('patient.otp', $otp);
            $status = $sms->sendOTP($otp, $request->Phone);
            if ($status) {
                return response()->json(['message' => 'Successfully sent OTP.'], 200);
            } else {
                return response()->json(['Sent OTP failed.'], 401);
            }
        } else {
            return response()->json(['OTP couldnot be sent before time'], 401);
        }
    }

    /**
     * Get future slots data by date from server through Ajax.
     *
     * @param Request $request Request data
     *
     * @return Json
     */
    public function getDoctorFutureSlots(Request $request)
    {
        $today = 'No Slots Available';
        if (request()->ajax()) {
            $doctor = Doctor::whereHas('mednetInformation', function ($query) {
                $query->where(['Hospital' => request()->facility, 'DoctorID' => request()->doctorID]);
            })->with('mednetInformation')->first();
            //$doctor = Doctor::find($request->doctorID);
            $hospital = Hospital::find($request->facility);

            if (!$doctor || !$hospital || (!$request->fromDate)) {
                return json_encode(['No Slots Available']);
            }

            $noOfDays = 1; //config('sarvodaya.max_slot_calendar')
            $slots = new Slots();

            $doctorIDOfSelectedHospital = collect($doctor->mednetInformation)->where('Hospital', request()->facility)->pluck('DoctorID');

            $response = $slots->fetchSlots($doctorIDOfSelectedHospital[0], $hospital->FacilityGUID, $request->fromDate, $noOfDays);
            $data = json_decode($response, false);

            if ($data->success == true) {
                foreach ($data->data as $as) {
                    if ($as->slotsList != []) {
                        $today = $this->getSlotHTML($as->slotsList, $as->appointmentDate);
                    }
                }
            }
        }

        return json_encode([$today]);
    }

    /**
     * Cancel Booking.
     *
     * @return redirect request
     */
    public function cancelBooking(Request $request)
    {
        //cancel booking
        $appointment_api = new AppointmentBook();
        $response = $appointment_api->cancelBooking($request->appointmentID, $request->facilityGUID, $request->hospital, $request->cancellationNote);

        return $response;
    }

    /**
     * Save in Session.
     *
     * @param string patient_uid
     * patient_name
     */
    public function saveInSession($patient_email, $patient_id, $patient_uid, $patient_name, $patient_age, $patient_gender, $patient_mobile, $booking_date, $booking_time, $order_id, $doctor_name, $doctor_department, $doctorPhoto, $doctor_hospital, $facilityGUID, $booking_slot, $help_line = '')
    {
        session()->put('book.patient_email', $patient_email);
        session()->put('patient.id', $patient_id);
        session()->put('book.patient_uid', $patient_uid);
        session()->put('book.patient_name', $patient_name);
        session()->put('book.patient_age', $patient_age);
        session()->put('book.patient_gender', $patient_gender);
        session()->put('book.patient_mobile', $patient_mobile);
        session()->put('book.booking_date', $booking_date);
        session()->put('book.booking_time', $booking_time);
        session()->put('OrderID', $order_id);
        session()->put('book.doctor_name', $doctor_name);
        session()->put('book.doctor_department', $doctor_department);
        session()->put('book.doctor_hospital', $doctor_hospital);
        session()->put('book.doctor_photo', $doctorPhoto);
        session()->put('patient.facilityGUID', $facilityGUID);
        session()->put('book.slot', $booking_slot);
        session()->put('book.hospital_help_line', $help_line);
    }

    /**
     * Destroy all patient session parameter except user auth.
     *
     * @return null
     */
    public function destroyInSession()
    {
        //session()->forget('patient.doctor_id');
        session()->forget('patient.otp');
        session()->forget('patient.otp_expire_at');
        session()->forget('patient.otp_verified');
        session()->forget('patient.price_online');
        session()->forget('patient.price_hospital');
        //session()->forget('patient.Phone');
        session()->forget('patient.facilityGUID');
        session()->forget('patient.FullName');
        //session()->forget('patient.Email');
        //session()->forget('patient.Gender');
        //session()->forget('patient.DOB');
        session()->forget('patient.mrn');

        session()->forget('book.patient_email');
        session()->forget('book.patient_uid');
        session()->forget('book.patient_name');
        session()->forget('book.patient_age');
        session()->forget('book.patient_gender');
        session()->forget('book.patient_mobile');
        session()->forget('book.booking_date');
        session()->forget('book.booking_time');
        session()->forget('OrderID');
        session()->forget('book.doctor_name');
        session()->forget('book.doctor_department');
        session()->forget('book.doctor_hospital');
        session()->forget('book.doctor_photo');
        session()->forget('book.slot');
        session()->forget('book.hospital_help_line');

        session()->forget('patient.ccAvenue.mobile_number');
        session()->forget('patient.ccAvenue.billing_name');
        session()->forget('patient.ccAvenue.billing_tel');
        session()->forget('patient.ccAvenue.billing_email');
        session()->forget('patient.ccAvenue.billing_country');
        session()->forget('patient.ccAvenue.language');
        session()->forget('patient.ccAvenue.cancel_url');
        session()->forget('patient.ccAvenue.redirect_url');
        session()->forget('patient.ccAvenue.currency');
        session()->forget('patient.ccAvenue.amount');
        session()->forget('patient.ccAvenue.order_id');
        session()->forget('patient.ccAvenue.tid');
        session()->forget('patient.ccAvenue.merchant_id');
    }

    /**
     * Book slot through API.
     *
     * As per the API 'checkAppointmentExists' should be 'true', if we would like to
     * check whether future appointment exist. We may bypass it by providing false
     * ex: $booking->checkAppointmentExists = true.
     *
     * @return BookingData
     */
    public function populateBookingData()
    {
        $booking_date = session()->get('book.booking_date');
        $booking_date = Carbon::createFromFormat('d-m-Y', $booking_date)->format('Y-m-d');
        $booking = new BookingData();
        $booking->appointmentDate = $booking_date;
        $booking->appointmentID = session()->get('book.slot');
        $booking->appointmentType = session()->get('patient.mrn') == '' ? 'NEW PATIENT' : 'EXISTING PATIENT'; //?new patient
        $booking->dob = session()->get('patient.DOB');
        $booking->gender = (session()->get('patient.Gender') == 1) ? 'M' : 'F';
        $booking->mrn = session()->get('patient.mrn');
        $booking->mobilePhone = session()->get('patient.Phone');
        $booking->reasonForAppt = 'NA';
        $booking->loginID = '';
        $booking->patientName = session()->get('patient.FullName');
        $booking->prefix = session()->get('patient.prefix');
        $booking->slotTime = session()->get('book.booking_time');
        $booking->checkAppointmentExists = false;
        $booking->address = session()->get('patient.address');
        $booking->country = session()->get('patient.countryName');
        $booking->state = session()->get('patient.stateName');
        $booking->city = session()->get('patient.cityName');
        $booking->region = '';
        $booking->pincode = session()->get('patient.pin');
        $booking->consultationType = 'InPersonAppt'; //now video consultation is not there
        $booking->countryCode = '91';

        return $booking;
    }

    /**
     * Book slot through API.
     *
     * As per the API 'checkAppointmentExists' should be 'true', if we would like to
     * check whether future appointment exist. We may bypass it by providing false
     * ex: $booking->checkAppointmentExists = true.
     *
     * @return BookingData
     */
    public function populateBookingDataCC($booking_date, $booking_time, $book_slot, $patient_phone, $patient_name, $patient_mrn, $patient_gender, $patient_dob)
    {
        $booking = new BookingData();
        $booking->appointmentDate = $booking_date;
        $booking->appointmentID = $book_slot;
        $booking->appointmentType = ($patient_mrn == '') ? 'NEW PATIENT' : 'EXISTING PATIENT'; //?new patient
        $booking->dob = $patient_dob;
        $booking->gender = ($patient_gender == 1) ? 'M' : 'F';
        $booking->mrn = $patient_mrn;
        $booking->mobilePhone = $patient_phone;
        $booking->reasonForAppt = 'NA';
        $booking->loginID = '';
        $booking->patientName = $patient_name;
        $booking->prefix = ($patient_gender == 1) ? 'MR.' : 'MS.';
        $booking->slotTime = $booking_time;
        $booking->checkAppointmentExists = false;
        $booking->address = '';
        $booking->country = 'India';
        $booking->state = '';
        $booking->city = '';
        $booking->region = '';
        $booking->pincode = '';
        $booking->consultationType = 'InPersonAppt'; //now video consultation is not there
        $booking->countryCode = '91';

        return $booking;
    }

    /**
     * Save appointment in DB.
     *
     * @param Request $request  Request data
     * @param int     $trans_id transaction amount
     * @param int     $amount   price
     *
     * @return Appointment
     */
    public function saveAppointmentinDB(Request $request, $trans_id, $amount)
    {
        $user = Auth::user();
        $appointment = Appointment::create(
            [
                'patient' => $user->id,
                'patient_name' => session()->get('patient.FullName'),
                'patient_mobile' => session()->get('patient.Phone'),
                'patient_dob' => session()->get('patient.DOB'),
                'patient_mrn' => session()->get('patient.mrn'),
                'patient_gender' => session()->get('patient.Gender'),
                'doctor' => $request->did,
                'slots' => $request->slots,
                'hospital' => $request->facility,
                'Price' => $amount,
                'PayAtHospital' => ($request->payment_type == 'price_online') ? 0 : 1,
                'PersonID' => $request->PersonID,
                'BookingDate' => Carbon::createFromFormat('d-m-Y', $request->date)->format('Y-m-d'),
                'BookingTime' => $request->time,
                'TrackingID' => $trans_id,
                //'published_at' => Carbon::now(),
                'TransactionStatus' => 'NA',
                'Patient_data' => json_encode(session('patient')),
                'CountryName' => session()->get('patient.countryName'),
                'StateName' => session()->get('patient.stateName'),
                'CityName' => session()->get('patient.cityName'),
                'Pincode' => session()->get('patient.pin'),
                'StreetAddress' => session()->get('patient.address'),
            ]
        );

        return $appointment;
    }

    /**
     * Provide wrapper for ccAvenue.
     *
     * @param Request $request Request method
     *
     * @return View
     */
    public function ccAvenueHtml(Request $request)
    {
        if (!$request->hasValidSignature()) {
            abort(401);
        }

        return view('pages.cc', compact('request'));
    }

    public function ccmail($book_id, $book_date, $book_time, $doctor_name, $hospital_name, $user_email, $hospital_helpline)
    {
        $user = Auth::user();

        info('Auth User CC Mail Method');
        info(collect($user)->toArray());

        $objMail = new \stdClass();
        $objMail->appointment_id = $book_id;
        $objMail->appointment_date = $book_date;
        $objMail->appointment_time = $book_time;
        $objMail->doctor_name = $doctor_name;
        $objMail->hospital = $hospital_name;
        $objMail->sender = config('mail.from.name');
        $objMail->receiver = $user_email;
        $objMail->hospital_helpline = $hospital_helpline;
        Mail::to($user_email)->send(new AppointmentConfirm($objMail));
    }

    /**
     * Actual Booking goes here.
     *
     * @param BookingData $booking      Booking variables
     * @param int         $facilityGUID Facility GUID
     *
     * @return string
     */
    public function bookMySlot(BookingData $booking, $facilityGUID, $hospital_name)
    {
        $appointment_api = new AppointmentBook();
        $response = $appointment_api->bookAppointment($booking, $facilityGUID, $hospital_name);

        $responseJson = json_decode($response, false);
        info(collect($responseJson)->toArray());

        if (!$responseJson) {
            return false;
        }

        if (($responseJson->success == true) && (json_decode($responseJson->data)->status == 'APPOINTMENT BOOKED')) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Get future slots data by date from server through Ajax.
     *
     * @param Request $request Request data
     *
     * @return Json
     */
    public function getDoctorSlotAvailability(Request $request)
    {
        $fromDate = !$request->fromDate ? Carbon::today()->format('d-m-Y') : $request->fromDate;
        if (request()->ajax()) {
            $doctor = Doctor::whereHas('mednetInformation', function ($query) {
                $query->where(['Hospital' => request()->facility, 'DoctorID' => request()->doctorID]);
            })->with('mednetInformation')->first();

            $doctorIDOfSelectedHospital = collect($doctor->mednetInformation)->where('Hospital', request()->facility)->pluck('DoctorID');
            $isBookingActive = collect($doctor->mednetInformation)->where('Hospital', request()->facility)->pluck('BookingEnabled');

            $hospital = Hospital::find($request->facility);

            if (!$doctor || !$hospital) {
                return json_encode(['offline' => true, 'help_line' => $hospital->LandlineNumber]);
            }

            if (!$isBookingActive[0]) {
                return json_encode(['offline' => true, 'help_line' => $hospital->LandlineNumber]);
            }

            $noOfDays = config('sarvodaya.max_slot_calendar');
            $slots = new Slots();

            $appointmentId = '';

            $response = $slots->fetchSlots($doctorIDOfSelectedHospital[0], $hospital->FacilityGUID, $fromDate, $noOfDays);
            $data = json_decode($response, false);

            if ($data->success == true) {
                foreach ($data->data as $as) {
                    if ($as->slotsList != []) {
                        foreach ($as->slotsList as $sl) {
                            foreach ($sl->timeSlotList as $slist) {
                                if (($slist->status == 'OPEN') && ($appointmentId == '')) {
                                    $mdate = $as->appointmentDate . ' ' . $slist->appointmentTime;
                                    $newdate = date_create_from_format('d-m-Y H:i A', $mdate);
                                    if ($newdate > now()) {
                                        return json_encode(
                                            [
                                                'offline' => false,
                                                'appointmentDate' => $as->appointmentDate,
                                                'appointmentTime' => $slist->appointmentTime,
                                                'appointmentId' => $slist->appointmentID,
                                                'mdate' => date_create_from_format('d-m-Y H:i A', $mdate),
                                            ]
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return json_encode(['offline' => true, 'help_line' => $hospital->LandlineNumber]);
    }

    public function gotoSlot(Request $request)
    {
        session()->put('patient.FullName', $request->dataName);
        session()->put('patient.Gender', $request->dataGender);
        if ($request->dataFormattedDOB) {
            session()->put('patient.DOB', Carbon::createFromFormat('d-m-Y', $request->dataFormattedDOB)->format('Y-m-d'));
        } else {
            session()->put('patient.DOB', '');
        }
        session()->put('patient.mrn', $request->dataMrn);
        $turl = route('appointment.slot-select');
        echo json_encode(['url' => $turl]);
    }

    public function getthankyou(Request $request)
    {
        $order_status = '';

        return view('pages.appointment-thanks', compact('order_status'));
    }

    public function postthankyou(Request $request)
    {
        $orderid = $request->orderid;
        $appointment = null;
        if ($orderid) {
            if (explode('SHBC', $orderid)) {
                $appointment = explode('SHBC', $orderid)[1];
            }
        }
        //$appointment = explode('SHBC', $orderid) ? (int) explode('SHBC', $orderid)[1] : null;

        $fd = Feedback::create([
            'PatientName' => $request->PatientName,
            'PatientMobile' => $request->PatientMobile,
            'Rating' => $request->Rating,
            'Feedback' => $request->Feedback,
            'appointment' => $appointment,
            'published_at' => Carbon::now(),
        ]);
        if (!$fd->id) {
            echo json_encode(['ok' => 'error']);
        } else {
            echo json_encode(['ok' => 'success']);
        }
    }

    public function listState(Request $request)
    {
        $sid = (int)$request->countryID;

        try {
            $url = 'https://live.mednetlabs.com/mxServer/ws/onlineDoctorsAppointment/listStates/' . $sid;
            $response = Http::get($url);
            $data = json_decode($response, false);

            if ($data) {
                return response()->json(['data' => $data->data], 200);
            } else {
                return response()->json(['error fetching data'], 401);
            }

        } catch (ConnectionException $exception) {
            return json_encode($exception);
        }
    }

    public function listCities(Request $request)
    {
        $sid = (int)$request->stateID;

        try {
            $url = 'https://live.mednetlabs.com/mxServer/ws/onlineDoctorsAppointment/listCity/' . $sid;
            $response = Http::get($url);
            $data = json_decode($response, false);

            if ($data) {
                return response()->json(['data' => $data->data], 200);
            } else {
                return response()->json(['error fetching data'], 401);
            }

        } catch (ConnectionException $exception) {
            return json_encode($exception);
        }
    }
}