HEX
Server: nginx/1.24.0
System: Linux DGT-WORDPRESS-VM-SERVER 6.14.0-1017-azure #17~24.04.1-Ubuntu SMP Mon Dec 1 20:10:50 UTC 2025 x86_64
User: ubuntu (1000)
PHP: 8.4.12
Disabled: NONE
Upload Files
File: /mnt/data/ghayatcom/ghayatcom-api/app/Http/Controllers/Api/HealthRecordController.php
<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Auth;
use DB;
use Config;
use Storage;
use DateTime;
use Hash;
use Exception;
use Throwable;
use Validator;
use Illuminate\Database\QueryException;
use Illuminate\Support\Carbon;
use App\DoctorSymptomTemplates;
use App\DoctorSymptoms;
use App\Appointment;
use App\HealthRecords;
use App\HealthRecordSymptoms;
use App\DoctorSymptomTemplateFields;
use App\Prescription;
use App\Diagnosis;
use App\PrescriptionDetails;
use App\PrescriptionRoutes;
use App\ReferalDetails;
use App\ReferalExaminations;
use App\ReferalSpecificExaminations;
use App\Examinations;
use App\ExaminationDetails;
use App\SickLeaveCertificate;
use App\ReferalRequests;
use App\ReferalRequestDetail;
use App\WebSetting;
use App\WaitingRoom;
use App\PrescriptionRouteLists;
use App\Http\Requests\CreatePrescriptionIDRequest;
use App\Http\Requests\ReferalExaminationRequest;
use App\Http\Requests\ConsultationReportRequest;
use App\Http\Requests\AddPrescriptionRequest;
use App\Http\Requests\SickLeaveCertificateRequest;
use App\Http\Requests\ReferalRequest;
use App\Http\Requests\SubmitConsultationRequest;
use App\Http\Requests\CreateHealthRecordRequest;
use App\Http\Requests\TemplateSymptomsRequest;
use App\Http\Resources\PrescriptionDetailResource;
use App\Http\Resources\SickLeaveCertificateResource;
use App\Http\Resources\AppointmentResource;
use App\Http\Resources\PrescriptionReportCollection;
use App\Http\Resources\ConsultationCollection;
use App\Http\Controllers\Controller;
use PDF;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use App\Library\RandomLibrary;
use App\Library\S3Library;
use App\Library\FcmLibrary;
use App\Jobs\ConsultationCompletedJob;
use App\Jobs\ConsultationReferalJob;
use App\Jobs\ConsultationPrescriptionJob;
use Illuminate\Support\Facades\Mail;
use App\User;
use App\DependantAccountHolder;
use App\Mail\SendEmailNotification;
use App\Jobs\SendEmailNotificationJob;
use App\Enums\AppoitmentStatusEnum;
use App\Notifications\PrescriptionDoctorCompletedNotify;
use App\Notifications\DoctorConsultationCompletedNotify;
use Notification;
use App\Jobs\AppointmentConsultationPdfCreate;
use App\Lab;
use App\LabParameter;
use App\LabPackage;
use App\LabTestDetails;
use App\LabOrder;
use App\LabOrderData;
use App\AdminSettings;

class HealthRecordController extends Controller
{
    public function getSymptomsTemplate(Request $request){
        try {
            $templates = DoctorSymptomTemplates::with(['templateFields'])->get()->toArray();
            return self::sentResponse(200, $templates, __('digimed_validation.success_response.data_fetch_success'));
        } catch (Exception $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }
    public function getSymptomsByTemplate(TemplateSymptomsRequest $request){
        try {
            $validated = $request->validated();
            /**
             * @var string $data_template_id
             */
            $data_template_id = $request->template_id;
            $template_id = explode(",", $data_template_id);
            $templates = DoctorSymptoms::whereIn("template_id",$template_id)->get()->toArray();
            return self::sentResponse(200, $templates, __('digimed_validation.success_response.data_fetch_success'));
        } catch (Exception $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }
    public function getReferalRequest(Request $request){
        try {
            $data = ReferalRequests::get()->toArray();
            return self::sentResponse(200, $data, __('digimed_validation.success_response.data_fetch_success'));
        } catch (Exception $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }
    public function getReferalExamination(Request $request){
        try {
            $data = Examinations::get()->toArray();
            return self::sentResponse(200, $data, __('digimed_validation.success_response.data_fetch_success'));
        } catch (Exception $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }
    public function getReferalSpecificExamination(ReferalExaminationRequest $request){
        try {
            $validated = $request->validated();
            /**
             * @var string $data_examination_id
             */
            $data_examination_id = $request->examination_id;
            $exam_id = explode(",", $data_examination_id);
            $templates = ExaminationDetails::whereIn("examination_id",$exam_id)->get()->toArray();
            return self::sentResponse(200, $templates, __('digimed_validation.success_response.data_fetch_success'));
        } catch (Exception $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }

    public function submitConsultation(SubmitConsultationRequest $request, RandomLibrary $randomLibrary, S3Library $S3Library, FcmLibrary $fcmLibrary){
        $validated = $request->validated();
        try {
            DB::beginTransaction();
            $appointment_id = $request->appointment_id;
            /**
             * @var string $data_health_record
             */
            $data_health_record = $request->health_record;
            $health_record = json_decode($data_health_record);
             /**
             * @var string $data_prescription
             */
            $data_prescription = $request->prescription;
            $prescription = json_decode($data_prescription);
             /**
             * @var string $data_referal
             */
            $data_referal = $request->referal;
            $referal = json_decode($data_referal);

            $authRole = Auth::user();
            $auth_id = auth()->user()->id;

            $pdf_password = substr(md5((string)rand()),0,8);
            $web_settings = WebSetting::find(1);
            $contact_email = $web_settings->contact_email;
            $website = $web_settings->website;
            $appointment = Appointment::with(['patientDetails','doctorDetails'])->find($appointment_id);

            // if($appointment->consultation_end_time != NULL){
            //     return self::sentResponse(401, [], __('digimed_validation.error_response.report_already_submitted'));
            // }

            if(!empty($health_record)){
                /** @var object $health_record */
                $records = HealthRecords::with(['templateSymptoms'])->where('appointment_id',$appointment_id)->first();
                // print_r($records->toArray());exit;
                if(empty($records)){
                    $records = new HealthRecords();
                }
                $records->user_id = $appointment->patient_id;
                $records->appointment_id = $appointment->id;
                $records->symptom_name = $health_record->symptom;
                $records->diagnosis = $health_record->diagnosis;
                $records->different_diagnosis = $health_record->different_diagnosis;
                $records->treatment_given = $health_record->treatment_given;
                $records->recommeded_follow_up = $health_record->recommended_follow_up;
                $records->other_comments = $health_record->other_comments;
                $records->template_id = $health_record->template_id == "" ? NULL: $health_record->template_id;
                // $records->template_symptoms = $health_record->template_symptoms;
                $records->other_symptom = $health_record->other_symptom;
                $records->grading = $health_record->grading;
                $records->infertility = $health_record->infertility;
                $records->stds = $health_record->stds;
                $records->contraception = $health_record->contraception;
                $records->dribbling = $health_record->dribbling;
                $records->pain_scale = $health_record->pain_scale;
                $records->last_menstrual_period = $health_record->last_menstrual_period;
                $records->pregnant = $health_record->pregnant;
                $records->miscarriages = $health_record->miscarriages;
                $records->length_of_periods = $health_record->length_of_periods;
                $records->libido = $health_record->libido;
                $records->pregnancies = $health_record->pregnancies;
                $records->status = $request->status;
                $records->created_by = $auth_id;
                $records->updated_by = $auth_id;
                $records->save();
                $record_id = $records->id;

                if(!empty($health_record->template_symptoms)) {
                    $records->templateSymptoms()->delete();
                    $symptoms = array_filter(explode(',', $health_record->template_symptoms));
                    for ($j=0; $j < count($symptoms); $j++) {
                        $AppointmentSymptom = new HealthRecordSymptoms();
                        $AppointmentSymptom->health_record_id = $record_id;
                        $AppointmentSymptom->symptom_id = $symptoms[$j];
                        $AppointmentSymptom->created_by = auth()->user()->id;
                        $AppointmentSymptom->save();
                    }
                }
            }
            /** @var object $prescription */
            $data = $prescription->prescription_data;
            if(!empty($data)){
                $exists = Prescription::where("appointment_id",$appointment_id)->update(['updated_by' =>$auth_id,'deleted_by' =>$auth_id,'deleted_at'=>new DateTime]);
                $exists = PrescriptionDetails::where("appointment_id",$appointment_id)->update(['updated_by' =>$auth_id,'deleted_by' =>$auth_id,'deleted_at'=>new DateTime]);
                foreach($data as $key => $value){
                    $type = $value->type;

                    // getPrescriptionCode
                    /** @var string|null $column */
                    $column = 'prescription_code';
                    /** @var string $forCondition */
                    $forCondition = 'prescription';
                    /** @var string|null $getPrescriptionCode */
                    $getPrescriptionCode = $randomLibrary->randomPluck(NULL, new Prescription, $column, $forCondition);

                    $parent = new Prescription();
                    $parent->appointment_id = $appointment_id;
                    $parent->patient_id = $appointment->patient_id;
                    $parent->type = $type;
                    $parent->prescription_code = $getPrescriptionCode;
                    $parent->status = $request->status;
                    $parent->prescription_date = Carbon::now()->format('Y-m-d h:i:s');
                    $parent->created_by = $auth_id;
                    $parent->save();
                    $prescription_id = $parent->id;

                    $routes_list = [];
                    $route_ids = $value->route_id;
                    if (isset($value->route)) {
                        $routes_list = array_filter(explode(",", $route_ids));
                        $routeskey = array_filter(explode(',', $value->route));
                        foreach($routeskey AS $val) {
                            $exists = PrescriptionRoutes::where('route', $val)->first();
                            if(!empty($exists)){
                                $exists_id = $exists->id;
                            }
                            else{
                                $routes = new PrescriptionRoutes;
                                $routes->route = $value->route;
                                $routes->created_by = $auth_id;
                                $routes->created_at = now();
                                $routes->save();
                                $exists_id = $routes->id;
                            }
                            array_push($routes_list, $exists_id);
                        }
                        $routes_data = $routes_list;
                    }
                    else
                    {
                        if(!empty($route_ids)) {
                            $routes_data = array_filter(explode(",", $route_ids));
                        }
                    }
                    if(!empty($routes_data)) {
                        for ($j=0; $j < count($routes_data); $j++) {
                            $list = new PrescriptionRouteLists;
                            $list->prescription_id = $prescription_id;
                            $list->route_id = $routes_data[$j];
                            $list->created_by = $auth_id;
                            $list->created_at = now();
                            $list->save();
                        }
                    }
                    $child = new PrescriptionDetails();
                    $child->appointment_id = $appointment_id;
                    $child->prescription_id = $parent->id;
                    $child->product_name = $value->product_name;
                    $child->dose = $value->dose;
                    $child->frequency = $value->frequency;
                    $child->duration = $value->duration;
                    $child->type_value = $value->type_value;
                    $child->type_value_total = $value->type_value;
                    $child->timing = $value->timing;
                    $child->other_comments = $value->other_comments;
                    $child->created_by = $auth_id;
                    $child->save();
                }
            }

            $verify_enabled = $appointment->sick_leave_verification;

            $certificate = SickLeaveCertificate::where('appointment_id', $appointment_id)->first();
            if (empty($certificate)) {
                $certificate = new SickLeaveCertificate;
                $certificate->created_by = $auth_id;
            }
            $certificate->appointment_id = $appointment_id;

            // Handle patient certificate upload
            if ($request->hasFile('patient_certificate')) {
                $digimedFile = $S3Library->fileUpload(true, 'jpeg|JPEG|jpg|JPG|png|PNG|pdf', true, $request->file('patient_certificate'), 'digimed/images/sick_leave_certificate/');

                if ($digimedFile['code'] == 200) {
                    $certificate->patient_certificate = $digimedFile['data'];
                } elseif ($digimedFile['code'] == 500) {
                    DB::rollback();
                    return self::sentResponse(500, $digimedFile['data'], $digimedFile['msg']);
                }
            }
            // else {
            //     if (empty($request->patient_certificate)) {
            //         $certificate->patient_certificate = "";
            //     }
            // }

            // Handle employer certificate upload
            if ($request->hasFile('employer_certificate')) {
                $digimedFile = $S3Library->fileUpload(true, 'jpeg|JPEG|jpg|JPG|png|PNG|pdf', true, $request->file('employer_certificate'), 'digimed/images/sick_leave_certificate/');

                if ($digimedFile['code'] == 200) {
                    $certificate->employer_certificate = $digimedFile['data'];
                } elseif ($digimedFile['code'] == 500) {
                    DB::rollback();
                    return self::sentResponse(500, $digimedFile['data'], $digimedFile['msg']);
                }
            }
            // else {
            //     if (empty($request->employer_certificate)) {
            //         $certificate->employer_certificate = "";
            //     }
            // }

            // Set other fields and save
            $certificate->medical_note = $request->medical_note;
            $certificate->updated_by = $auth_id;
            $certificate->status = $request->status;
            $certificate->save();


            if(!empty($referal)){
                /** @var object $referal */
                $referal_data = ReferalDetails::where('appointment_id', $appointment_id)->first();
                if(empty($referal_data)){
                    $referal_data = new ReferalDetails;
                }
                $referal_data->appointment_id = $appointment_id;
                $referal_data->is_referal = $referal->is_referal;
                $referal_data->presenting_complaints = $referal->presenting_complaints;
                $referal_data->indications = $referal->indications;
                $referal_data->special_comments = $referal->special_comments;
                $referal_data->last_menstrual_period = $referal->last_menstrual_period;
                $referal_data->additional_comments = $referal->additional_comments;
                $referal_data->other_examinations = $referal->other_examinations;
                $referal_data->status = $request->status;
                $referal_data->created_by = $auth_id;
                $referal_data->updated_by = $auth_id;
                $referal_data->save();
                $referal_id = $referal_data->id;


                if(!empty($referal->examinations)){
                    $examinations = array_filter(explode(',', $referal->examinations));
                    $referal_data->referalExaminations()->sync($examinations);
                }
                if(!empty($referal->specific_examinations)){
                    $specific_examinations = array_filter(explode(',', $referal->specific_examinations));
                    $spec_list = [];
                    foreach($specific_examinations as $row){
                        $list = ExaminationDetails::find($row);
                        $spec_list[$row] =['examinations_id'=>$list->examination_id];
                    }
                    $referal_data->referalSpecificExaminations()->sync($spec_list);
                }
                if($referal->request_for){
                    $exists = ReferalRequestDetail::where("referal_details_id",$referal_id)->update(['updated_by' =>$auth_id,'deleted_by' =>$auth_id,'deleted_at'=>new DateTime]);
                    $request_for = array_filter(explode(',', $referal->request_for));
                    foreach($request_for as $row)
                    {
                        $list = new ReferalRequestDetail;
                        $list->referal_details_id = $referal_id;
                        $list->referal_requests_id = $row;
                        $list->created_by = $auth_id;
                        $list->created_at = now();
                        $list->save();
                    }
                }
            }
            DB::commit();
            if($request->status == 1){
                dispatch(new AppointmentConsultationPdfCreate($appointment_id));
                Appointment::where('id', $appointment_id)->update(['consultation_end_time' => new DateTime, 'appointment_status' => AppoitmentStatusEnum::COMPLETED()]);
                WaitingRoom::where('appointment_id', $appointment_id)->update(['status' => 3]);
            }
            return self::sentResponse(200, [], __('digimed_validation.success_response.data_update_success'));

        } catch(Exception | Throwable | QueryException $e) {
            DB::rollback();
            return self::sentResponse(500,[], $e->getMessage());
        }
    }
    public function consultationReport(ConsultationReportRequest $request){
        try {
            $validated = $request->validated();
            $authRole = Auth::user();
            $auth_id = auth()->user()->id;
            $appointment_id = $request->appointment_id;
            $appointment = Appointment::find($appointment_id);
            if($appointment->consultation_end_time == NULL){
                return self::sentResponse(500, [], __('digimed_validation.error_response.appointment_not_completed'));
            }
            
            // Check if the authenticated user has permission to view a report.
            // if(!$this->checkReportPermission($appointment->patient_id,$appointment->doctor_id)){
            //     return self::sentResponse(403, [], __('digimed_validation.error_response.report_permission_denied'));
            // }
           
            $health_record = HealthRecords::where("appointment_id",$appointment_id)->first();
            if(!empty($health_record)){
                $health_record_pdf = $health_record->pdf;
            }
            else{
                $health_record_pdf = "";
            }
            $prescription = Prescription::where("appointment_id",$appointment_id)->first();
            if(!empty($prescription)){
                $prescription_pdf = $prescription->pdf;
            }
            else{
                $prescription_pdf = "";
            }
            $referal = ReferalDetails::where("appointment_id",$appointment_id)->first();
            if(!empty($referal)){
                if($referal->is_referal == 1){
                    $referal_pdf = $referal->pdf;
                }
                else{
                    $referal_pdf = "";
                }
            }
            else{
                $referal_pdf = "";
            }
            $sick_certificate = SickLeaveCertificate::where('appointment_id', $appointment_id)->first();
            // print_r($sick_certificate);exit;
            if (empty($sick_certificate)) {
                $patient_pdf = "";
                $employer_pdf = "";
                $medical_note_pdf = "";
            } else {
                $patient_pdf = $sick_certificate->patient_certificate ?? "";
                $employer_pdf = $sick_certificate->employer_certificate ?? "";
                $medical_note_pdf = $sick_certificate->pdf ?? "";
            }
            // if(empty($sick_certificate)){
            //    $patient_pdf = "";
            //    $employer_pdf = "";
            //    $medical_note_pdf = "";
            // }
            // else{
            //     if(!empty($sick_certificate->patient_certificate)){
            //         $patient_pdf = SickLeaveCertificate::where('appointment_id', $appointment_id)->first()->patient_certificate;
            //     }
            //     else{
            //         $patient_pdf = "";
            //     }
            //     if(!empty($sick_certificate->employer_certificate)){
            //         $employer_pdf = SickLeaveCertificate::where('appointment_id', $appointment_id)->first()->employer_certificate;
            //     }
            //     else{
            //         $employer_pdf = "";
            //     }
            //     if(!empty($sick_certificate->medical_note)){
            //         $medical_note_pdf = SickLeaveCertificate::where("appointment_id",$appointment_id)->first()->pdf;
            //     }
            //     else{
            //         $medical_note_pdf ="";
            //     }
            // }
            $prescriptions = Prescription::with(['prescriptionDetails','appointment.patientDetails','appointment.doctorDetails'])->where('appointment_id',$appointment_id)->get();

            $lab_data['lab_suggestion'] = $appointment['lab_suggestion'];
            
            if( $lab_data['lab_suggestion'] == 1) {
                $lab_suggestion_details = json_decode($appointment['lab_suggestion_details'], true);
            
                $labsId = $lab_suggestion_details['lab_id'];

                $adminSetting = AdminSettings::take(1)->first();
                
                $totalPrice = 0;
                $taxPercentage = !empty($adminSetting->lab_tax) ? $adminSetting->lab_tax : config('custom.default.lab_tax');
                $parameterDetails = [];
                $packageDetails = [];

                $lab_details = Lab::select('id','name')->where('id',$labsId)->first();
                if($lab_details){
                    $lab_data['lab_id'] = $lab_details->id; 
                    $lab_data['lab_name'] = $lab_details->name;
                }
        
                $lab_package_details = LabPackage::whereIn('id', $lab_suggestion_details['package_ids'])->get();
                if(count($lab_package_details)>0){
                    $lab_data['lab_package_details'] = $lab_package_details->toArray();

                    //calculation for lab package id

                    if (!empty($lab_suggestion_details['package_ids'])) {
                        $packages = LabPackage::with(['lab', 'category']) // Eager load lab and category relationships
                            ->whereIn('id', $lab_suggestion_details['package_ids'])
                            ->get();
        
                        foreach ($packages as $package) {
                            $packageDetail = [
                                'id' => $package->id,
                                'name' => $package->name,
                                'lab_id' => $package->lab->id ?? null,
                                'lab' => $package->lab->name ?? null,
                                'category_id' => $package->category->id ?? null,
                                'category' => $package->category->name ?? null,
                            ];
        
                            // if (!$isDoctor) {
                                $packageDetail['price'] = $package->price;
                                $totalPrice += $package->price;
                            // }
        
                            $packageDetails[] = $packageDetail;
                        }
                    }
                }
                $lab_parameter_details = LabParameter::whereIn('id', $lab_suggestion_details['parameter_ids'])->get();
                if(count($lab_parameter_details)>0){
                    
                    $lab_data['lab_parameter_details'] = $lab_parameter_details->toArray();
                    // for calculation
                    if (!empty($lab_suggestion_details['parameter_ids'])) {
                        $parameters = LabParameter::with(['lab', 'category']) // Eager load lab and category relationships
                            ->whereIn('id', $lab_suggestion_details['parameter_ids'])
                            ->get();
        
                        foreach ($parameters as $parameter) {
                            $parameterDetail = [
                                'id' => $parameter->id,
                                'name' => $parameter->name,
                                'lab_id' => $parameter->lab->id ?? null,
                                'lab' => $parameter->lab->name ?? null,
                                'category_id' => $parameter->category->id ?? null,
                                'category' => $parameter->category->name ?? null,
                            ];
        
                            // if (!$isDoctor) {
                                $parameterDetail['price'] = $parameter->price;
                                $totalPrice += $parameter->price;
                            // }
        
                            $parameterDetails[] = $parameterDetail;
                        }
                    }
        
                }
                $subTotal = $totalPrice;
                $taxAmount = ($taxPercentage / 100) * $subTotal;
                $totalPrice += $taxAmount;

                //lab order data
                $lab_order_data = LabOrder::with('orderData','address')->where('appointment_id',$appointment['id'])->get();
                $lab_data['order_details'] = [];
                if($lab_order_data->isNotEmpty()){
                    $lab_data['order_details'] = $lab_order_data;
                }

                $lab_data['parameter_details'] = $parameterDetails;
                $lab_data['package_details'] = $packageDetails;
                $lab_data['subtotal'] = number_format($subTotal, 2, '.', '');
                $lab_data['tax_percentage'] = $taxPercentage;
                $lab_data['tax_amount'] = number_format($taxAmount, 2, '.', '');
                $lab_data['total_price'] = number_format($totalPrice, 2, '.', '');

                //parameter and package amount calculation
              
              
            }
            $response_array = [
                'health_record_pdf' => $health_record_pdf,
                'prescription_pdf' => $prescription_pdf,
                'medical_note_pdf' => $medical_note_pdf,
                'referal_pdf' => $referal_pdf,
                'sick_leave_patient_pdf' => $patient_pdf,
                'sick_leave_employer_pdf' => $employer_pdf,
                'report_permission' =>$appointment->report_permission,
                'lab_details' => $lab_data,
                'prescription' => new PrescriptionReportCollection($prescriptions),
                
            ];
            return self::sentResponse(200, $response_array, __('digimed_validation.success_response.data_fetch_success'));

        } catch(\Exception | Throwable | QueryException $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }

    public function consultationDraftList(ConsultationReportRequest $request){
        try {
            $appointment_id = $request->appointment_id;
            $health_record = HealthRecords::with(['templateSymptoms'])->where('appointment_id', $appointment_id)->first();
            $prescription = Prescription::where("appointment_id",$appointment_id)->get();
            $referal = ReferalDetails::where("appointment_id",$appointment_id)->first();
            $sick_certificate = SickLeaveCertificate::where('appointment_id', $appointment_id)->first();

            $array = [
                'appointment_id'=> $appointment_id,
                'health_record' => $health_record,
                'prescription'=> $prescription,
                'referal'=>$referal,
                'sick_certificate'=> $sick_certificate
            ];
            return new ConsultationCollection($array);

        } catch(\Exception | Throwable | QueryException $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }
    public function sendPrescriptionPdf(ConsultationReportRequest $request){
        try {
            $validated = $request->validated();
            $appointment_id = $request->appointment_id;
            $attachments = [];
            $prescription = Prescription::where("appointment_id",$appointment_id)->get();
            foreach($prescription as $key => $value){
                $attachments[] = 'digimed/images/prescription/prescription_'.$appointment_id.'.pdf';
            }

        } catch(\Exception | Throwable | QueryException $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }

    /**
    * Check if the authenticated user has permission to view a report.
    */
    private function checkReportPermission($patientId, $doctorId)
    {
        $authId = auth()->id();
        $hasPermission = User::where('id', $patientId)->value('report_permission');
    
        // Return true if:
        // 1. Permission is not given but the auth user is either the doctor or the patient
        // 2. Permission is given
        return $hasPermission || $authId === $patientId || $authId === $doctorId;
    }

    //reject lab suggestion by patient
    public function rejectSuggestion(ConsultationReportRequest $request)
    {
        try {
            $rules = [               
                'appointment_id' => 'required|exists:appointments,id',   
            ];
            $messages = [
                'appointment_id.required' => __('digimed_validation.form_validation_error.appointment_id_req'),
            ];
            $validator = Validator::make($request->all(), $rules, $messages);

            if ($validator->fails()) {
                return self::sentResponse(422, [], $validator->errors()->first()); 
            } 

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

            $appointment->lab_suggestion = 2;
            $appointment->save();
        
            return self::sentResponse(200, [], __('digimed_validation.success_response.reject_lab_suggestion'));

        } catch (Exception | Throwable | QueryException $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }


}