<?php
namespace App\Model\Table;

use App\Model\Entity\DailySafetyChecklist;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use MedidasDispersao\MedidasDispersao;

require_once ROOT . DS . "vendor" . DS . "Zurubabel" . DS . "MedidasDispersao.php";

/**
 * DailySafetyChecklists Model
 *
 * @property \Cake\ORM\Association\BelongsTo $Hospitalizations
 * @property \Cake\ORM\Association\HasMany $Procedures
 */
class DailySafetyChecklistsTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('daily_safety_checklists');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Hospitalizations', [
            'foreignKey' => 'hospitalization_id',
            'joinType' => 'INNER',
        ]);
        $this->hasMany('Procedures', [
            'foreignKey' => 'daily_safety_checklist_id',
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->allowEmpty('cabeceira_de_leito_elevado');

        $validator
            ->allowEmpty('prevenção_de_lesao_aguda_de_mucosa_gastrica');

        $validator
            ->allowEmpty('profilaxia_de_tev');

        $validator
            ->allowEmpty('suporte_nutricional');

        $validator
            ->boolean('protocolo_de_controle_glicemico')
            ->allowEmpty('protocolo_de_controle_glicemico');

        $validator
            ->allowEmpty('total_de_insulina_sub_cutanea_nas_24_horas');

        $validator
            ->boolean('fez_insulina_venosa')
            ->allowEmpty('fez_insulina_venosa');

        $validator
            ->allowEmpty('total_de_insulina_venosa_nas_24_horas');

        $validator
            ->integer('total_glicemias_menor_que_60')
            ->allowEmpty('total_glicemias_menor_que_60');

        $validator
            ->boolean('sedacao')
            ->allowEmpty('sedacao');

        $validator
            ->boolean('sob_analgesia')
            ->allowEmpty('sob_analgesia');

        $validator
            ->boolean('delirium')
            ->allowEmpty('delirium');

        $validator
            ->boolean('teve_dor_nas_ultimas_24_horas')
            ->allowEmpty('teve_dor_nas_ultimas_24_horas');

        $validator
            ->boolean('ventilacao_mecanica_invasiva')
            ->allowEmpty('ventilacao_mecanica_invasiva');

        $validator
            ->boolean('pa2_fio2_menor_que_300')
            ->allowEmpty('pa2_fio2_menor_que_300');

        $validator
            ->boolean('volume_corrente_menor_que_8')
            ->allowEmpty('volume_corrente_menor_que_8');

        $validator
            ->boolean('pressao_de_plato_menor_que_30')
            ->allowEmpty('pressao_de_plato_menor_que_30');

        $validator
            ->boolean('iniciar_desmane')
            ->allowEmpty('iniciar_desmane');

        $validator
            ->boolean('iniciar_peca_t')
            ->allowEmpty('iniciar_peca_t');

        $validator
            ->boolean('cateter_venoso_central')
            ->allowEmpty('cateter_venoso_central');

        $validator
            ->boolean('cateter_venoso_central_can_be_removed')
            ->allowEmpty('cateter_venoso_central_can_be_removed');

        $validator
            ->boolean('cateter_vesical_de_demora')
            ->allowEmpty('cateter_vesical_de_demora');

        $validator
            ->boolean('cateter_vesical_de_demora_can_be_removed')
            ->allowEmpty('cateter_vesical_de_demora_can_be_removed');

        $validator
            ->boolean('antibioticos')
            ->allowEmpty('antibioticos');

        $validator
            ->boolean('antibioticos_can_be_removed')
            ->allowEmpty('antibioticos_can_be_removed');

        $validator
            ->boolean('corticoesteroides')
            ->allowEmpty('corticoesteroides');

        $validator
            ->boolean('corticoesteroides_can_be_removed')
            ->allowEmpty('corticoesteroides_can_be_removed');

        $validator
            ->boolean('cateter_arterial_can_be_removed')
            ->allowEmpty('cateter_arterial_can_be_removed');

        $validator
            ->boolean('cateter_arterial')
            ->allowEmpty('cateter_arterial');

        $validator
            ->boolean('total_de_afericoes')
            ->allowEmpty('total_de_afericoes');

        $validator
            ->boolean('afericoes_maior_180')
            ->allowEmpty('afericoes_maior_180');

        $validator
            ->boolean('fez_insulina_ultimas_24_h')
            ->allowEmpty('fez_insulina_ultimas_24_h');

        $validator
            ->allowEmpty('total_insulina_ultimas_24_h');

        $validator
            ->boolean('total_afericoes_glicemicas')
            ->allowEmpty('total_afericoes_glicemicas');

        $validator
            ->integer('total_glicemias_menor_que_60')
            ->allowEmpty('total_glicemias_maior_que_180');

        $validator
            ->boolean('protocolo_glicemico')
            ->allowEmpty('protocolo_glicemico');

        $validator
            ->boolean('uso_de_sedacao')
            ->allowEmpty('uso_de_sedacao');

        $validator
            ->boolean('sedacao_dentro_da_meta')
            ->allowEmpty('sedacao_dentro_da_meta');

        $validator
            ->allowEmpty('interrupcao_sedacao');

        $validator
            ->boolean('is_active')
            ->allowEmpty('is_active');

        $validator
            ->boolean('protocolo_higienico_oral')
            ->allowEmpty('protocolo_higienico_oral');

        $validator
            ->boolean('aspiracao_da_secrecao')
            ->allowEmpty('aspiracao_da_secrecao');

        $validator
            ->allowEmpty('necessidade_de_profilaxia');

        $validator
            ->boolean('atingiu_vet_pleno')
            ->allowEmpty('atingiu_vet_pleno');

        $validator
            ->allowEmpty('via_de_nutricao');

        $validator
            ->boolean('avaliacao_delirium_pelo_camicu')
            ->allowEmpty('avaliacao_delirium_pelo_camicu');

        $validator
            ->boolean('paciente_sob_ventilacao_espontanea')
            ->allowEmpty('paciente_sob_ventilacao_espontanea');

        return $validator;
    }

    public function getRelatorioData($hospitalizations, $date_begin, $date_end)
    {
        $calc_obj = new MedidasDispersao();

        $data =
            [
            'total_de_registros' => 0,

            'arr_pacientes_internados' => [],
            'tot_pacientes_internados' => 0,

            'clinica' => [
                'arr' => [],
                'total' => 0,
                'percentual' => 0,
                'total_avaliacao' => 0,
                'percentual_avaliacao' => 0,
            ],

            'cirurgica' => [
                'arr' => [],
                'total' => 0,
                'percentual' => 0,
                'total_avaliacao' => 0,
                'percentual_avaliacao' => 0,
            ],
            'cirurgica_emergencial' => [
                'arr' => [],
                'total' => 0,
                'percentual' => 0,
                'total_avaliacao' => 0,
                'percentual_avaliacao' => 0,
            ],

            'eletiva' => [
                'arr' => [],
                'total' => 0,
                'percentual' => 0,
                'total_avaliacao' => 0,
                'percentual_avaliacao' => 0,
            ],

            'emergencia' => [
                'arr' => [],
                'total' => 0,
                'percentual' => 0,
                'total_avaliacao' => 0,
                'percentual_avaliacao' => 0,
            ],

            'geral' => [
                'arr' => [],
                'total' => 0,
                'percentual' => 0,
                'total_avaliacao' => 0,
                'percentual_avaliacao' => 0,
            ],

            'profilaxia_tev' => [
                '0' => ['tot' => 0, 'percen' => 0],
                '1' => ['tot' => 0, 'percen' => 0],
                '2' => ['tot' => 0, 'percen' => 0],
                '3' => ['tot' => 0, 'percen' => 0],
                '4' => ['tot' => 0, 'percen' => 0],
                '5' => ['tot' => 0, 'percen' => 0],
            ],
            'via_de_nutricao' => [
                '0' => ['tot' => 0, 'percen' => 0],
                '1' => ['tot' => 0, 'percen' => 0],
                '2' => ['tot' => 0, 'percen' => 0],
                '3' => ['tot' => 0, 'percen' => 0],
                '4' => ['tot' => 0, 'percen' => 0],
                '5' => ['tot' => 0, 'percen' => 0],
            ],

            'teste_nutricao' => [],
        ];
        
        $columns = $this->schema()->columns();
          foreach ($columns as $key => $column)
          {
              $data[$column]['total'] = 0;
              $data[$column]['percentual'] = 0;
              $data[$column]['media'] = 0;
              $data[$column]['mediana'] = 0;
              $data[$column]['desvio_padrao'] = 0;
              $data[$column]['soma'] = 0;
          }

        foreach ($hospitalizations as $hospitalization)
        {           

            //calcula total de pacientes
            $hospitalization_type = null;
            if (stripos($hospitalization['type'], 'Clínica') !== false)
            {
                $hospitalization_type = 'clinica';
            }

            if (stripos($hospitalization['type'], 'Cirúr') !== false)
            {
                $hospitalization_type = 'cirurgica';
            }

            if (stripos($hospitalization['type'], 'letiva') !== false)
            {
                $hospitalization_type = 'eletiva';
            }

            if (stripos($hospitalization['type'], 'emergencia') !== false)
            {
                $hospitalization_type = 'emergencia';
            }

            if (stripos($hospitalization['type'], 'cirúr') !== false &&
                stripos($hospitalization['type'], 'emergencia') !== false)
            {
                $hospitalization_type = 'cirurgica_emergencial';
            }

            //verifica se o id do paciente já existe no array        
            if ($hospitalization_type &&
                !in_array($hospitalization['patients_id'], $data[$hospitalization_type]['arr']) )
            {
                array_push($data[$hospitalization_type]['arr'], $hospitalization['patient_id']);
                $data[$hospitalization_type]['total']++;                                
            }
            if ($hospitalization_type)
            {
                $data[$hospitalization_type]['total_avaliacao']++;
            }
            
            

            //calcula todos os pacientes que estão internados
            if (!in_array($hospitalization['patients_id'], $data['arr_pacientes_internados']) )
            {
                array_push($data['arr_pacientes_internados'], $hospitalization['patient_id']);
                $data['tot_pacientes_internados']++;                
            }
            

            foreach ($hospitalization["daily_safety_checklists"] as $key_1 => $neonatal)
            {
                if ($neonatal['created'] < $date_begin ||
                    $neonatal['created'] > $date_end)
                {
                    continue;
                }

                $neonatal_arr = (array) $neonatal;
                $i = 0;

                $data['total_de_registros']++;

                   
                if (isset($neonatal['profilaxia_de_tev']))
                {
                    $data['profilaxia_tev'][$neonatal['profilaxia_de_tev']]['tot']++;              
                }

                if (isset($neonatal['via_de_nutricao']))
                {
                    $data['via_de_nutricao'][$neonatal['via_de_nutricao']]['tot']++;                 
                }
                array_push($data['teste_nutricao'], $neonatal['via_de_nutricao']);

                foreach ($neonatal_arr as $key_2 => $value_2)
                {
                    $i++;
                    if ($i == 2) //acessa as propriades do obj
                    {
                        foreach ($value_2 as $key_3 => $value_3)
                        {
                            //$data[$key_3] = $value_3;
                            formatArr($value_3, $data, $key_3);
                        }
                    }
                }
            }

            // foreach ($hospitalization["daily_safety_checklists"] as $key_1 => $neonatal)
            // {
            //     $neonatal_arr = (array) $neonatal;
            //     $i = 0;

            //     $data['total_de_registros']++;

            //     foreach ($neonatal_arr as $key_2 => $value_2)
            //     {
            //         $i++;
            //         if ($i == 2) //acessa as propriades do obj
            //         {
            //             foreach ($value_2 as $key_3 => $value_3)
            //             {
            //                 //$data[$key_3] = $value_3;
            //                 $this->formatArr($value_3, $data, $key_3);
            //             }
            //         }
            //     }
            // }
        }

        foreach ($data as $key => $value)
        {
            $marcados = 0;
            if (isset($data[$key]['arr']))
            {
              $len = count($data[$key]['arr']);

                for ($i = 0; $i < $len; $i++)
                {
                    if ($data[$key]['arr'][$i] || $data[$key]['arr'][$i] !== 0)
                    {
                        $marcados++;
                    }
                }  
            }
            

            if (isset($data[$key]['percentual']))
            {
                $data[$key]['total'] = count($data[$key]['arr']);
                $data[$key]['soma'] = array_sum($data[$key]['arr']);
                $data[$key]['percentual'] = $calc_obj->calculate_percentage($marcados, $data['total_de_registros']);
                $data[$key]['media'] = $calc_obj->calc_average($data[$key]['arr']);
                $data[$key]['mediana'] = $calc_obj->calculate_median($data[$key]['arr']);
                $data[$key]['desvio_padrao'] = $calc_obj->standard_deviation($data[$key]['arr']);
            }

            if ($data['tot_pacientes_internados'] > 0)
            {
                if ($data['clinica']['total'] > 0)
                {
                    $data['clinica']['percentual'] = ($data['clinica']['total'] * 100) / $data['tot_pacientes_internados'];
                    $data['clinica']['percentual'] = round($data['clinica']['percentual'], 2);
                }

                if ($data['eletiva']['total'] > 0)
                {
                    $data['eletiva']['percentual'] = ($data['eletiva']['total'] * 100) / $data['tot_pacientes_internados'];
                    $data['eletiva']['percentual'] = round($data['eletiva']['percentual'], 2);
                }

                if ($data['cirurgica']['total'] > 0)
                {
                    $data['cirurgica']['percentual'] = ($data['cirurgica']['total'] * 100) / $data['tot_pacientes_internados'];
                    $data['cirurgica']['percentual'] = round($data['cirurgica']['percentual'], 2);
                }

                if ($data['cirurgica_emergencial']['total'] > 0)
                {
                    $data['cirurgica_emergencial']['percentual'] = ($data['cirurgica_emergencial']['total'] * 100) / $data['tot_pacientes_internados'];
                    $data['cirurgica_emergencial']['percentual'] = round($data['cirurgica_emergencial']['percentual'], 2);
                }
            }
        }

        foreach ($data['via_de_nutricao'] as $key_via => $via) 
        {
            if (isset($via['tot']) &&
                $via['tot'] > 0 &&
                $data['total_de_registros'] > 0)
            {
                $data['via_de_nutricao'][$key_via]['percen'] = ($via['tot'] * 100) / $data['total_de_registros'];
                $data['via_de_nutricao'][$key_via]['percen'] = round($data['via_de_nutricao'][$key_via]['percen'], 2);
            }
        }

        return $data;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['hospitalization_id'], 'Hospitalizations'));
        return $rules;
    }
}
