HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
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/vhost/disk-apps/dev-telemedicina.teky.com.co/app/Http/Controllers/AgendaController.php
<?php

namespace Telemedicina\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use Telemedicina\User;
use Telemedicina\Event;
use Telemedicina\TemplateResponse;
use Telemedicina\AgendaType;
use Calendar;
use DateTime;
use Validator;
use Session;
use Carbon\Carbon;
use Config;
use Telemedicina\PaymentTransaction;
use Telemedicina\HeaderValue;
use Telemedicina\Insurance;
use Telemedicina\Specialty;
use Illuminate\Support\Facades\Mail;
use Telemedicina\Mail\ConsentEmail;
use Telemedicina\Mail\TransactionEmail;
use PHPJasper\PHPJasper;
use Illuminate\Support\Facades\Storage;
use Telemedicina\FileAttach;

class AgendaController extends Controller
{

    public function addEvent(Request $request){
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
            'medic_id' => 'required',
            'agenda_type_id' => 'required',
            'event_date' => 'required',
            'end_time' => 'required'
        ]);

        if ($validator->fails()) {
            Session::flash('warning', __('agenda.validation.all_fields'));
            return Redirect::to('/agenda')->withInput()->withErrors($validator);
        }

        // If current user is medic, this date is for him.
        if(Auth::user()->rol->id == 3 || Auth::user()->rol->id == 6){
            $medic_id =Auth::user()->id;
        }

        $event = new Event;
        $event->user_id = $request['user_id'];
        $event->medic_id = $request['medic_id'];
        $event->agenda_type_id = $request['agenda_type_id'];
        $event->event_date = $request['event_date'];
        $event->start_time = $request['start_time'];
        $event->end_time = $request['end_time'];
        $event->specialty_id = $request['specialty_id'];
        $event->rate = $request['rate'];
        $event->send_consent = $request['send_consent'] == "on" ? true : false;
        $event->send_payment = $request['send_payment'] == "on" ? true : false;
        $event->header_value_id = $request['header_value_id'];
        $event->save();

        // Create pending transaction if true.
        if($event->send_payment && intval($event->rate) > 0){
            $this->createTransaction($request['user_id'], $request['rate'], $event, $request['medic_id']);
        }

        // Send Consent to User via email if true.
        if($event->send_consent){
            $this->sendConsentToUser($event->user_id, $request['medic_id']);
        }


        // Notify user.
        $tags = array(
            ["field" => "tag", "key" => "user_id", "relation" => "=", "value" => $request["user_id"]],
            ["field" => "tag", "key" => "app_name", "relation" => "=", "value" => Config::get('app.name')]
        );

        $data = array(
            "type" => "scheduling_detail",
            "id" => $event->id
        );

        try{
            $message = __('messages.agenda.notification_text');

            $message = str_replace('<date>', Carbon::parse($request['event_date'])->format('d/m/Y'), $message);
            $message = str_replace('<time>', $request['start_time'], $message);

            OneSignalController::sendToTags($message, $tags, null, $data, null, null, 'U');
        }
        catch(\Exception $e){}


        Session::flash('success', __('agenda.event_created'));
        return Redirect::to('/agenda');
    }

    public function uploadConsent(Request $request){
        $user_id = Auth::user()->id;
        $event_id = $request->event_id;
        
        $year = date('Y');
        $month = date('m');
        $day = date('d');

        //** subir archivo a S3 */  
        $filenamewithextension = $request->file('file')->getClientOriginalName();
        $filename = pathinfo($filenamewithextension, PATHINFO_EXTENSION);

        $filenametostore =  $user_id . '/'. $year . '/' . $month . '/' . $day."/".uniqid().".".$filename;
        Storage::disk('s3')->put(env('S3_CONSENTS_PATH').$filenametostore, fopen($request->file('file'), 'r+'), 'public');

        $event = Event::where('id', $event_id)->first();
        $event->consent_file = $filenametostore;

        $event->update();

        return $filenametostore;
    }

    public function createTransaction($user_id, $rate, $event, $medic_id){
        $t = new PaymentTransaction;
        $t->rate = $rate;
        $t->user_id = $user_id;
        $t->event_id = $event->id;
        $t->transaction_state = 'PENDING';
        $t->transaction_id = '';
        $t->signature = $this->generateRandomString(10) . '-' . time();

        $t->save();

        // Send Email with key to make payment.
        $this->sendTransactionEmail($user_id, $t, $event, $medic_id);
    }

    function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function sendConsentToUser($user_id, $medic_id){
        // Send email.
        $user = User::where('id', $user_id)->first();
        $medic = User::where('id', $medic_id)->with('centro')->with('specialty')->first();

        $resultPDF = $this->generateConsentSpecialty($user, $medic);
        Mail::to($user->email)->send(new ConsentEmail($user, $resultPDF));
    }

    public function sendTransactionEmail($user_id, $agenda_transaction, $event, $medic_id){
        // Send transaction
        $user = User::where('id', $user_id)->first();
        $medic = User::where('id', $medic_id)->with('centro')->with('specialty')->first();

        Mail::to($user->email)->send(new TransactionEmail($user, $agenda_transaction, $event, $medic));
    }

    public function getDateInformation($event_id){
        $agendaTransaction = PaymentTransaction::where('event_id', $event_id)->first();
        $event = Event::where('id', $event_id)->with('user','event_state_option')->first();
        $paymentReceived = false;
        $consentReceived = false;
        $apply_payment = false;

        if($agendaTransaction && $agendaTransaction->transaction_state){
            $paymentReceived = true;
            $apply_payment = true;
        }

        if($event->consent_file){
            $consentReceived = true;
        }

        return [
            'not_apply_payment' => $apply_payment,
            'payment_received'  => $paymentReceived,
            'consent_received'  => $consentReceived,
            'event_file_id' => ($event->consent_file ? $event->id : null),
            'header_value_id' => $event->header_value_id,
            'event' => $event
        ];
    }

    public function getEventInformation($event_id){
        $event = Event::where('id', $event_id)->with('user','event_state_option')->get();
        return response()->json($event);
    }

    public function generateConsentSpecialty($user, $medic){
        $name_file = 'Consent-' . $user->document . '-' . $medic->document;
        $jasper = base_path('').'/public/Consentimiento.jasper';
        $output = base_path('')."/public/reports/".$name_file;

        $options = [
            'format' => ['pdf'],
            'locale' => 'es',
            'params' => [
                'labelnombrepaciente' => $user->name . ' ' . $user->last_name,
                'labelceduladelpaciente' => $user->document,
                'labeltipodedocumento' => $user->identification_type->name,
                'labelmedico' => $medic->name . ' ' . $medic->last_name,
                'labelnombrehospital' => $medic->centro->name,
                'labelciudad' => $user->city ? $user->city->name : '',
                'labelfecha' => Carbon::now()->format('d-m-Y'),
            ]
        ];

        $jasperProcess = new PHPJasper;
        $jasperProcess->process(
            $jasper,
            $output,
            $options
        )->execute();

        
        $file = $output . '.pdf';

        if (!file_exists($file)) {
            abort(404);
        }

        $pdf_url = env('APP_URL').'/reports/'.$name_file.'.pdf';
        return [ $pdf_url, $name_file ];
    }

    public function removeEvent(Request $request){
        $e = Event::where('id', $request->event_id)->first();
        $e->active = false;
        $e->save();

        // Notify user.
        $tags = array(
            ["field" => "tag", "key" => "user_id", "relation" => "=", "value" => $e->user_id],
            ["field" => "tag", "key" => "app_name", "relation" => "=", "value" => Config::get('app.name')]
        );

        try{
            $message = __('messages.agenda.cancel_notification');

            $message = str_replace('<date>', Carbon::parse($e->event_date)->format('d/m/Y'), $message);
            $message = str_replace('<time>', $e->start_time, $message);

            OneSignalController::sendToTags($message, $tags, null, null, null, null, 'U');
        } catch(\Exception $e) {}
    }

    public function getMedicsBySpecialty($specialty_id){
        $medics = User::where('specialty_id', $specialty_id)->where('active', true)->get();
        return $medics;
    }

    public function getProposalDataAgenda($header_id){
        $header = HeaderValue::where('id', $header_id)
                    ->with('form')            
                    ->first();

        $specialty_id = $header->form->specialty_id;
        $user = User::where('id', $header->user_id)->select('id', 'name', 'last_name', 'document', 'insurance_id')->first();
        $insurance = Insurance::where('id', $user->insurance_id)->first();
        $rate = $insurance ? $insurance->rate : 0;

        $reponse = array(
            'specialty_id' => $specialty_id, 
            'user' => $user, 
            'rate' => $rate,
            'header_id' => $header_id,
            'medic_id' => $header->suggested_medic_id
        );

        return $reponse;
    }

    public function showConsentFile($id){
        $file = Event::find($id);
        $url = Storage::disk('s3')->temporaryUrl(
            env('S3_CONSENTS_PATH') . $file->consent_file, Carbon::now()->addSeconds(5)
        );
        return redirect($url);
    }
}