<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
/**
 * Hospitalization Entity.
 *
 * @property int $id
 * @property int $patient_id
 * @property \App\Model\Entity\Patient $patient
 * @property string $health_care_number
 * @property string $type
 * @property string $complementary_health
 * @property \Cake\I18n\Time $expected_discharge_day
 * @property int $screening_id
 * @property \App\Model\Entity\Screening $screening
 * @property int $origin_id
 * @property \App\Model\Entity\Origin $origin
 * @property int $unit_id
 * @property \App\Model\Entity\Unit $unit
 * @property \Cake\I18n\Time $created
 * @property string $updated
 * @property bool $readmission_to_hospital_until_30_days
 * @property bool $rehospitalization_up_24
 * @property float $weight
 * @property float $height
 * @property string $systemic_diagnosis
 * @property int $sector_id
 * @property \App\Model\Entity\Sector $sector
 * @property string $numero_do_prontuario
 * @property float $imc
 * @property int $medical_care_id
 * @property \App\Model\Entity\MedicalCare $medical_care
 * @property \App\Model\Entity\ApacheIiScore[] $apache_ii_scores
 * @property \App\Model\Entity\BarthelIndex[] $barthel_indexes
 * @property \App\Model\Entity\BradenScale[] $braden_scales
 * @property \App\Model\Entity\Bundle[] $bundles
 * @property \App\Model\Entity\CardiacSurgeryChecklist[] $cardiac_surgery_checklists
 * @property \App\Model\Entity\NeonatalChecklist[] $neonatal_checklists
 * @property \App\Model\Entity\ChestPainProtocol[] $chest_pain_protocols
 * @property \App\Model\Entity\ClinicTevProtocol[] $clinic_tev_protocols
 * @property \App\Model\Entity\CribScore[] $crib_scores
 * @property \App\Model\Entity\Culture[] $cultures
 * @property \App\Model\Entity\CurbScore[] $curb_scores
 * @property \App\Model\Entity\DailySafetyChecklist[] $daily_safety_checklists
 * @property \App\Model\Entity\Diagnostic[] $diagnostics
 * @property \App\Model\Entity\Discharge[] $discharges
 * @property \App\Model\Entity\FugulinBradenScale[] $fugulin_braden_scales
 * @property \App\Model\Entity\HistoricPatientMovement[] $historic_patient_movements
 * @property \App\Model\Entity\IdentificationOfRisk[] $identification_of_risks
 * @property \App\Model\Entity\Infection[] $infections
 * @property \App\Model\Entity\InformedConsentForm[] $informed_consent_forms
 * @property \App\Model\Entity\ItuPreventionBundle[] $itu_prevention_bundles
 * @property \App\Model\Entity\MedicalBulletin[] $medical_bulletins
 * @property \App\Model\Entity\MedicalOpinionRequest[] $medical_opinion_requests
 * @property \App\Model\Entity\NasScore[] $nas_scores
 * @property \App\Model\Entity\NutritionalAssessment[] $nutritional_assessments
 * @property \App\Model\Entity\ObstetricSurgeryChecklist[] $obstetric_surgery_checklists
 * @property \App\Model\Entity\PavPreventionBundle[] $pav_prevention_bundles
 * @property \App\Model\Entity\PreAnestheticVisit[] $pre_anesthetic_visits
 * @property \App\Model\Entity\PreDeliricScore[] $pre_deliric_scores
 * @property \App\Model\Entity\Prescription[] $prescriptions
 * @property \App\Model\Entity\SafeSurgeryBundle[] $safe_surgery_bundles
 * @property \App\Model\Entity\SapsIiiScore[] $saps_iii_scores
 * @property \App\Model\Entity\SepseProtocol[] $sepse_protocols
 * @property \App\Model\Entity\SkinIntegrity[] $skin_integrities
 * @property \App\Model\Entity\SnapIiScore[] $snap_ii_scores
 * @property \App\Model\Entity\SofaEscore[] $sofa_escores
 * @property \App\Model\Entity\StrengthAssessmentScale[] $strength_assessment_scales
 * @property \App\Model\Entity\SupportiveMeasure[] $supportive_measures
 * @property \App\Model\Entity\Surgery[] $surgeries
 * @property \App\Model\Entity\SurgicalChecklist[] $surgical_checklists
 * @property \App\Model\Entity\SurgicalTevProtocol[] $surgical_tev_protocols
 * @property \App\Model\Entity\SuspectedMeProtocol[] $suspected_me_protocols
 * @property \App\Model\Entity\VentilatoryCarePlan[] $ventilatory_care_plans
 */
class Hospitalization extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id' => false,
    ];

    public function screening($screening_id = null, $type = null){
        $queixa_principal       = ['alteracao_estado_mental' => 'Alteração de estado mental', 'dispneia' => 'Dispneia', 'hiperglicemia' => 'Hiperglicemia', 'alt_sinais_vitais' => 'Alt. sinais vitais isolados', 'tosse' => 'Tosse', 'lesoes_de_pele' => 'Lesões de pele', 'dor' => 'Dor', 'febre' => 'Febre', 'hipoglicemia' => 'Hipoglicemia', 'diarreia' => 'Diarreia', 'casos_especiais' => 'Casos especiais', 'procura_da_unidade' => 'Procura da unidade p/ procedimentos', 'hemorragia' => 'Hemorragia', 'alteracao_de_pressao' => 'Alteração de pressão', 'parada_cardiorrespiratoria' => 'Parada cardiorrespiratória', 'hemorragia_digestiva' => 'Hemorragia digestiva', 'queixas_cronicas' => 'Queixas crônicas'];

        $screening_table = TableRegistry::get('Screenings');
        $screenings = $screening_table->find('all', [
            'contain' => ["MedicalCares", "Admissions", 'Patients' => ['Diagnostics'], 'Professionals' => ["Users"]],

            'conditions' => ['Screenings.id' => $screening_id],
        ]);



        $el = '';
        foreach ($screenings as $key => $screening) {
            //echo 'ssss' . $screening["id"];
            /*echo '<pre>';
            print_r($screening);*/
            if($type == 'classificacaoRisco'){
                //echo 'ssss222' . $screening["classificacao_sugerida"];
                if ( isset( $screening["classificacao_selecionada"] ) && $screening["classificacao_selecionada"] != "" ) {
                    //echo "aaaaaaa";
                    $el = $screening["classificacao_selecionada"];
                } else {
                    //echo "bbbbbbb" . $screening["classificacao_sugerida"];
                    $el = $screening["classificacao_sugerida"]; 
                }
            }

            if($type == 'queixa_principal'){
                //echo 'ssss222' . $screening["classificacao_sugerida"];
                if ( isset( $queixa_principal[$screening["queixa_principal"]] ) ) {
                    $el = $queixa_principal[$screening["queixa_principal"]];
                }
            }

            if($type == 'status'){
                //echo 'ssss222' . $screening["classificacao_sugerida"];
                if ( isset( $screening["medical_cares"]["status"] ) ) {
                    $el = $screening["medical_cares"]["status"];
                }
            }

            if($type == 'nome_medico'){
                //echo 'ssss222' . $screening["classificacao_sugerida"];
                if ( isset( $screening["professional"]["user"] ) ) {
                    $el = $screening["professional"]["user"]["name"];
                }
            }

            if($type == 'data_ultimo_atendimento'){
                //echo 'ssss222' . $screening["classificacao_sugerida"];
                foreach ($screening["medical_cares"] as $key => $medical_care) {
                    $el = $medical_care["created"];
                }
            }

        }
        

        return $el;
    }

    public function surgicalMaterial($id = null){
        $surgical_material_table = TableRegistry::get('SurgicalMaterials');
        $surgeries_table = TableRegistry::get('Surgeries');

        $surgeries = $surgeries_table->find('all')
            ->contain(['SurgicalMaterials'])
            ->where(['Surgeries.id'=>$id]);

        $surgicalMateralNomes = '';

        foreach ($surgeries as $key => $surgeries) {

            foreach ($surgeries['surgical_materials'] as $key => $surgical_materials) {
                if($key == 0){
                $surgicalMateralNomes .= $surgical_materials['nome'];
                }
                else{
                    $surgicalMateralNomes = $surgicalMateralNomes . ', ' . $surgical_materials['nome'];
                }
            }            
        };
        return $surgicalMateralNomes;
    }

    public function sectorName($hospitalization_id = null)
    {
        $historic_patient_movement_table = TableRegistry::get('HistoricPatientMovements');

        $historic_patient_movements = $historic_patient_movement_table->find('all')
        ->where(['HistoricPatientMovements.hospitalization_id'=>$hospitalization_id]);

        foreach ($historic_patient_movements as $key => $historic_patient_movement) {
            $room_id = $historic_patient_movement['room_id'];
        }

        $room_table = TableRegistry::get('Rooms');
        $sector_table = TableRegistry::get('Sectors');

        $room = $room_table->get($room_id);

        $sector = $sector_table->get($room['sector_id']);

        return $sector['name'];
    }

    public function roomName($hospitalization_id = null)
    {
        $historic_patient_movement_table = TableRegistry::get('HistoricPatientMovements');

        $historic_patient_movements = $historic_patient_movement_table->find('all')
        ->where(['HistoricPatientMovements.hospitalization_id'=>$hospitalization_id]);

        foreach ($historic_patient_movements as $key => $historic_patient_movement) {
            $room_id = $historic_patient_movement['room_id'];
        }

        $room_table = TableRegistry::get('Rooms');

        $room = $room_table->get($room_id);

        return $room['name'];
    }

    public function typeSurgeries($id = null){
        $surgeries_table = TableRegistry::get('Surgeries');

        $surgeries = $surgeries_table->find('all')
            ->contain(['ChangeTypeOfAnesthesias'])
            ->where(['Surgeries.id'=>$id]);

        $changeTypeOfAnesthesiaNomes = '';        

        foreach ($surgeries as $key => $surgeries) {

            foreach ($surgeries['change_type_of_anesthesias'] as $key => $change_type_of_anesthesias) {
                if($key == 0){
                $changeTypeOfAnesthesiaNomes .= $change_type_of_anesthesias['nome'];
                }
                else{
                    $changeTypeOfAnesthesiaNomes = $changeTypeOfAnesthesiaNomes . ', ' . $change_type_of_anesthesias['nome'];
                }
            }            
        };
        return $changeTypeOfAnesthesiaNomes;
    }
}
