<?php
namespace App\Helper;
use DateTime;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Hash;
use App\Models\Files;
use App\Jobs\SendWhatsAppNotification;
use App\Jobs\SendEmail;
use App\Services\TwilioService;
use App\Models\ClinicIdentity;

class Helper{
    public const MAIL_TO_SEND = "administracion@solidclinic360.com";
    public const OTHERS_MAIL_TO_SEND = [];
    public const SUBJECT_DEFAULT_NOTIFICATION   = "Nueva consulta médica";
    public const SUBJECT_DEFAULT_MAIL_TO_SEND   = "Datos de su consulta médica";

    /**
     * 
     */
    public static function getEspeciality($code){
        $especiality = "";
        switch ($code) {
            case 'PED':
                $especiality = "Pediatría";
            break;
            case 'NED':
                $especiality = "Nefrología";
            break;
        }
        return $especiality;
    }

    public static function getParent($code){
        $parent = "";
        switch ($code) {
            case "FATH":
               $parent = "Padre";
            break;
            case "MOTH":
                $parent = "Madre";
            break;
            case "UNCL":
                $parent = "Tío";
            break;
            case "AUNT":
                $parent = "Tía";
            break;
            case "GRAF":
                $parent = "Abuelo";
            break;
            case "GRAM":
                $parent = "Abuela";
            break;
            case "BROT":
                $parent = "Hermano";
            break;
            case "SIST":
                $parent = "Hermana";
            break;
            case "OTHE":
                $parent = "Otro";
            break;
        }
        return $parent;
    }


    /**
     * 
     */
    public static function JsonToCollection($json){
        $collection = collect(json_decode($json, true));
        return $collection;
    }

    public static function sendWhatsAppMessage($appointment){
        SendWhatsAppNotification::dispatch($appointment);
    }   

    /**
     * 
     */
    public static function sendEmail($from,$emails,$subject,$data,$classImpl,$model = NULL){
         SendEmail::dispatch($from,$emails,$subject,$data,$classImpl,$model);
         return false;
    }

    /**
     * 
     */
    public static function createId(){
        $date   = new DateTime();
        $id     = $date->format('Y-m-d H:i:s');
        return  md5($id);
    }

    /**
     * 
     */
    public static function getFieldsFromRequest($data,$fillable){
        $model = [];
        $data["id"] = Helper::createId();
        foreach($data as $key =>$value){
            if(in_array($key,$fillable)){
                if($key === "birthday"){
                    $value = date_create_from_format('d/m/Y',$value);
                }
                $model[$key] = $value;
            }            
        }
        return $model;
    }

    /**
     * 
     */
    public static function fillDataFromAppointment(array &$data, array &$redirectData){
        if(isset($data["date"]))
            $redirectData["date"] = $data["date"];
        if(isset($data["dateAppointment"]))
            $redirectData["dateAppointment"] = $data["dateAppointment"];
        if(isset($data["especiality"]))
            $redirectData["especiality"] = $data["especiality"];
        if(isset($data["hour"]))
            $redirectData["hour"] = $data["hour"];
        if(isset($data["minute"]))
            $redirectData["minute"] = $data["minute"];
        if(isset($data["schedule"]))
            $redirectData["schedule"] = $data["schedule"];
        if(isset($data["summary"]))
            $redirectData["summary"] = $data["summary"];
        if(isset($data["doctorname"]))
            $redirectData["doctorname"] = $data["doctorname"];

    }

    /**
     * 
     */
    public static function createReferenceForPayments($userId,$amount) {
        $timestamp = now();
        return md5($userId . $amount . $timestamp);
    }


      /**
     * 
     */
    public static function processFileUploadHistoryAndControl($files,$nameField,$historyId,$controlId=null) 
    {
        foreach($files as $file){
            $fileUpload = new Files();
            $fileUpload->friendly_name = $file->getClientOriginalName();
            $fileUpload->path = $file->store($nameField);
            $fileUpload->extension= $file->getClientOriginalExtension();
            $fileUpload->history_id= $historyId;
            $fileUpload->control_history_id= $controlId;
            $fileUpload->save();
        }    
    }

    /*
    *
    */
    public static function sanitizeInput($value) {
        if (is_array($value)) {
            return array_map([self::class, 'sanitizeInput'], $value);
        }
        
        return htmlspecialchars(strip_tags(trim($value)), ENT_QUOTES, 'UTF-8');
    }


    public static function buildMessageAppointmentWhatsApp($appointment){
        $patient = $appointment->patient()->first();
        $doctor = $appointment->getDoctor();
        $speciality = $appointment->especiality()->first();
        $phone = substr($patient->phone, -10);
        $clinicIdentity = ClinicIdentity::getActive();
        $name = ucwords(strtolower($patient->firstname)) . " " . ucwords(strtolower($patient->lastname));

        $message = "✅ *Confirmación de Cita Médica*\n\n";
        
        $message .= "Estimado(a) *{$name}*,\n\n";
        $message .= "Le confirmamos que su cita médica ha sido registrada con éxito. A continuación encontrará los detalles:\n\n";
        
        $message .= "📋 *ID de Cita:* " . $appointment->code . "\n";

        if($appointment->date instanceof \DateTime){
            $message .= "📅 *Fecha:* " . $appointment->date->format('d/m/Y') . "\n";
            $message .= "⏰ *Hora:* " . $appointment->date->format('g:i A') . "\n";
        }else{
            $message .= "📅 *Fecha:* " .date('d/m/Y', strtotime($appointment->date)) . "\n";
            $message .= "⏰ *Hora:* " . date('g:i A', strtotime($appointment->date)) . "\n";
        }

        $message .= "🩺 *Especialidad:* " . $speciality->name . "\n";
        $message .= "🟢 *Estado:* Confirmada\n\n";
        
        $message .= "👨‍⚕️ *Información del Doctor:*\n";
        $message .= "• Nombre: *" . $doctor->firstname . " " . $doctor->lastname . "*\n\n";
        
        $message .= "⚠️ *¡Importante!*\n";
        $message .= "Por favor llegue *15 minutos antes* de la hora programada para completar los trámites administrativos necesarios.\n\n";
        
        $message .= "📝 *Instrucciones para su Cita:*\n";
        $message .= "• Traiga su documento de identidad\n";
        $message .= "• Traiga exámenes médicos previos relacionados\n";
        $message .= "• Informe al médico sobre condiciones especiales o alergias\n";
        $message .= "• Para cancelar o reprogramar, hágalo con *24 horas de anticipación*\n\n";
        
        $clinicContact = "";
        if (isset($clinicIdentity)) {
            $clinicContact = "🏥 *" . $clinicIdentity->name . "*\n";
            $clinicContact .= "📞 Teléfono: " . $clinicIdentity->phone . "\n";
            $clinicContact .= "✉️ Email: " . $clinicIdentity->email . "\n";
            $clinicContact .= "📍 Dirección: " . $clinicIdentity->address . "\n";
            $clinicContact .= "🕒 Horario: " . $clinicIdentity->working_hours . "\n\n";
            return $message . $clinicContact . "Atentamente,\n" . $clinicIdentity->name;
        }
        return $message;
    }

 
}