<?php

namespace App\Http\Controllers\Agent;

use App\Classes\Constant;
use App\Events\DeviceCurrentStatus;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Cart;
use App\Models\Doctor;
use App\Models\DoctorAppointment;
use App\Models\Item;
use App\Models\ItemHistory;
use App\Models\Lab;
use App\Models\LabKit;
use App\Models\LicenseNumberModel;
use App\Models\Patient;
use App\Models\PatientAnswer;
use App\Models\PatientLab;
use App\Models\PatientNote;
use App\Models\PatientPrescription;
use App\Models\PatientTask;
use App\Models\Prescription;
use App\Models\Question;
use App\Models\QuestionBuilder;
use App\Models\QuestionGroup;
use App\Models\Telemedpro;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\File;
use App\Models\Setting;
use Illuminate\Support\Facades\Storage;
use Laravel\Prompts\Note;

class AppointmentController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $data = [];
        $appointments = Appointment::where('telemed_pros_id', $user->id)->get();
        foreach ($appointments as $appointment) {
            $patient = Patient::where('id', $appointment->patient_id)->first();
            array_push($data, [
                'id' => $appointment->id,
                'patient_name' => $patient->first_name . " " . $patient->last_name,
                'patient_id' => $appointment->patient_id,
                'telemed_pros_id ' => $appointment->telemed_pros_id,
                'appointment_time' => $appointment->appointment_time,
                'meeting_id' => $appointment->meeting_id,
                'created_at' => $appointment->created_at,
                'updated_at' => $appointment->updated_at,
                'in_call' => $appointment->in_call
            ]);
        }
        // dd($data);
        return  view('agent.appointments.index', ['appointments' => $data]);
    }

    public function profile(Request $request)
    {
        $user = Auth::user();
        return response()->json(['profile' => $user], 200);
    }
    public function profileImageUpload(Patient $patient, Request $request)
    {
        $user = $patient;
        $image = $request->get('image');
        $fileName = 'profile-' . time();

        $logo = base64_decode($image);
        $ext = (explode('/', finfo_buffer(finfo_open(), $logo, FILEINFO_MIME_TYPE))[1]);

        $imageName =  $fileName . '.' . $ext;
        Storage::disk('local')->put("public/profile_pictures/" . $imageName, $logo);
        $user->profile_picture = $imageName;
        $user->save();
        return response()->json(['profile' => $user], 200);
    }

    public function delete($id, Request $request)
    {
        Appointment::where('id', $id)->delete();
        $request->session()->flash('message', 'Appointment deleted successfully');
        return redirect()->back();
    }

    public function patientDetails($id)
    {
        $appointment = Appointment::where('id', $id)->first();
        $patient = Patient::where('id', $appointment->patient_id)->first();
        return  view('agent.appointments.patient-details', ['patient' => $patient, 'appointment_id' => $appointment->id]);
    }
    public function patientProfileDetails(Patient $patient)
    {
        return response()->json(['patient' => $patient], 200);
    }


    public function patientAddress($id)
    {
        $patient = Patient::where('id', $id)->first();
        return  view('agent.appointments.patient-address', ['patient' => $patient]);
    }

    public function savePatientAddress($id, Request $request)
    {
        $appointment = Appointment::where('id', $id)->first();
        $patient = Patient::where('id', $appointment->patient_id)->first();

        $address = $request->input('address');
        $city = $request->input('city');
        $state = $request->input('state');
        $zip_code = $request->input('zip_code');

        $patient->address = $address;
        $patient->city = $city;
        $patient->state = $state;
        $patient->zip_code = $zip_code;
        $patient->save();

        $request->session()->flash('message', 'Address saved successfully');


        return  view('agent.appointments.patient-details', ['patient' => $patient, 'appointment_id' => $appointment->id]);
    }

    public function patientLabs($id)
    {
        $patient = Patient::where('id', $id)->first();
        $labs = Lab::where('city', 'like', '%' . $patient->city . '%')
            ->orWhere('state', 'like', '%' . $patient->state . '%')
            ->orWhere('zip_code', 'like', '%' . $patient->zip_code . '%')
            ->get();
        return  view('agent.appointments.patient-labs', ['patient' => $patient, 'labs' => $labs]);
    }

    public function patientBookLab(Appointment $appointment, Request $request)
    {

        $lab = new Lab();
        $lab->address = $request->input('lab_address');
        $lab->name = $request->input('lab_name');
        $lab->city = $request->input('lab_city');
        $lab->state = $request->input('lab_state');
        $lab->distance = $request->input('lab_distance');
        $lab->contact_no = $request->input('lab_contact_no');
        $lab->lang = $request->input('lab_lang');
        $lab->lat = $request->input('lab_lat');

        $lab->slot_date = $request->input('slot_date');
        $lab->slot_time = $request->input('slot_time');
        $lab->booking_time = Carbon::now()->format('Y-m-d H:i:s');

        $lab->appointment_id = $appointment->id;
        $lab->save();

        return ['message' => 'Lab booked successfully'];
    }
    public function patientBookLabGet(Appointment $appointment)
    {
        $lab = Lab::where("appointment_id", $appointment->id)->first();
        return response()->json([
            'lab_name' => $lab->name,
            'lab_address' => $lab->address,
            'lab_city' => $lab->city,
            'lab_state' => $lab->state,
            'lab_distance' => $lab->distance,
            'lab_contact_no' => $lab->contact_no,
            'lab_lang' => $lab->lang,
            'lab_lat' => $lab->lat,
            'slot_date' => $lab->slot_date,
            'slot_time' => $lab->slot_time,
            'booking_time' => $lab->booking_time,
        ]);
    }

    public function doctorAppointment($id)
    {
        $appointment = Appointment::where('id', $id)->first();
        $patient = Patient::where('id', $appointment->patient_id)->first();
        $doctors = Doctor::all();
        return  view('agent.appointments.doctor-appointment', ['patient' => $patient, 'doctors' => $doctors, 'appointment' => $appointment]);
    }
    public function pendingAppointmentDetail()
    {

        $appointments = Appointment::whereNull('end_time')
            ->where(function ($query) {
                $startTimeM = Carbon::now()->subHours(12)->format('Y-m-d');
                $endTimeM = Carbon::now()->addHours(12)->format('Y-m-d');
                $startTime = Carbon::now()->subHours(12)->format('H:i:s');
                $endTime = Carbon::now()->addHours(12)->format('H:i:s');
                $query //->where('appointment_time', '>=', $startTime)
                    //->where('appointment_time', '<=', $endTime)
                    ->where('appointment_date', '>=', $startTimeM)
                    ->where('appointment_date', '<=', $endTimeM);
            })
            ->with('patient:id,first_name,last_name,address,city,state,zip_code,country')
            ->get([
                'id',
                'patient_id',
                'appointment_time',
                'appointment_date',
                'start_time',
                'end_time',
                'duration',
                'timezone'
            ])
            ->groupBy('patient_id', 'appointment_time', 'appointment_date', 'start_time')
            ->map(function ($group) {
                $patient = $group->first()->patient;
                $appointments = $group->sortByDesc('id');
                $array = [];
                foreach ($appointments as $appointment) {
                    $filePath = public_path("assets/profiles/{$patient->id}.png");

                    if (File::exists($filePath)) {
                        $patient->url = "/assets/profiles/{$patient->id}.png";
                    } else {
                        $patient->url = null;
                    }
                    $cart = Cart::where("appointment_id", $appointment->id)->first();
                    $array[] = [
                        'id' => $patient->id,
                        'patient_timezone' => $patient->timezone,
                        'appointment_timezone' => $appointment->timezone,
                        'name' => $patient->first_name . ' ' . $patient->last_name,
                        'address' => $patient->address,
                        'city' => $patient->city,
                        'state' => $patient->state,
                        'zip_code' => $patient->zip_code,
                        'url' => $patient->url,
                        'country' => $patient->country,
                        'time' => time(),
                        'order_id' => $cart->id ?? "",
                        'appointment' => [
                            'id' => $appointment->id,
                            'appointment_time' => $appointment->appointment_time,
                            'appointment_date' => $appointment->appointment_date,
                            'start_time' => $appointment->start_time,
                            'end_time' => $appointment->end_time,
                            'duration' => $appointment->duration,
                            'timezone' => $appointment->timezone

                        ]
                    ];
                }
                return $array;
            })->flatten(1);

        return response()->json($appointments, 200);
    }



    public function doctorAppointmentSave($id, Request $request)
    {
        $appointment_date = $request->input('appointment_date');
        $appointment_time = $request->input('appointment_time');
        $appointment_date = new DateTime($appointment_date);
        $appointment_date = $appointment_date->format('Y-m-d');
        $doctor_id = $request->input('doctor_id');

        $appointment = Appointment::where('id', $id)->first();

        $doctorAppointment = DoctorAppointment::where('patient_id', $appointment->patient_id)
            ->where('doctor_id', $doctor_id)
            ->where('appointment_id', $id)
            ->where('appointment_date', $appointment_date)
            ->where('appointment_time', $appointment_time)
            ->first();

        if (empty($doctorAppointment)) {
            DoctorAppointment::create([
                'patient_id' => $appointment->patient_id,
                'doctor_id' => $doctor_id,
                'appointment_id' => $id,
                'appointment_date' => $appointment_date,
                'appointment_time' => $appointment_time
            ]);


            return response()->json(['message' => 'Doctor appointment booked'], 200);
        } else {
            return response()->json(['message' => 'Error in booking Appointment!'], 200);
        }
        return redirect()->back();
    }

    public function patientTasks($id)
    {
        $appointment = Appointment::where('id', $id)->first();
        $patient = Patient::where('id', $appointment->patient_id)->first();
        $patientTasks = PatientTask::where('patient_id', $appointment->patient_id)->get();
        return  view('agent.appointments.patient-tasks', ['patient' => $patient, 'appointment' => $appointment, 'patientTasks' => $patientTasks]);
    }

    public function patientTasksSave($id, Request $request)
    {
        $description = $request->input('description');

        PatientTask::create([
            'patient_id' => $id,
            'description' => $description,
        ]);

        $request->session()->flash('message', 'Task saved successfully');
        return redirect()->back();
    }

    public function patientTaskDelete($id, Request $request)
    {
        PatientTask::where('id', $id)->delete();
        $request->session()->flash('message', 'Task deleted successfully');
        return redirect()->back();
    }
    public function questions()
    {
        return 'ddd';
    }
    public function questionsList()
    {
        $questionsData = [];
        $groups = QuestionGroup::all();
        foreach ($groups as $group) {
            $questions = Question::where('group_id', $group->id)->get()->toArray();
            $questionsData[$group->title] = $questions;
        }
        return response()->json(
            $questionsData
        );
    }
    public function questionsAnswers($patient_id, $appointment_id)
    {
        $questionsData = [];
        $answers = [];
        $groups = QuestionGroup::all();
        foreach ($groups as $group) {
            $questions = Question::where('group_id', $group->id)->get();
            foreach ($questions as $question) {

                $answer = PatientAnswer::where('question_id', $question->id)->where('patient_id', $patient_id)->where('appointment_id', $appointment_id)->first();
                if (isset($answer->answer))
                    $question['answer'] = $answer->answer;
                else
                    $question['answer'] = null;
            }
            $questionsData[$group->title] = $questions;
        }
        return response()->json(
            $questionsData
        );
    }

    public function storeAnswers(Patient $patient, Appointment $appointment, Request $request)
    {

        $data = $request->input("data");

        foreach ($data as $row) {
            if (isset($row['answer']))
                PatientAnswer::create([
                    'patient_id' => $patient->id,
                    'appointment_id' => $appointment->id,
                    'question_id' => $row['question_id'],
                    'answer' => $row['answer']
                ]);
        }

        return response()->json([
            'message' => 'Answers stored successfully'
        ]);
    }
    public function getQuestions(Patient $patient, Appointment $appointment, Request $request)
    {
        $questions = PatientAnswer::select('questions.*', 'patient_answers.answer')
            ->leftJoin('questions', 'questions.id', '=', 'patient_answers.question_id')
            ->where('patient_answers.patient_id', $patient->id)
            ->where('patient_answers.appointment_id', $appointment->id)
            ->get();

        return response()->json([
            'questions' => $questions
        ]);
    }
    public function switchButton(Telemedpro $agent, $switch)
    {
        if ($switch == 1)
            $agent->recording_switch = $switch;
        else
            $agent->recording_switch = 0;
        $agent->save();

        return response()->json([
            'message' => 'Recording Switched: ' . $switch
        ]);
    }
    public function switchButtonGet(Telemedpro $agent)
    {
        return response()->json([
            'recording_switch' => $agent->recording_switch,
        ]);
    }
    public function switchAiButton(Telemedpro $agent, $switch)
    {
        if ($switch == 1)
            $agent->ai_switch = $switch;
        else
            $agent->ai_switch = 0;
        $agent->save();

        return response()->json([
            'message' => 'AI Switched: ' . $switch
        ]);
    }
    public function switchAiButtonGet(Telemedpro $agent)
    {
        return response()->json([
            'ai_switch' => $agent->ai_switch,
        ]);
    }
    public function getProfile(Request $request)
    {
        $user = Auth::user();
        return response()->json([
            'ai_switch' => $user,
        ]);
    }


    public function questionsListV1()
    {
        $questionGroups = QuestionGroup::with('questions')->get();

        $formattedGroups = [];

        foreach ($questionGroups as $group) {
            $formattedGroups[$group->title] = [];
            foreach ($group->questions as $question) {
                $formattedGroups[$group->title][$question->question] = [$question->type => unserialize($question->options)];
            }
        }

        return response()->json($formattedGroups);
    }
    public function DeviceCurrentStatus(Request $request)
    {
        /*  $patient = Patient::where("id", $patient_id)->firstOrFail(); */
        $micStatus = $request->input('micStatus');
        $camStatus = $request->input('camStatus');
        event(new DeviceCurrentStatus($micStatus, $camStatus));

        return true;
    }
    public function getAnalytics($filter = '12_months')
    {
        $currentMonth = Carbon::now();

        // Filter logic
        switch ($filter) {
            case 'current_month':
                $startDate = $currentMonth->copy()->startOfMonth();
                break;
            case '1_month':
                $startDate = $currentMonth->copy()->subMonth()->startOfMonth();
                break;
            case '2_months':
                $startDate = $currentMonth->copy()->subMonths(2)->startOfMonth();
                break;
            case '3_months':
                $startDate = $currentMonth->copy()->subMonths(3)->startOfMonth();
                break;
            case '6_months':
                $startDate = $currentMonth->copy()->subMonths(6)->startOfMonth();
                break;
            default: // Default to 12 months
                $startDate = $currentMonth->copy()->subMonths(12)->startOfMonth();
        }

        $endDate = $currentMonth->endOfMonth();


        $appointments = Appointment::with('patient')
            ->where("telemed_pros_id", Auth::user()->id)
            ->whereBetween('created_at', [$startDate, $endDate])
            ->get();

        $totalSessions = $appointments->count();
        $totalCallTime = 10; // Assuming you have some logic to calculate this
        if ($totalSessions != 0) {
            $avgSessionTime = $totalCallTime / $totalSessions;
            $avgSessionTime = round(($avgSessionTime / 60), 2);
        } else
            $avgSessionTime = '';


        $monthlyData = [];

        // Loop through each month in the last 12 months
        for ($date = $startDate->copy(); $date->lte($endDate); $date->addMonth()) {
            $monthStart = $date->startOfMonth()->format('Y-m-d');
            $monthEnd = $date->copy()->endOfMonth()->format('Y-m-d'); // Key change here!

            $monthAppointments = Appointment::with('patient')
                ->where("telemed_pros_id", Auth::user()->id)
                ->whereBetween('created_at', [$monthStart, $monthEnd])
                ->get();


            // Calculate any metrics you need from $monthAppointments
            $monthlyData[] = [
                'month' => $date->format('M'), // Example: Jan 2024
                'appointment_count' => $monthAppointments->count()
                // Add other metrics as needed
            ];
        }
        $monthsList = [];
        $monthlySessionCount = [];

        foreach ($monthlyData as $dataPoint) {
            $monthsList[] = $dataPoint['month'];
            $monthlySessionCount[] = $dataPoint['appointment_count'];
        }


        return response()->json([
            'total_sessions' => $totalSessions,
            'total_call_time' => $totalCallTime,
            'avg_session_time' => $avgSessionTime,
            'data' => array_values($monthlySessionCount),  // Ensure consistent order
            'months_list' => $monthsList,
        ]);
    }

    public function getMeetingHistory($filter = '12_months')
    {
        $currentMonth = Carbon::now();

        // Filter logic
        switch ($filter) {
            case 'current_month':
                $startDate = $currentMonth->copy()->startOfMonth();
                break;
            case '1_month':
                $startDate = $currentMonth->copy()->subMonth()->startOfMonth();
                break;
            case '2_months':
                $startDate = $currentMonth->copy()->subMonths(2)->startOfMonth();
                break;
            case '3_months':
                $startDate = $currentMonth->copy()->subMonths(3)->startOfMonth();
                break;
            case '6_months':
                $startDate = $currentMonth->copy()->subMonths(6)->startOfMonth();
                break;
            default: // Default to 12 months
                $startDate = $currentMonth->copy()->subMonths(12)->startOfMonth();
        }

        $endDate = $currentMonth->endOfMonth();

        // Fetch patient names and appointment counts directly from the database
        $monthlyData = Appointment::select(
            'appointments.patient_id',
            /* DB::raw('COUNT(*) as appointment_count'), */
            'appointment_time',
            'appointment_date',
            'start_time',
            'end_time',
            'duration',
            'appointments.id as appointment_id',
            'carts.id as order_id'
        )
            ->leftJoin('carts', 'carts.appointment_id', 'appointments.id')
            ->where("appointments.telemed_pros_id", Auth::user()->id)
            ->whereBetween('appointments.created_at', [$startDate, $endDate])

            ->get();

        $patients = [];

        foreach ($monthlyData as $dataPoint) {
            $patient = $dataPoint->patient;
            /* $appointmentCount = $dataPoint->appointment_count; */
            $start_time = $dataPoint->start_time;
            $end_time = $dataPoint->end_time;
            $duration = $dataPoint->duration;
            $appointment_time = $dataPoint->appointment_time;
            $appointment_date = $dataPoint->appointment_date;
            $appointment_id = $dataPoint->appointment_id;
            $order_id = $dataPoint->order_id;

            $patients[] = [
                'patient' => $patient,
                'appointment_time' => $appointment_time,
                'appointment_date' => $appointment_date,
                /* 'appointment_count' => $appointmentCount, */
                'start_time' => $start_time,
                'end_time' => $end_time,
                'duration' => $duration,
                'appointment_id' => $appointment_id,
                'order_id' => $order_id
            ];
        }

        return response()->json([
            'patients' => $patients,
        ]);
    }
    public function sessionHistory(Request $request)
    {
        $user = $request->user();

        // Assuming user can be either telemedPro or patient
        $history = Appointment::select(
            'appointments.*',
            'appointments.patient_id',
            'patients.first_name as patient_name',
            'carts.id as order_id'
        )
            ->leftJoin('patients', 'appointments.patient_id', '=', 'patients.id')
            ->leftJoin('carts', 'carts.appointment_id', '=', 'appointments.id')
            ->where(function ($query) use ($user) {
                $query->where('appointments.telemed_pros_id', $user->id);
            })
            ->whereNotNull("appointments.end_time")
            ->orderBy('appointments.appointment_date', 'desc')
            ->get();

        return response()->json(['history' => $history]);

        return response()->json(['history' => $history]);
    }
    public function getAppointmentByid($patient, $appointment, Request $request)
    {
        $user = $request->user();

        // Assuming user can be either telemedPro or patient
        $data = Appointment::select(
            'appointments.*',
            'telemed_pros.name as agent_name',
        )
            ->leftJoin('telemed_pros', 'appointments.telemed_pros_id', '=', 'telemed_pros.id')
            ->where('appointments.telemed_pros_id', $user->id)
            ->where('appointments.patient_id', $patient)
            ->where('appointments.id', $appointment)
            ->first();
        $order = Cart::where('appointment_id', $data->id)->first();
        $orderItems = Item::leftJoin('plans_v1', 'plans_v1.id', 'items.plans_id')
            ->where('cart_id', $order->id)->get();
        $data->order = $order;
        $data->telemedPro;
        // $data->order_items = $orderItems;
        $totalPrice = 0;
        $total_products = 0;
        $quantity = [];
        $totalShippingCost = 0;
        $data->order_notes = PatientNote::where('appointment_id', $appointment)->get();
        foreach ($orderItems as $item) {
            $totalShippingCost += $item->shipping_cost;
            $item->total_price = $item->quantity * $item->price;
            $totalPrice += $item->total_price;
            $order->order_total_amount = $totalPrice;
            $order->order_total_shipping = $totalShippingCost;
            $item->plansV1->qty = $item->quantity;
        }
        $data->order_items = $orderItems;

        $data->shipping_activity = ItemHistory::where('cart_id', $order->id)->get();
        return response()->json(['data' => $data]);
    }
    public function addNotePatient(Patient $patient, Appointment $appointment, Request $request)
    {
        $user = Auth::user();
        $addNotePatient = PatientNote::create([
            'note' => $request->input('note'),
            'note_type' => $request->input('note_type'),
            'patient_id' => $patient->id,
            'appointment_id' => $appointment->id,
            'telemed_pros_id' => $user->id
        ]);
        $addNotePatient->file_url = "";
        if ($request->hasFile('file')) {
            $file = $request->file('file');

            $filename = $addNotePatient->id . '.' . $file->getClientOriginalExtension();

            $file->move(public_path('assets/files'), $filename);

            $addNotePatient->file_url = "assets/files" . $addNotePatient->id . '.' . $file->getClientOriginalExtension();
        }
        $patient = $addNotePatient->patient;
        $setting = Setting::find(1);
        Mail::send('emails.noteAdded', ['patient' => $patient, 'agent' => $user, 'setting' => $setting], function ($message) use ($patient, $user) {
            $message->to($patient->email, $patient->first_name)
                ->subject('You Have a New Note from ' . $user->name);
        });
        return response()->json([
            'message' => 'Note created',
            'data' => $addNotePatient
        ], 200);
    }

    public function getNotePatient(Patient $patient, Appointment $appointment, Request $request)
    {
        $patientNotes = PatientNote::where("patient_id", $patient->id)
            ->where("appointment_id", $appointment->id)
            ->with('appointment')
            ->get();

        $data = $patientNotes->map(function ($patientNote) {
            $fileUrl = "/assets/files/{$patientNote->id}.png";
            $filePath = public_path($fileUrl);

            if (File::exists($filePath)) {
                $fileUrl = "/assets/files/{$patientNote->id}.png";
            } else {
                $fileUrl = null;
            }

            return [
                'id' => $patientNote->id,
                'note' => $patientNote->note,
                'note_type' => $patientNote->note_type,
                'created_at' => $patientNote->created_at,
                'patient_id' => $patientNote->patient_id,
                'appointment' => $patientNote->appointment,
                'telemedPro' => $patientNote->telemedPro,
                'file_url' => $fileUrl,
                'telemedPro' => $patientNote->appointment?->telemedPro
            ];
        });

        return response()->json([
            'message' => 'Patient notes retrieved',
            'data' => $data
        ], 200);
    }

    public function getQuestionBuilderStore(Patient $patient, Request $request)
    {

        $questionBuilder = QuestionBuilder::select('key', 'value')->where("customer_id", $patient->id)->get();
        $jsonData = $questionBuilder->mapWithKeys(function ($item) {
            return [$item->key => $item->value];
        });
        // Store data
        return response()->json([
            'message' => 'Data Sent',
            'data' => $jsonData
        ], 200);
    }
    public function getPrescription()
    {
        $prescriptions = Prescription::all();
        return response()->json($prescriptions);
    }
    public function storePrescription(Request $request)
    {
        $prescription = Prescription::create($request->all());
        return response()->json($prescription, 200);
    }
    public function storePatientPrescription(Request $request)
    {
        $user = Auth::user();
        $prescription = PatientPrescription::create($request->all());
        $prescription->status = "pending";
        $prescription->save();
        $patient = $prescription->patient;
        $setting = Setting::find(1);
        Mail::send('emails.prescriptionAdd', ['patient' => $patient, 'prescription' => $prescription, 'setting' => $setting], function ($message) use ($patient, $user) {
            $message->to($patient->email, $patient->first_name)
                ->subject('New Prescription Details from ' . $user->name);
        });
        return response()->json($prescription, 200);
    }
    public function updateStatusPrescription($patient_prescription_id, Request $request)
    {
        $status = $request->input("status");
        $prescription = PatientPrescription::find($patient_prescription_id);
        $prescription->status = $status;
        $prescription->save();
        $patient = $prescription->patient;
        $setting = Setting::find(1);
        Mail::send('emails.prescriptionUpdated', ['patient' => $patient, 'setting' => $setting], function ($message) use ($patient) {
            $message->to($patient->email, $patient->first_name)
                ->subject('Prescription updated.');
        });
        return response()->json($prescription, 200);
    }

    public function getStatusPrescription($patient_prescription_id)
    {
        $prescription = PatientPrescription::find($patient_prescription_id);
        return response()->json($prescription, 200);
    }
    public function getPatientPrescription($patient_id, $appointment_id)
    {
        $patientPrescription = PatientPrescription::with('prescription')
            ->where('patient_id', $patient_id)
            ->where('appointment_id', $appointment_id)
            ->get();

        $prescriptionData = [];
        foreach ($patientPrescription as $prescription) {
            $prescriptionData[] = [
                'patient' => $prescription->patient,
                'prescription' => $prescription->prescription,
                'created_at' => $prescription->created_at,
                'updated_at' => $prescription->updated_at,
                'direction_one' => $prescription->direction_one,
                'direction_two' => $prescription->direction_two,
                'dont_substitute' => $prescription->dont_substitute,
                'comments' => $prescription->comments,
                'appointment_id' => $prescription->appointment_id,
                'status' => $prescription->status,
                'appointment' => $prescription->appointment,
                'telemedPro' => $prescription->appointment->telemedPro,
                'licenseNumber' => LicenseNumberModel::where("provider_id", $patient_id)->orderBy('id', 'DESC')->first()
            ];
        }
        if (!$patientPrescription->isEmpty()) {
            return response()->json($prescriptionData);
        } else {
            return response()->json(['message' => 'Prescription not found'], 404);
        }
    }
    public function getOrderData(Cart $cart, Request $request)
    {
        $cart = Cart::with("patient")->get();
        return response()->json(['cart' => $cart], 200);
    }

    public function getLabKit(Cart $cart, Request $request)
    {
        $kit = LabKit::all();
        return response()->json(['kit' => $kit], 200);
    }

    public function orderLabKit(LabKit $labkit, Patient $patient, Request $request)
    {


        $user = $patient;
        $cart = new Cart();
        $cart->lab_kit_id = $labkit->id;
        $cart->first_name = $patient->first_name;
        $cart->last_name = $patient->last_name;
        $cart->email = $patient->email;
        $cart->phone = $patient->phone_no;
        $cart->status = "pending";

        $cart->date_of_birth = $patient->dob ?? null;

        $cart->patient_id = $user->id;

        $cart->shipping_address1 = $patient->address;
        $cart->shipping_city = $patient->city;
        $cart->shipping_state = $patient->state;
        $cart->shipping_zipcode = $patient->zip_code;
        $cart->shipping_country = $patient->country;


        $cart->shipping_amount = $labkit->amount;
        $cart->total_amount = $labkit->amount;

        $cart->save();
        return response()->json(['status' => 'Success', 'cart' => $cart], 200);
    }

    public function getorderedLabKit(LabKit $labkit, Patient $patient, Request $request)
    {
        $detail = Cart::select("carts.*", "lab_kit.name")->leftJoin("lab_kit", "carts.lab_kit_id", "=", "lab_kit.id")
            ->where("carts.lab_kit_id", $labkit->id)
            ->where("carts.patient_id", $patient->id)
            ->get();

        return response()->json(['order' => $detail], 200);
    }
    public function getorderedLabKitBasedOnPatient(Patient $patient, Request $request)
    {
        $detail = Cart::select("carts.*", "lab_kit.name")->leftJoin("lab_kit", "carts.lab_kit_id", "=", "lab_kit.id")
            ->where("carts.patient_id", $patient->id)
            ->get();

        return response()->json(['order' => $detail], 200);
    }
    public function updateStatusOrderData(Cart $cart, Request $request)
    {

        $cart = Cart::where("id", $cart->id)->firstOrFail();
        $cart->status = $request->input("status");
        $cart->save();

        return response()->json(['status' => 'Success', 'cart' => $cart], 200);
    }
    public function PatientAppointment()
    {
        $user = Auth::user();
        $data = [];
        $appointments = Appointment::select('patient_id')->where('telemed_pros_id', $user->id)->groupBy('patient_id')->get();
        foreach ($appointments as $appointment) {
            $patient = Patient::where('id', $appointment->patient_id)->first();
            array_push($data, $patient->toArray());
        }
        return response()->json(['status' => 'Success', 'patient' => $data], 200);
    }
}
