<?php
namespace App\Controller;

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

/**
 * NutritionalAssessments Controller
 *
 * @property \App\Model\Table\NutritionalAssessmentsTable $NutritionalAssessments
 */
class NutritionalAssessmentsController extends AppController
{

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Permission');
        $this->loadComponent('Upload');
        $this->set('title', 'Avaliação Nutricional');
    }

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

        return $this->Permission->hasPermission($user['role_name'], 'NutritionalAssessments', $action);

        //return parent::isAuthorized($user);
    }

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $session = $this->request->session();
        $hospitalization_id = $session->read('selected-hospitalization');

        $this->paginate = [
            'contain' => ['Hospitalizations'],
            'order' => ['created' => 'desc'],
            'conditions' => ['NutritionalAssessments.hospitalization_id' => $hospitalization_id],
        ];

        $nutritionalAssessments = $this->paginate($this->NutritionalAssessments);

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

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $setores_criticos = ['Unidade de Terapia Intensiva Adulta', 'Unidade de Terapia Intensiva Pediátrica', 'Unidade de Terapia Intensiva Neonatal'];
        $session = $this->request->session();
        $patient_table = TableRegistry::get('Patients');
        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $estado_paciente = 'normal';

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

        $patient = $patient_table->get($pacient_id, []);

        $patient_movement_table = TableRegistry::get('HistoricPatientMovements');
        $patient_movement = $patient_movement_table
            ->find('all')
            ->where(['HistoricPatientMovements.hospitalization_id' => $hospitalization_id])
            ->contain(['Rooms' => ['Sectors' => ['Types']]])
            ->order(['HistoricPatientMovements.created' => 'DESC'])
            ->first();

        if (isset($patient_movement['room']['sector']['type']))
        {
            if (in_array($patient_movement['room']['sector']['type']['description'], $setores_criticos))
            {
                $estado_paciente = 'crítico';
            }
        }

        $hospitalization = $hospitalization_table->get($hospitalization_id, ['contain' => ['SofaEscores', 'ApacheIiScores', 'Diagnostics' => ['Comorbidities']]]);

        $nutritionalAssessment = $this->NutritionalAssessments->newEntity();

        if ($this->request->is('post'))
        {
            $nutritionalAssessment = $this->NutritionalAssessments->patchEntity($nutritionalAssessment, $this->request->data);

// echo "<pre>";
            // print_r($nutritionalAssessment);
            $nutritionalAssessment->sector_id = $patient_movement['room']['sector_id'];

            if ($this->NutritionalAssessments->save($nutritionalAssessment))
            {
                $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.'));
            }
        }

        $this->set(compact('nutritionalAssessment', 'patient', 'hospitalization', 'estado_paciente', 'hospitalization_id'));
        $this->set('_serialize', ['nutritionalAssessment']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Nutritional Assessment 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)
    {
        $setores_criticos = ['Unidade de Terapia Intensiva Adulta', 'Unidade de Terapia Intensiva Pediátrica', 'Unidade de Terapia Intensiva Neonatal'];
        $patient_table = TableRegistry::get('Patients');
        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $estado_paciente = 'normal';

        $session = $this->request->session();
        $pacient_id = $session->read('selected-pacient');
        $hospitalization_id = $session->read('selected-hospitalization');
        $nutritionalAssessment = $this->NutritionalAssessments->get($id, [
            'contain' => [],
        ]);

        $hospitalization = $hospitalization_table->get($hospitalization_id, ['contain' => ['SofaEscores', 'ApacheIiScores', 'Diagnostics' => ['Comorbidities']]]);
        $patient = $patient_table->get($pacient_id, []);

        $patient_movement_table = TableRegistry::get('HistoricPatientMovements');
        $patient_movement = $patient_movement_table
            ->find('all')
            ->where(['HistoricPatientMovements.hospitalization_id' => $hospitalization_id])
            ->contain(['Rooms' => ['Sectors' => ['Types']]])
            ->order(['HistoricPatientMovements.created' => 'DESC'])
            ->first()
        ;

        if (isset($patient_movement['room']['sector']['type']))
        {
            if (in_array($patient_movement['room']['sector']['type']['description'], $setores_criticos))
            {
                $estado_paciente = 'crítico';
            }
        }

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

            if ($this->NutritionalAssessments->save($nutritionalAssessment))
            {
                $this->Flash->success(__('O registro foi salvo.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                Log::write('debug', $nutritionalAssessment->errors());
                $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente novamente.'));
            }
        }

        $this->set(compact('nutritionalAssessment', 'estado_paciente', 'patient', 'hospitalization'));
        $this->set('_serialize', ['nutritionalAssessment']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Nutritional Assessment 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']);
        $nutritionalAssessment = $this->NutritionalAssessments->get($id);

        if ($this->NutritionalAssessments->delete($nutritionalAssessment))
        {
            $this->Flash->success(__('O registro foi salvo.'));
        }
        else
        {
            $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente novamente.'));
        }

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

    public function desactivate($id = null)
    {
        $this->request->allowMethod(['post', 'desactivate']);
        $session = $this->request->session();
        $nutritionalAssessment = $this->NutritionalAssessments->get($id);
        $nutritionalAssessment->is_active = false;

        if ($this->NutritionalAssessments->save($nutritionalAssessment))
        {
            $this->Flash->success(__('O registro foi suspenso com sucesso.'));
        }
        else
        {
            $this->Flash->error(__('O registro não pode ser suspenso. Por favor, tente novamente.'));
        }

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

    public function activate($id = null)
    {

        $this->request->allowMethod(['post', 'desactivate']);
        $session = $this->request->session();

        $nutritionalAssessment = $this->NutritionalAssessments->get($id);
        $nutritionalAssessment->is_active = true;

        if ($this->NutritionalAssessments->save($nutritionalAssessment))
        {
            $this->Flash->success(__('O registro foi ativado com sucesso.'));
        }
        else
        {
            $this->Flash->error(__('O registro não pode ser ativado. Por favor, tente novamente.'));
        }

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