<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;

/**
 * Discharges Controller
 *
 * @property \App\Model\Table\DischargesTable $Discharges
 */
class DischargesController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Auth', [
            'authorize' => 'Controller',
        ]);
        $this->loadComponent('Permission');

        // View or Controller
        $this->set('title', 'Alta Hospitalar');

        $session = $this->request->session();

        $pacient_id = $session->read('selected-pacient');
        $this->set('pacient_id', $pacient_id);

        $unit_id = $session->read('selected-unit');
        $this->set('unit_id', $unit_id);

        $hospitalization_id = $session->read('selected-hospitalization');
        $this->set('hospitalization_id', $hospitalization_id);
    }

    public function isAuthorized($user)
    {
        return true;
        $action = $this->request->params['action'];

        return $this->Permission->hasPermission($user['role_name'], 'ApacheIiScores', $action);
        //return parent::isAuthorized($user);
    }

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['Hospitalizations'],
        ];
        $discharges = $this->paginate($this->Discharges);

        $this->set(compact('discharges'));
        $this->set('_serialize', ['discharges']);
    }

    /**
     * View method
     *
     * @param string|null $id Discharge id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $discharge = $this->Discharges->get($id, [
            'contain' => ['Hospitalizations'],
        ]);

        $this->set('discharge', $discharge);
        $this->set('_serialize', ['discharge']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    // public function add()
    // {
    //     $discharge = $this->Discharges->newEntity();

    //     if ($this->request->is('post'))
    //     {
    //         $discharge = $this->Discharges->patchEntity($discharge, $this->request->data);

    //         if ($this->Discharges->save($discharge))
    //         {
    //             $this->Flash->success(__('O registro foi salvo.'));
    //             return $this->redirect(['action' => 'index']);
    //         }
    //         else
    //         {
    //             $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente novamente.'));
    //         }
    //     }

    //     $hospitalizations = $this->Discharges->Hospitalizations->find('list', ['limit' => 200]);
    //     $this->set(compact('discharge', 'hospitalizations'));
    //     $this->set('_serialize', ['discharge']);
    // }

    /**
     * Edit method
     *
     * @param string|null $id Discharge id.
     * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $hospitalizations = null;
        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $session = $this->request->session();
        $hospitalization_id = $session->read('selected-hospitalization');

        $discharge_exist = $hospitalization_table->Discharges->find('all',
            ['limit' => 200])->first();

        if ($discharge_exist)
        {
            $discharge = $this->Discharges->get($discharge_exist->id, [
                'contain' => ['Sectors'],
            ]);
            $hospitalizations = $this->Discharges->Hospitalizations->find('list', ['limit' => 200]);
        }
        else
        {
            $discharge = $this->Discharges->newEntity();
        }

        if ($this->request->is(['patch', 'post', 'put']))
        {
            $discharge = $this->Discharges->patchEntity($discharge, $this->request->data);

            $hospitalization = $hospitalization_table->get($hospitalization_id);

            if ($discharge->data_saida_unidade)
            {
                switch ($discharge->destino_apos_alta)
                {
                    case '0':
                        $hospitalization->status = 'alta';
                        $hospitalization->data_alta_obito = $discharge->data_saida_unidade;
                        break;

                    case '1':
                        $hospitalization->status = 'obito';
                        $hospitalization->data_alta_obito = $discharge->data_saida_unidade;
                        break;

                    case '2':
                        $hospitalization->status = 'alta';
                        $hospitalization->data_alta_obito = $discharge->data_saida_unidade;
                        break;
                }
            }


            $hospitalization_table->save($hospitalization);


            if ($this->Discharges->save($discharge))
            {
                $this->Flash->success(__('O registro foi salvo.'));
                //return $this->redirect(['controller' => 'HistoricPatientMovements', 'action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente novamente.'));
            }
        }

        $sectors = $this->Discharges->Sectors->find('list', ['fields' => ['id', 'name'], 'limit' => 200]);
        $this->set(compact('discharge', 'hospitalizations', 'sectors'));
        $this->set('_serialize', ['discharge']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Discharge id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $discharge = $this->Discharges->get($id);
        if ($this->Discharges->delete($discharge))
        {
            $this->Flash->success(__('The discharge has been deleted.'));
        }
        else
        {
            $this->Flash->error(__('The discharge could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }

    public function printView($id = null)
    {
        $is_print_view = true;

        $session = $this->request->session();

        $hospitalizations = null;

        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $patientTable = TableRegistry::get('Patients');
        $units_table = TableRegistry::get('Units');

        $discharge_exist = $hospitalization_table->Discharges->find('all',
            ['limit' => 200])->first();

        if ($discharge_exist)
        {
            $discharge = $this->Discharges->get($discharge_exist->id, [
                'contain' => ['Sectors'],
            ]);
            $hospitalizations = $this->Discharges->Hospitalizations->find('list', ['limit' => 200]);
        }
        else
        {
            $discharge = $this->Discharges->newEntity();
        }

        $unit_id = $session->read('selected-unit');
        $pacient_id = $session->read('selected-pacient');
        $hospitalization_id = $session->read('selected-hospitalization');

        $unit = $units_table->get($unit_id);
        $hospitalization = $hospitalization_table->get($hospitalization_id, ['contain' => ['Discharges', 'Sectors']]);
        $patient = $patientTable->get($pacient_id);

        if ($this->request->is(['patch', 'post', 'put']))
        {
            $discharge = $this->Discharges->patchEntity($discharge, $this->request->data);
            if ($this->Discharges->save($discharge))
            {
                $this->Flash->success(__('The discharge has been saved.'));
                return $this->redirect(['controller' => 'HistoricPatientMovements', 'action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('The discharge could not be saved. Please, try again.'));
            }
        }

        $sectors = $this->Discharges->Sectors->find('list', ['fields' => ['id', 'name'], 'limit' => 200])->toArray();
        $this->set(compact('is_print_view', 'patient', 'hospitalization', 'unit', 'discharge', 'hospitalizations', 'sectors'));
        $this->set('_serialize', ['discharge']);
    }

    public function printAlta($id = null)
    {
        //init settings
        $is_print_view = true;
        $session = $this->request->session();

        //ids
        $unit_id = $session->read('selected-unit');
        $pacient_id = $session->read('selected-pacient');
        $hospitalization_id = $session->read('selected-hospitalization');


        //tables
        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $patientTable = TableRegistry::get('Patients');
        $units_table = TableRegistry::get('Units');


        // getting objects
        $unit    = $units_table->get($unit_id);
        $patient = $patientTable->get($pacient_id);
        $hospitalization = $hospitalization_table->get($hospitalization_id, [
            'contain' => [
                'Sectors',
                'Surgeries'=>['TypeOfAnesthesias'],
                'ApacheIiScores',
                'SofaEscores',
                'SnapIiScores',
                'PreDeliricScores',
                'CribScores',
                'SapsIiiScores',
                'CurbScores',
                'NasScores',
                'SupportiveMeasures',
                'FugulinBradenScales',
                'BradenScales',
                'SkinIntegrities',
                'IdentificationOfRisks',
                'NutritionalAssessments',
                'MedicalOpinionRequests'=> [
                   'Specialties'
                 ],
                'Diagnostics' => [
                   'Comorbidities',
                   'SystemicDiagnosis',
                   'Malformations'
                 ],
                 'Cultures' => [
                   'ListAntibiotics',
                   'AntibioticsInUse'
                 ],
                 'Infections'=>[
                     'Cultures'=>[
                        'Medications'
                     ]
                  ]
            ]
         ]);


        // getting specific info to view
        $diagnostics = (!empty($hospitalization['diagnostics'])) ? $hospitalization['diagnostics'] : [] ;

        $surgeries = (!empty($hospitalization['surgeries'])) ? $hospitalization['surgeries'] : [] ;


        //scores
        $apache_ii_scores = (!empty($hospitalization['apache_ii_scores'])) ? $hospitalization['apache_ii_scores'] : [] ;

        $curb_scores = (!empty($hospitalization['curb_scores'])) ? $hospitalization['curb_scores'] : [] ;

        $saps_iii_scores = (!empty($hospitalization['saps_iii_scores'])) ? $hospitalization['saps_iii_scores'] : [] ;

        $crib_scores = (!empty($hospitalization['crib_scores'])) ? $hospitalization['crib_scores'] : [] ;

        $snap_ii_scores = (!empty($hospitalization['snap_ii_scores'])) ? $hospitalization['snap_ii_scores'] : [] ;

        $sofa_escores = (!empty($hospitalization['sofa_escores'])) ? $hospitalization['sofa_escores'] : [] ;

        $pre_deliric_scores = (!empty($hospitalization['pre_deliric_scores'])) ? $hospitalization['pre_deliric_scores'] : [] ;
        //scores


        //enfermagem
        $fugulin_braden_scales = (!empty($hospitalization['fugulin_braden_scales'])) ? $hospitalization['fugulin_braden_scales'] : [] ;

        $braden_scales = (!empty($hospitalization['braden_scales'])) ? $hospitalization['braden_scales'] : [] ;

        $nas_scores = (!empty($hospitalization['nas_scores'])) ? $hospitalization['nas_scores'] : [] ;

        $skin_integrities = (!empty($hospitalization['skin_integrities'])) ? $hospitalization['skin_integrities'] : [] ;

        $nutritional_assessments = (!empty($hospitalization['nutritional_assessments'])) ? $hospitalization['nutritional_assessments'] : [] ;

        $identification_of_risks = (!empty($hospitalization['identification_of_risks'])) ? $hospitalization['identification_of_risks'] : [] ;
        //enfermagem


        $cultures = (!empty($hospitalization['cultures'])) ? $hospitalization['cultures'] : [] ;

        $supportive_measures = (!empty($hospitalization['supportive_measures'])) ? $hospitalization['supportive_measures'] : [] ;

        $infections = (!empty($hospitalization['infections'])) ? $hospitalization['infections'] : [] ;



        // scores
        $scores = [];
        $item = [];

        foreach ($apache_ii_scores as $key => $apache_ii_score) {
            $item['type'] = 'Apache II';
            $item['pontuation'] = $apache_ii_score['pontuation'];
            $item['death_rate'] = $apache_ii_score['probabilidade_de_obito'];

            array_push($scores,$item);
        }


        foreach ($curb_scores as $key => $curb_score) {
            $item['type'] = 'CURB65';
            $item['pontuation'] = $curb_score['pontuation'];
            $item['death_rate'] = '';

            array_push($scores,$item);
        }


        foreach ($saps_iii_scores as $key => $saps_iii_score) {
            $item['type'] = 'Saps III';
            $item['pontuation'] = $saps_iii_score['pontuation'];
            $item['death_rate'] = $saps_iii_score['probabilidade_de_obito'];

            array_push($scores,$item);
        }


        foreach ($crib_scores as $key => $crib_score) {
            $item['type'] = 'CRIB';
            $item['pontuation'] = $crib_score['pontuation'];
            $item['death_rate'] = $crib_score['probabilidade_obito'];

            array_push($scores,$item);
        }


        foreach ($snap_ii_scores as $key => $snap_ii_score) {
            $item['type'] = 'Snap II';
            $item['pontuation'] = $snap_ii_score['pontuation'];
            $item['death_rate'] = $snap_ii_score['probabilidade_obito_snap'];

            array_push($scores,$item);
        }


        foreach ($sofa_escores as $key => $sofa_escore) {
            $item['type'] = 'SOFA';
            $item['pontuation'] = $sofa_escore['pontuation'];
            $item['death_rate'] = '';

            array_push($scores,$item);
        }


        foreach ($pre_deliric_scores as $key => $pre_deliric_score) {
            $item['type'] = ' Pre-Deliric';
            $item['pontuation'] = $pre_deliric_score['pontuation'];
            $item['death_rate'] = $pre_deliric_score['probabilidade_obito'];

            array_push($scores,$item);
        }



        $enfermagemScores = [];
        $itemEnfermagem = [];

      //   $skin_integrities

        foreach ($fugulin_braden_scales as $key => $fugulin_braden_scale) {
            $itemEnfermagem['type'] = 'Fugulin';
            $itemEnfermagem['pontuation'] = $fugulin_braden_scale['fugulin_score'];

            array_push($enfermagemScores,$itemEnfermagem);
        }


        foreach ($braden_scales as $key => $braden_scale) {
            $itemEnfermagem['type'] = 'Braden';
            $itemEnfermagem['pontuation'] = $braden_scale['pontuacao'];

            array_push($enfermagemScores,$itemEnfermagem);
        }

        foreach ($nas_scores as $key => $nas_score) {
            $itemEnfermagem['type'] = 'NAS';
            $itemEnfermagem['pontuation'] = $nas_score['pontuation'];

            array_push($enfermagemScores,$itemEnfermagem);
        }


        //parecer
        $medical_opinion_requests = (!empty($hospitalization['medical_opinion_requests'])) ? $hospitalization['medical_opinion_requests'] : [] ;

        $sector = (!empty($hospitalization['sector'])) ? $hospitalization['sector'] : [] ;

        $this->set(
             compact(
               'is_print_view',
               'patient',
               'hospitalization',
               'unit',
               'cultures',
               'infections',
               'diagnostics',
               'surgeries',
               'apache_ii_scores',
               'curb_scores',
               'saps_iii_scores',
               'crib_scores',
               'nas_scores',
               'snap_ii_scores',
               'sofa_escores',
               'pre_deliric_scores',
               'supportive_measures',
               'fugulin_braden_scales',
               'skin_integrities',
               'nutritional_assessments',
               'medical_opinion_requests',
               'sector',
               'scores',
               'enfermagemScores',
               'skin_integrities',
               'identification_of_risks'
             )
        );

    }

}
