<?php
namespace App\Controller;

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


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

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

        $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'], 'NasScores', $action);
        //return parent::isAuthorized($user);
    }

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

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

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $session = $this->request->session();
        $hospitalization_id = $session->read('selected-hospitalization');
        $patient_movement_table = TableRegistry::get('HistoricPatientMovements');

        $nasScore = $this->NasScores->newEntity();

        if ($this->request->is('post'))
        {
            $patient_movement = $patient_movement_table
                ->find('all')
                ->where(['HistoricPatientMovements.hospitalization_id' => $hospitalization_id])
                ->contain(['Rooms' => ['Sectors' => ['Types']]])
                ->order(['HistoricPatientMovements.created' => 'DESC'])
                ->first();
            $nasScore = $this->NasScores->patchEntity($nasScore, $this->request->data);
            $nasScore->sector_id = $patient_movement['room']['sector_id'];

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

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

    /**
     * Edit method
     *
     * @param string|null $id Nas Score 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)
    {
        $nasScore = $this->NasScores->get($id, [
            'contain' => [],
        ]);

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

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

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

    /**
     * Delete method
     *
     * @param string|null $id Nas Score 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']);
        $nasScore = $this->NasScores->get($id);

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

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

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

        if ($this->NasScores->save($nasScore))
        {
            $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(['controller' => 'fugulinBradenScales', 'action' => 'index']);
    }

    public function activate($id = null)
    {

        $this->request->allowMethod(['post', 'activate']);

        $nasScore = $this->NasScores->get($id);
        $nasScore->is_active = true;

        if ($this->NasScores->save($nasScore))
        {
            $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(['controller' => 'fugulinBradenScales', 'action' => 'index']);
    }
}
