<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Patients;
use App\Models\MedicalReport;
use App\Models\MedicalRecipe;
use DateTime;
use App\BloodTypes\BloodTypes;
use App\Exceptions\GlobalException;
use App\Helper\Helper;
use Illuminate\Support\Facades\Auth;
use App\Helper\ClinicIdentityHelper;
use App\Exports\PatientExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Especiality;

use Throwable;

class PatientController extends Controller
{
    /**
     * Tipos de sangre válidos
     */
    private const BLOOD_TYPES = [
        'A+' => 'A+',
        'A-' => 'A-',
        'B+' => 'B+',
        'B-' => 'B-',
        'O+' => 'O+',
        'O-' => 'O-',
        'AB+' => 'AB+',
        'AB-' => 'AB-'
    ];

    /**
     * 
     */
    public function view(Request $request){
       try{
            $patients = Patients::orderBy('created_at', 'desc')->get();
            return view("view-patients", ['patients' => $patients]);
       }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }


    /**
     * 
     */
    public function viewMedicalReports(Request $request){
        try{
             $data = $request->all();
             $patientId = $data["patientId"];
             session([config('constants.keysSessions.medicalReportsIdPatient') => $patientId]);
             $model = Patients::find( $patientId);
             if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
             
             // Obtener los informes médicos del paciente
             $medicalReports = MedicalReport::where("patients_id", $patientId)
                                ->orderBy('created_at', 'DESC')
                                ->get();
             
             return view("view-medical-reports",[
                "model" => $model,
                "patientName" => $model->firstname . " " . $model->lastname,
                "medicalReports" => $medicalReports,
                "showButtonCreateMedicalReport" => Auth::user()->isAbleTo('create-medical-report')
            ]);
        }catch (Throwable $th) {
             throw new GlobalException($th->getMessage());
         }
     }


     
    /**
     * 
     */
    public function viewMedicalRecipes(Request $request){
        try{
             $data = $request->all();
             $patientId = $data["patientId"];
             session([config('constants.keysSessions.medicalRecipesIdPatient') => $patientId]);
             $model = Patients::find( $patientId);
             if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
             return view("view-medical-recipes",[
                "model"=>$model
            ]);
        }catch (Throwable $th) {
             throw new GlobalException($th->getMessage());
         }
     }

    

    /**
     * 
     */
    public function detail(Request $request){
        try{
            $data = $request->all();
            $id = $data["id"];
            $model = Patients::find($id);
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));

            session([config('constants.keysSessions.medicalReportsIdPatient') => $model->id]);

            return view("detail-patient",[
                "model"=>$model,
                "exist"=>(isset($data["exist"]) && ($data["exist"] === "1")) ? "1" : "0"
            ]);
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

     /**
     * 
     */
    public function updateMedicalReport(Request $request){
        try{
            $data = $request->all();
            $id = $data["id"];
            $patientId = $data["patientId"];
            $model = Patients::find($patientId);
            $medicalReport =  MedicalReport::find($id);
            $description =  isset($data["description"]) ? $data["description"] : $medicalReport->description;
            
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
            if(!($request->method() === "POST")){
                $especialities = Especiality::all();
                return view("create-medical-report",[
                    "id"=>$id,
                    "model"=>$model,
                    "isUpdate"=>1,
                    "patientName"=>$model->firstname . " " . $model->lastname,
                    "description"=>$description,
                    "specialities"=>$especialities 
                ]);
            }else{
                $medicalReport->especiality = $data["specialities"];
                $medicalReport->description = $data["description"];
                $medicalReport->save();
                
                return redirect()->route("/admin/view-medical-reports",[
                    "patientId"=>$patientId
                ]);
            }
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

     /**
     * 
     */
    public function createMedicalReport(Request $request){
        try{
            $data = $request->all();
            $id = $data["patientId"];
            $model = Patients::find($id);
            $medicalReport = new MedicalReport();
            $specialities = Especiality::all();
            
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
            if(!($request->method() === "POST")){
                return view("create-medical-report",[
                    "model"=>$model,
                    "isUpdate"=>0,
                    "patientName"=>$model->firstname . " " . $model->lastname,
                    "description"=>"",
                    "specialities"=>$specialities 
                ]);
            }else{
                //se crea el registro
                $timeid = date('YmdHisu'); 
                $medicalReport->id = md5($data["description"] . $timeid);
                $medicalReport->patients_id = $model->id;
                $medicalReport->users_id = Auth::user()->id;
                $medicalReport->description = $data["description"];
                $medicalReport->especiality = $data["specialities"];

                $medicalReport->save();
                $description =  $data["description"];
                return redirect()->route("/admin/download-medical-report-preview",[
                    "id"=>$medicalReport->id,
                    "description"=>$description,
                    "patientId"=>$model->id,
                    "patientName"=>$model->firstname . " " . $model->lastname,
                    "especiality"=>$data["specialities"] 
                ]);
            }
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

     /**
     * 
     */
    public function createMedicalRecipes(Request $request){
        try{
            $data = $request->all();
            $id = $data["patientId"];
            $model = Patients::find($id);
            $medicalRecipe = new MedicalRecipe();
            
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
            if(!($request->method() === "POST")){
                return view("create-medical-recipe",[
                    "model"=>$model,
                    "isUpdate"=>0,
                    "patientName"=>$model->firstname . " " . $model->lastname,
                    "description"=>"" 
                ]);
            }else{
                //se crea el registro
                $timeid = date('YmdHisu'); 
                $medicalRecipe->id = md5($data["description"] . $timeid);
                $medicalRecipe->patients_id = $model->id;
                $medicalRecipe->users_id = Auth::user()->id;
                $medicalRecipe->description = $data["description"];

                $medicalRecipe->save();
                $description =  $data["description"];
                return redirect()->route("/admin/download-medical-recipe-preview",[
                    "id"=>$medicalRecipe->id,
                    "description"=>$description,
                    "patientId"=>$model->id,
                    "patientName"=>$model->firstname . " " . $model->lastname 
                ]);
            }
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }


      /**
     * 
     */
    public function updateMedicalRecipes(Request $request){
        try{
            $data = $request->all();
            $id = $data["id"];
            $patientId = $data["patientId"];
            $model = Patients::find($patientId);
            $medicalRecipe =  MedicalRecipe::find($id);
            $description =  isset($data["description"]) ? $data["description"] : $medicalRecipe->description;
            
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
            if(!($request->method() === "POST")){
                return view("create-medical-recipe",[
                    "id"=>$id,
                    "model"=>$model,
                    "isUpdate"=>1,
                    "patientName"=>$model->firstname . " " . $model->lastname,
                    "description"=>$description 
                ]);
            }else{
                $medicalRecipe->description = $data["description"];
                $medicalRecipe->save();
                
                return redirect()->route("/admin/view-medical-recipes",[
                    "patientId"=>$patientId
                ]);
            }
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }



    /**
     * 
     */
    public function downloadMedicalReportPreview(Request $request){
        try{
            $data = $request->all();
            $id = $data["id"];
            $description = $data["description"];
            $patientId = $data["patientId"];
            $patientName = $data["patientName"];
            if(isset($data["especiality"])){
                $especiality = Especiality::find($data["especiality"])->name;
            }else{
                $especiality = "";
            }
            $model = Patients::find($patientId);
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
                return view("download-medical-report-preview",[
                    "id"=>$id,
                    "description"=>$description,
                    "model"=>$model,
                    "patientName"=>$patientName,
                    "patientId"=>$patientId,
                    "especiality"=>$especiality
                ]);
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

     /**
     * 
     */
    public function downloadMedicalRecipesPreview(Request $request){
        try{
            $data = $request->all();
            $id = $data["id"];
            $description = $data["description"];
            $patientId = $data["patientId"];
            $patientName = $data["patientName"];
            $model = Patients::find($patientId);
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
                return view("download-medical-recipe-preview",[
                    "id"=>$id,
                    "description"=>$description,
                    "model"=>$model,
                    "patientName"=>$patientName,
                    "patientId"=>$patientId
                ]);
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }



     /**
     * 
     */
    public function downloadMedicalReport(Request $request){
        try{
            $data = $request->all();
            $id = $data["id"];
            $format = ".docx";
            $model = MedicalReport::find($id);
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
            header("Content-Description: File Transfer");
            header('Content-Disposition: attachment; filename="REPORT-'.$model->patient()->first()->firstname ." ".$model->patient()->first()->lastname.$format.'"');
            header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
            header('Content-Transfer-Encoding: binary');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Expires: 0');
            $objWriter = new \PhpOffice\PhpWord\TemplateProcessor($_SERVER['DOCUMENT_ROOT'] . "/template-base-solidclinic360.docx");
            
            // Agregar datos de identidad del consultorio
            $identity = ClinicIdentityHelper::getActiveIdentity();
            if ($identity) {
                // Crear un encabezado más elegante
                $headerText = '';
                
                // Añadir logo de identidad si existe
                if ($identity->logo_path && file_exists(storage_path('app/public/' . $identity->logo_path))) {
                    $logoPath = storage_path('app/public/' . $identity->logo_path);
                    try {
                        // Reemplazamos la imagen placeholder directamente
                        $objWriter->setImageValue('header_logo', [
                            'path' => $logoPath,
                            'width' => 150,
                            'height' => 75,
                            'ratio' => true
                        ]);
                    } catch (\Exception $e) {
                        // Si hay error al insertar el logo, continuar sin él
                    }
                }
                
                $headerText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                $headerText .= '<w:r><w:rPr><w:b/><w:sz w:val="28"/><w:color w:val="2A4E6D"/></w:rPr><w:t>'.$identity->name.'</w:t></w:r>';
                $headerText .= '</w:p>';
                
                if ($identity->specialty) {
                    $headerText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                    $headerText .= '<w:r><w:rPr><w:i/><w:sz w:val="24"/><w:color w:val="4A90E2"/></w:rPr><w:t>'.$identity->specialty.'</w:t></w:r>';
                    $headerText .= '</w:p>';
                }
                $addressText = '';
                $addressText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                $addressText .= '<w:r><w:rPr><w:sz w:val="20"/><w:color w:val="2A4E6D"/></w:rPr><w:t>'.$identity->address.'</w:t></w:r>';
                $addressText .= '</w:p>';
                
                if ($identity->phone || $identity->email) {
                    $addressText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                    $contactText = '';
                    if ($identity->phone) {
                        $contactText .= 'Tel: '.$identity->phone;
                    }
                    if ($identity->phone && $identity->email) {
                        $contactText .= ' | ';
                    }
                    if ($identity->email) {
                        $contactText .= 'Email: '.$identity->email;
                    }
                    $addressText .= '<w:r><w:rPr><w:sz w:val="20"/><w:color w:val="2A4E6D"/></w:rPr><w:t>'.$contactText.'</w:t></w:r>';
                    $addressText .= '</w:p>';
                }
                
                // Título del documento
                $titleText = '<w:p><w:pPr><w:jc w:val="center"/><w:spacing w:before="400" w:after="300"/></w:pPr>';
                $titleText .= '<w:r><w:rPr><w:b/><w:sz w:val="32"/><w:color w:val="2A4E6D"/></w:rPr><w:t>'.__("detail-patient.medicalReport").'</w:t></w:r>';
                $titleText .= '</w:p>';
                
                // Agregar más espacio después del título
                $titleText .= '<w:p><w:pPr><w:spacing w:before="100" w:after="100"/></w:pPr></w:p>';

                $dataPatient ="";
                
                // Datos del paciente
                $patient = $model->patient()->first();
                if ($patient) {
                    $dataPatient .= '<w:p><w:pPr><w:spacing w:before="400"/></w:pPr>';
                    $dataPatient .= '<w:r><w:rPr><w:b/></w:rPr><w:t>'.__("detail-patient.patient").' </w:t></w:r>';
                    $dataPatient .= '<w:r><w:t>'.$patient->firstname.' '.$patient->lastname.'</w:t></w:r>';
                    $dataPatient .= '</w:p>';
                    $dataPatient .= '<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Fecha: </w:t></w:r><w:r><w:t>'.date('d/m/Y').'</w:t></w:r></w:p>';
                }
                
                $dataPatient .= '<w:p><w:pPr><w:spacing w:before="200" w:after="200"/></w:pPr></w:p>';

                $objWriter->setValue('title', $titleText);
                $objWriter->setValue('data_patient', $dataPatient);
                $objWriter->setValue('header', $headerText);
            } else {
                $objWriter->setValue('header', '');
            }
            
            // Contenido del informe con formato mejorado
            $content = '<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>' . str_replace("\n", '</w:t></w:r></w:p><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>', $model->description) . '</w:t></w:r></w:p>';
            $objWriter->setValue('content', $content);
            
            // Agregar firma digital del doctor si existe
            $doctor = $model->user()->first();
            $footerText = '';
            $signatureText = '';
            
            if ($doctor) {
                // Espacio para firma
                $footerText .= '<w:p><w:pPr><w:spacing w:before="400"/><w:jc w:val="center"/></w:pPr>';
                // Obtener nombre completo del doctor desde el perfil
                $doctorName = $doctor->name; // Valor predeterminado
                $doctorProfile = $doctor->profile ?? null;
                if ($doctorProfile && !empty($doctorProfile->firstname) && !empty($doctorProfile->lastname)) {
                    $doctorName = $doctorProfile->firstname . ' ' . $doctorProfile->lastname;
                }
                // Agregar nombre del doctor encima de la firma
                $footerText .= '<w:r><w:rPr><w:b/><w:color w:val="4A90E2"/></w:rPr><w:t>Dr. '.$doctorName.'</w:t></w:r>';
                $footerText .= '</w:p>';
                
                // Verificar si el doctor tiene firma digital
                if ($doctor->hasDigitalSignature()) {
                    // Añadir la imagen de la firma
                    try {
                        // Intentar añadir la imagen de la firma al documento
                        $signaturePath = storage_path('app/public/signatures/' . $doctor->signature_path);
                        if (file_exists($signaturePath)) {
                            $signatureText = '<w:p><w:pPr><w:jc w:val="center"/><w:spacing w:before="0" w:after="0"/></w:pPr>';
                            $objWriter->setImageValue('signature', [
                                'path' => $signaturePath,
                                'width' => 100,
                                'height' => 50,
                                'ratio' => false
                            ]);
                            $signatureText .= '</w:p>';
                            
                            // Añadir texto de validación de firma digital
                            $signatureText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                            $signatureText .= '<w:r><w:rPr><w:i/><w:sz w:val="16"/><w:color w:val="4A90E2"/></w:rPr>';
                            $signatureText .= '<w:t>Documento firmado digitalmente</w:t></w:r>';
                            $signatureText .= '</w:p>';
                        } else {
                            // Si no se encuentra el archivo, agregar solo el texto
                            $signatureText = '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                            $signatureText .= '<w:r><w:rPr><w:i/><w:sz w:val="16"/><w:color w:val="4A90E2"/></w:rPr>';
                            $signatureText .= '<w:t>Documento firmado digitalmente</w:t></w:r>';
                            $signatureText .= '</w:p>';
                        }
                    } catch (\Exception $e) {
                        // Si hay un error al insertar la imagen, usar solo texto
                        $signatureText = '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                        $signatureText .= '<w:r><w:rPr><w:i/><w:sz w:val="16"/><w:color w:val="4A90E2"/></w:rPr>';
                        $signatureText .= '<w:t>Documento firmado digitalmente</w:t></w:r>';
                        $signatureText .= '</w:p>';
                    }
                }
            }
            
            
            $objWriter->setValue('signature', $signatureText);
            $objWriter->setValue('footer', $footerText);
            $objWriter->setValue('address', $addressText);
            $objWriter->saveAs("php://output");
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

     /**
     * 
     */
    public function downloadMedicalRecipes(Request $request){
        try{
            $data = $request->all();
            $id = $data["id"];
            $format = ".docx";
            $model = MedicalRecipe::find($id);
            if($model === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
            header("Content-Description: File Transfer");
            header('Content-Disposition: attachment; filename="RECIPE-'.$model->patient()->first()->firstname ." ".$model->patient()->first()->lastname.$format.'"');
            header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
            header('Content-Transfer-Encoding: binary');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Expires: 0');
            $objWriter = new \PhpOffice\PhpWord\TemplateProcessor($_SERVER['DOCUMENT_ROOT'] . "/template-base-solidclinic360.docx");
            
            // Agregar datos de identidad del consultorio
            $identity = ClinicIdentityHelper::getActiveIdentity();
            if ($identity) {
                // Crear un encabezado más elegante
                $headerText = '';
                
                // Añadir logo de identidad si existe
                if ($identity->logo_path && file_exists(storage_path('app/public/' . $identity->logo_path))) {
                    $logoPath = storage_path('app/public/' . $identity->logo_path);
                    try {
                        // Reemplazamos la imagen placeholder directamente
                        $objWriter->setImageValue('header_logo', [
                            'path' => $logoPath,
                            'width' => 150,
                            'height' => 75,
                            'ratio' => true
                        ]);
                    } catch (\Exception $e) {
                        // Si hay error al insertar el logo, continuar sin él
                    }
                }
                
                $headerText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                $headerText .= '<w:r><w:rPr><w:b/><w:sz w:val="28"/><w:color w:val="2A4E6D"/></w:rPr><w:t>'.$identity->name.'</w:t></w:r>';
                $headerText .= '</w:p>';
                
                if ($identity->specialty) {
                    $headerText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                    $headerText .= '<w:r><w:rPr><w:i/><w:sz w:val="24"/><w:color w:val="4A90E2"/></w:rPr><w:t>'.$identity->specialty.'</w:t></w:r>';
                    $headerText .= '</w:p>';
                }
                
                $addressText = '';
                $addressText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                $addressText .= '<w:r><w:rPr><w:sz w:val="20"/><w:color w:val="2A4E6D"/></w:rPr><w:t>'.$identity->address.'</w:t></w:r>';
                $addressText .= '</w:p>';
                
                if ($identity->phone || $identity->email) {
                    $addressText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                    $contactText = '';
                    if ($identity->phone) {
                        $contactText .= 'Tel: '.$identity->phone;
                    }
                    if ($identity->phone && $identity->email) {
                        $contactText .= ' | ';
                    }
                    if ($identity->email) {
                        $contactText .= 'Email: '.$identity->email;
                    }
                    $addressText .= '<w:r><w:rPr><w:sz w:val="20"/><w:color w:val="2A4E6D"/></w:rPr><w:t>'.$contactText.'</w:t></w:r>';
                    $addressText .= '</w:p>';
                }
                
                // Título del documento
                $headerText .= '<w:p><w:pPr><w:jc w:val="center"/><w:spacing w:before="300" w:after="300"/></w:pPr>';
                $headerText .= '<w:r><w:rPr><w:b/><w:sz w:val="32"/><w:color w:val="2A4E6D"/></w:rPr><w:t>'.__("detail-patient.medicalRecipe").'</w:t></w:r>';
                $headerText .= '</w:p>';
                
                // Agregar más espacio después del título
                $headerText .= '<w:p><w:pPr><w:spacing w:before="300" w:after="300"/></w:pPr></w:p>';
                
                // Datos del paciente
                $patient = $model->patient()->first();
                if ($patient) {
                    $headerText .= '<w:p><w:pPr><w:spacing w:before="200"/></w:pPr>';
                    $headerText .= '<w:r><w:rPr><w:b/></w:rPr><w:t>'.__("detail-patient.patient").' </w:t></w:r>';
                    $headerText .= '<w:r><w:t>'.$patient->firstname.' '.$patient->lastname.'</w:t></w:r>';
                    $headerText .= '</w:p>';
                    $headerText .= '<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Fecha: </w:t></w:r><w:r><w:t>'.date('d/m/Y').'</w:t></w:r></w:p>';
                }
                
                $headerText .= '<w:p><w:pPr><w:spacing w:before="200" w:after="200"/></w:pPr></w:p>';
                
                $objWriter->setValue('header', $headerText);
            } else {
                $objWriter->setValue('header', '');
            }
            
            // Contenido de la receta con formato mejorado
            $content = '<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>' . str_replace("\n", '</w:t></w:r></w:p><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>', $model->description) . '</w:t></w:r></w:p>';
            $objWriter->setValue('content', $content);
            
            // Agregar firma digital del doctor si existe
            $doctor = $model->user()->first();
            $footerText = '';
            $signatureText = '';
            
            if ($doctor) {
                // Espacio para firma
                $footerText .= '<w:p><w:pPr><w:spacing w:before="400"/><w:jc w:val="center"/></w:pPr>';
                // Obtener nombre completo del doctor desde el perfil
                $doctorName = $doctor->name; // Valor predeterminado
                $doctorProfile = $doctor->profile ?? null;
                if ($doctorProfile && !empty($doctorProfile->firstname) && !empty($doctorProfile->lastname)) {
                    $doctorName = $doctorProfile->firstname . ' ' . $doctorProfile->lastname;
                }
                // Agregar nombre del doctor encima de la firma
                $footerText .= '<w:r><w:rPr><w:b/><w:color w:val="4A90E2"/></w:rPr><w:t>Dr. '.$doctorName.'</w:t></w:r>';
                $footerText .= '</w:p>';
                
                // Verificar si el doctor tiene firma digital
                if ($doctor->hasDigitalSignature()) {
                    // Añadir la imagen de la firma
                    try {
                        // Intentar añadir la imagen de la firma al documento
                        $signaturePath = storage_path('app/public/signatures/' . $doctor->signature_path);
                        if (file_exists($signaturePath)) {
                            $signatureText = '<w:p><w:pPr><w:jc w:val="center"/><w:spacing w:before="0" w:after="0"/></w:pPr>';
                            $objWriter->setImageValue('signature', [
                                'path' => $signaturePath,
                                'width' => 100,
                                'height' => 50,
                                'ratio' => false
                            ]);
                            $signatureText .= '</w:p>';
                            
                            // Añadir texto de validación de firma digital
                            $signatureText .= '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                            $signatureText .= '<w:r><w:rPr><w:i/><w:sz w:val="16"/><w:color w:val="4A90E2"/></w:rPr>';
                            $signatureText .= '<w:t>Documento firmado digitalmente</w:t></w:r>';
                            $signatureText .= '</w:p>';
                        } else {
                            // Si no se encuentra el archivo, agregar solo el texto
                            $signatureText = '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                            $signatureText .= '<w:r><w:rPr><w:i/><w:sz w:val="16"/><w:color w:val="4A90E2"/></w:rPr>';
                            $signatureText .= '<w:t>Documento firmado digitalmente</w:t></w:r>';
                            $signatureText .= '</w:p>';
                        }
                    } catch (\Exception $e) {
                        // Si hay un error al insertar la imagen, usar solo texto
                        $signatureText = '<w:p><w:pPr><w:jc w:val="center"/></w:pPr>';
                        $signatureText .= '<w:r><w:rPr><w:i/><w:sz w:val="16"/><w:color w:val="4A90E2"/></w:rPr>';
                        $signatureText .= '<w:t>Documento firmado digitalmente</w:t></w:r>';
                        $signatureText .= '</w:p>';
                    }
                }
            }
            
            $objWriter->setValue('signature', $signatureText);
            $objWriter->setValue('footer', $footerText);
            $objWriter->setValue('address', $addressText);
            $objWriter->saveAs("php://output");

        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }



      /**
     * 
     */
    public function create(Request $request, BloodTypes $bloodTypes){
        try {
            $patient = new Patients();
            if(!($request->method() === "POST")){
                return view("create-patient",[
                    "patient"=>$patient,
                    "bloodTypes"=>$bloodTypes->getTypes()
                ]);
            }
            $data = $request->all();

            $model = $patient->createModelFromRequest($data);

            if(isset($data["identification"]) && (Patients::where("identification",$data["identification"])->count() > 0)){
                return redirect()->route("/admin/detail-patient",[
                    "model"=>Patients::where("identification",$data["identification"])->get()->first(),
                    "id"=>Patients::where("identification",$data["identification"])->get()->first()->id,
                    "exist"=>true
                ]);
            }
                
            $patient->create($model);
            $redirectData = [
                "id"=>$model["id"],
                "patient"=>$model,
                "patientId"=>$model["id"]
            ];
            
            

            if((int)$model["age"] < config("app.minimumAgeAdult")){
                if(isset($data["continueFromAppointment"]) && ($data["continueFromAppointment"] === "1"))
                    $redirectData["continueFromAppointment"] = $data["continueFromAppointment"]; 
                    Helper::fillDataFromAppointment($data, $redirectData);
                return redirect()->route("/admin/create-representative-from-patient",$redirectData); 
            }
            if(isset($data["continueFromAppointment"]) && ($data["continueFromAppointment"] === "1")){
                Helper::fillDataFromAppointment($data, $redirectData);
                return redirect()->route("/admin/create-appointment",$redirectData);
            }
            return redirect()->route("/admin/create-history",$redirectData);

        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    /**
     * 
     */
    public function update(Request $request,BloodTypes $bloodTypes){
       try{
        $data = $request->all();
        $id = $data["id"];
        $model = Patients::find($id);
        $date = NULL;
        if(!($request->method() === "POST")){
            $date = new DateTime($model->birthday);
            $model->birthday = $date->format("d/m/Y");
            return view("update-patient",[
                "patient"=>$model,
                "bloodTypes"=>$bloodTypes->getTypes()
            ]);
        }
        unset($data["id"]);
        $model->loadModelFromRequest($data);
        $model->save();
        return redirect()->route("/admin/detail-patient",[
            "id"=>$model->id
        ]);
       }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    /**
     * 
     */
    public function deleteMedicalReport(Request $request){
        try{
            $data = $request->all();
            $id = $data["id"];
            $patientId = $data["patientId"];
            $medicalReport = MedicalReport::find($id);
            
            if($medicalReport === null)
                throw new GlobalException(__("error-500.messageNoSearch"));
                
            // Verificar que el usuario actual sea el propietario del informe
            if($medicalReport->users_id != Auth::user()->id)
                throw new GlobalException(__("error-500.unauthorizedAction"));
                
            $medicalReport->delete();
            
            return redirect()->route("/admin/view-medical-reports",[
                "patientId" => $patientId
            ]);
        }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    /**
     * Export patients to Excel
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function export(Request $request)
    {
        try {
            $filename = 'pacientes_' . date('Y-m-d') . '.xlsx';
            return Excel::download(new PatientExport(), $filename);
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
}
