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/AdminPrescriptionController.php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\PrescriptionCollection;
use App\Prescription;
use App\PrescriptionRequest;
use App\WebSetting;
use App\Appointment;
use App\Http\Requests\AppointmentDetailRequest;
use App\Enums\AppoitmentStatusEnum;
use Exception;
use Throwable;
use Illuminate\Database\QueryException;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\AdminPrescriptionExport;
use Config;
use Storage;
use PDF;
use App\Library\S3Library;
use Illuminate\Support\Carbon;
use SoapClient;

class AdminPrescriptionController extends Controller
{
    public function index(Request $request)
    {
        try {
            $paginate = $request->count_per_page ? $request->count_per_page : 10;
            /** @var int|null $paginate */
            $orderBy = $request->order_by ? $request->order_by : 'desc';
            $pageNumber = $request->page ? $request->page : 1;
            $sort_by = $request->sort_by ? $request->sort_by : 'id';
            $search_key = $request->search ? $request->search : '';
            /** @var \App\User $authRole */
            $type = $request->type;
            $list = Prescription::with(['appointment','prescriptionDetails','prescriptionRequests'])->whereHas('appointment', function($q){
                $q->where('appointment_status', AppoitmentStatusEnum::COMPLETED());
                $q->where('consultation_end_time', '!=', NULL);
            })
            ->has('prescriptionRequests')
            ->where('status', '1');

            if(!empty($search_key)) {
                $list = $list->where(function($q) use($search_key) {
                    $q->where('prescription_code', 'LIKE', "%{$search_key}%");
                    $q->orWhereHas('appointment.patientDetails',function($r) use($search_key) {
                        $r->where('first_name', 'LIKE', "%{$search_key}%");
                        $r->orWhere('last_name', 'LIKE', "%{$search_key}%");
                        $r->orWhere('passport_number', 'LIKE', "%{$search_key}%");
                    });
                    $q->orWhereHas('appointment.doctorDetails',function($r) use($search_key) {
                        $r->where('first_name', 'LIKE', "%{$search_key}%");
                        $r->orWhere('last_name', 'LIKE', "%{$search_key}%");
                        $r->orWhere('passport_number', 'LIKE', "%{$search_key}%");
                    });
                    $q->orWhereHas('prescriptionRequests.pharmacyData',function($r) use($search_key) {
                        $r->where('name', 'LIKE', "%{$search_key}%");
                    });
                });
            }

            if(!empty($type)) {
                $list = $list->where('request_status', $type);
            }
            /**
            * @var string $sort_by
            * @var string $orderBy
            */
            $list = $list->orderBy($sort_by,$orderBy);
            return new PrescriptionCollection($list->paginate($paginate), 200);
        } catch(Exception | Throwable | QueryException $e) {
            return self::sentResponse(500,[], $e->getMessage());
        }
    }

    public function adminPrescriptionListExcel(Request $request)
    {
        try {
            $fileName = date('YmdHis').".xlsx";
            if(Config::get('filesystems.default') == "s3") {
                Excel::store(new AdminPrescriptionExport($request), 'digimed/images/prescription-excel/'.$fileName, 's3');
                $S3Library = new \App\Library\S3Library;
                $digimedFile = ($S3Library->s3Url($fileName, null, 'digimed/images/prescription-excel'));
            } else {
                Excel::store(new AdminPrescriptionExport($request),'public/images/prescription-excel/'.$fileName,'local');
                $digimedFile = Storage::url('app/public/images/prescription-excel/'.$fileName);
            }
            $result = [ 'url' => $digimedFile ];
            return self::sentResponse(200, $result, __('digimed_validation.success_response.data_fetch_success'));
        } catch(Exception | Throwable | QueryException $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }

    public function adminPrescriptionListPdf(Request $request)
    {
        try {
            $paginate = $request->count_per_page ? $request->count_per_page : 10;
            $pageNumber = $request->page ? $request->page : 1;
            $search_key = $request->search ? $request->search : '';
            
            $sort_by_col = (isset($request->sort_by)) ? $request->sort_by : 'id';
            $data_order_by = $request->order_by;
            /** @var string $data_order_by */
            $orderBy = $data_order_by ? strtoupper($data_order_by) : strtoupper('asc');

            $list = Prescription::with(['appointment','appointment.patientDetails','appointment.doctorDetails','prescriptionRequests'])->whereHas('appointment', function($q){
                $q->where('appointment_status', AppoitmentStatusEnum::COMPLETED());
                $q->where('consultation_end_time', '!=', NULL);
            })
            ->has('prescriptionRequests')
            ->where('status', '1');

            if(!empty($search_key)) {
                $list = $list->where(function($q) use($search_key) {
                    $q->where('prescription_code', 'LIKE', "%{$search_key}%");
                    $q->orWhereHas('appointment.patientDetails',function($r) use($search_key) {
                        $r->where('first_name', 'LIKE', "%{$search_key}%");
                        $r->orWhere('last_name', 'LIKE', "%{$search_key}%");
                        $r->orWhere('passport_number', 'LIKE', "%{$search_key}%");
                    });
                    $q->orWhereHas('appointment.doctorDetails',function($r) use($search_key) {
                        $r->where('first_name', 'LIKE', "%{$search_key}%");
                        $r->orWhere('last_name', 'LIKE', "%{$search_key}%");
                        $r->orWhere('passport_number', 'LIKE', "%{$search_key}%");
                    });
                    $q->orWhereHas('prescriptionRequests.pharmacy_details',function($r) use($search_key) {
                        $r->where('name', 'LIKE', "%{$search_key}%");
                    });
                });
            }

            if($sort_by_col) {
                /**
                 * @var string $sort_by_col
                 * @var string $orderBy
                 */
                $list = $list->orderBy($sort_by_col, $orderBy);
            }

            $list = $list->get();
            $web_settings = WebSetting::find(1);
            $contact_email = $web_settings->contact_email;
            $website = $web_settings->website;
            $file_name = 'pdf_'.date('Y-m-d H:i:s').'.pdf';
            if(Config::get('filesystems.default') == "s3") {
                $logo_image = Storage::temporaryUrl('digimed/images/assets/img/logo.svg', now()->addMinutes(30));
            } else {
                $logo_image = Storage::disk('public')->url('images/logo.png');
            }
            $list_pdf = PDF::loadView('pdf.admin_prescription_list_pdf', compact('logo_image','list','contact_email','website'));
            // echo $list_pdf->stream();
            // die;
            if(Config::get('filesystems.default') == "s3") {
                Storage::disk('s3')->put('digimed/images/prescription-pdf/'.$file_name, $list_pdf->output());
            }
            else{
                Storage::put('prescription-pdf/'.$file_name, $list_pdf->output());
            }
            $S3Library = new \App\Library\S3Library;
            $digimedFile = ($S3Library->s3Url($file_name, null, 'digimed/images/prescription-pdf'));
            $result = [ 'url' => $digimedFile ];
            return self::sentResponse(200, $result, __('digimed_validation.success_response.data_fetch_success'));
        } catch(Exception | Throwable | QueryException $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }

    public function sendPrescriptionWeno(AppointmentDetailRequest $request)
    {
        try {
            $appointment = Appointment::with(['patientDetails','doctorDetails.userDetail'])->find($request->appointment_id);
            $wenoResponse = $this->sendWenoCall($appointment);
            $prescription = Prescription::where('appointment_id',$request->appointment_id)->latest()->first();
            $prescriptionRequest = PrescriptionRequest::where('prescription_id',$prescription->id)->latest()->first();
            $prescriptionRequest->weno_response = json_encode($wenoResponse);
            $prescriptionRequest->save();
            
            return self::sentResponse(200, ['weno_response' => $wenoResponse], __('digimed_validation.success_response.data_update_success'));
        } catch(Exception | Throwable | QueryException $e) {
            return self::sentResponse(500, [], $e->getMessage());
        }
    }

    public function sendWenoCall($appointment) {
        $Wsdl = 'https://cert.wenoexchange.com/wenox/service.asmx?WSDL';
        libxml_disable_entity_loader(false); //adding this worked for me

        $prescription_data = json_decode($appointment->prescription_data);
        $prescription_data = json_decode($prescription_data);

        $message = '<Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" DatatypesVersion="20170715" TransportVersion="20170715" TransactionDomain="SCRIPT" TransactionVersion="20170715" StructuresVersion="20170715" ECLVersion="20170715">
                  <Header>
                    <To Qualifier="P">7654321</To>
                    <From Qualifier="D">D111111:C111111</From>
                    <MessageID>'.Carbon::now()->format('YmdHiss').'</MessageID>
                    <SentTime>'.Carbon::now()->format('Y-m-d').'T'.Carbon::now()->format('H:i:s.s').'</SentTime>
                    <Security>
                      <UsernameToken>
                        <Username>1282</Username>
                        <Password Type="PasswordDigest">B7DA0F04952041ABE3FDF3797CA13F9B</Password>
                      </UsernameToken>
                    </Security>
                    <SenderSoftware>
                      <SenderSoftwareDeveloper>Digital EyeCare Associates</SenderSoftwareDeveloper>
                      <SenderSoftwareProduct>Restore Vision</SenderSoftwareProduct>
                      <SenderSoftwareVersionRelease>V1</SenderSoftwareVersionRelease>
                    </SenderSoftware>
                    <DigitalSignature Version="F">
                      <DigitalSignatureIndicator>0</DigitalSignatureIndicator>
                    </DigitalSignature>
                  </Header>
                  <Body>
                    <NewRx>
                      <Patient>
                        <HumanPatient>
                          <Name>
                            <LastName>'.ucwords($appointment->patientDetails->last_name).'</LastName>
                            <FirstName>'.ucwords($appointment->patientDetails->first_name).'</FirstName>
                          </Name>
                          <Gender>'.ucwords(substr($appointment->patientDetails->gender, 0, 1)).'</Gender>
                          <DateOfBirth>
                            <Date>'.Carbon::parse($appointment->patientDetails->dob)->format('Y-m-d').'</Date>
                          </DateOfBirth>
                          <Address>
                            <AddressLine1>'.$appointment->patientDetails->address.'</AddressLine1>
                            <City>'.$appointment->patientDetails->city_data->name.'</City>
                            <StateProvince>'.$appointment->patientDetails->state_data->name.'</StateProvince>
                            <PostalCode>'.$appointment->patientDetails->post_code.'</PostalCode>
                            <CountryCode>US</CountryCode>
                          </Address>
                          <CommunicationNumbers>
                            <PrimaryTelephone>
                              <Number>'.$appointment->patientDetails->mobile_number.'</Number>
                            </PrimaryTelephone>
                          </CommunicationNumbers>
                        </HumanPatient>
                      </Patient>
                      <Pharmacy>
                            <Identification>
                                <NCPDPID>5936387</NCPDPID>
                                <NPI>1891468526</NPI>
                            </Identification>
                            <Specialty>Compound</Specialty>
                            <BusinessName>Primera Compounding</BusinessName>
                            <Address>
                                <AddressLine1>30444 Southwest Freeway Bldg H,Suite 111</AddressLine1>
                                <City>Rosenberg</City>
                                <StateProvince>TX</StateProvince>
                                <PostalCode>77471</PostalCode>
                                <CountryCode>US</CountryCode>
                            </Address>
                            <CommunicationNumbers>
                                <PrimaryTelephone>
                                <Number>8886081740</Number>
                                </PrimaryTelephone>
                                <Fax>
                                    <Number>3463214500</Number>
                                </Fax>
                            </CommunicationNumbers>
                    </Pharmacy>
                      <Prescriber>
                        <NonVeterinarian>
                        <Identification>
                          <StateLicenseNumber>TX567567</StateLicenseNumber>
                          <DEANumber>AP1234563</DEANumber>
                          <NPI>NPI111111</NPI>
                        </Identification>
                        <Name>
                          <LastName>'.ucwords($appointment->doctorDetails->last_name).'</LastName>
                          <FirstName>'.ucwords($appointment->doctorDetails->first_name).'</FirstName>
                          <Suffix>MD</Suffix>
                        </Name>
                        <Address>
                          <AddressLine1>'.$appointment->doctorDetails->address.'</AddressLine1>
                          <City>'.$appointment->doctorDetails->city_data->name.'</City>
                          <StateProvince>'.$appointment->doctorDetails->state_data->name.'</StateProvince>
                          <PostalCode>'.$appointment->doctorDetails->post_code.'</PostalCode>
                          <CountryCode>US</CountryCode>
                        </Address>
                        <CommunicationNumbers>
                          <PrimaryTelephone>
                            <Number>'.$appointment->doctorDetails->mobile_number.'</Number>
                          </PrimaryTelephone>
                        </CommunicationNumbers>
                        </NonVeterinarian>
                      </Prescriber>
                      <MedicationPrescribed>
                        <DrugDescription>'.$prescription_data->description.' / '.$prescription_data->details.'</DrugDescription>
                        <DrugCoded>
                          <DrugDBCode>
                            <Code>1247386</Code>
                            <Qualifier>SCD</Qualifier>
                          </DrugDBCode>
                          <DEASchedule>
                            <Code>C38046</Code>
                          </DEASchedule>
                        </DrugCoded>';
                        if(!empty($prescription_data->qty)) {
                            foreach ($prescription_data->qty as $key => $qty) {
                                if ($key == array_key_first($prescription_data->qty)) {
                                    $message .= '<Quantity>
                                                  <Value>'.$qty->data->id.'</Value>
                                                  <CodeListQualifier>38</CodeListQualifier>
                                                  <QuantityUnitOfMeasure>
                                                    <Code>C48542</Code>
                                                  </QuantityUnitOfMeasure>
                                                </Quantity>';
                                }
                            }
                        }
                $message .= '<DaysSupply>10</DaysSupply>
                        <WrittenDate>
                          <DateTime>'.Carbon::now()->format('Y-m-d').'T'.Carbon::now()->format('H:i:s').'</DateTime>
                        </WrittenDate>
                        <Substitutions>0</Substitutions>';
                        if(!empty($prescription_data->refill))
                            $message .= '<NumberOfRefills>'.$prescription_data->refill.'</NumberOfRefills>';
                        else
                            $message .= '<NumberOfRefills>0</NumberOfRefills>';
            $message .= '<Note>Patient likes a certain generic please accommodate if you can</Note>';
                        if(!empty($prescription_data->sig)) {
                            foreach ($prescription_data->sig as $key => $sig) {
                                if ($key == array_key_first($prescription_data->sig)) {
                                    if(strtolower($sig->data->name) != 'other') {
                                        $message .= '<Sig>
                                                      <SigText>'.$sig->data->name.'</SigText>
                                                    </Sig>';
                                    }
                                }
                            }
                        }
            $message .= '<OtherMedicationDate>
                          <OtherMedicationDate>
                            <Date>'.Carbon::now()->format('Y-m-d').'</Date>
                          </OtherMedicationDate>
                          <OtherMedicationDateQualifier>EffectiveDate</OtherMedicationDateQualifier>
                        </OtherMedicationDate>
                      </MedicationPrescribed>
                    </NewRx>
                  </Body>
                </Message>';
         
        $soapclient = new SoapClient($Wsdl);
        $param=array('inputString' => $message);
        $response =$soapclient->wenoswitch($param);
        $array = json_decode(json_encode($response), true); 
        foreach($array as $item)
        {    
            // print_r($item);
        }
        return $array;
    }
}