<?php
namespace App\Controller;

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


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

        $this->loadComponent('Permission');

        // View or Controller
        $this->set('title', 'Identificação de Riscos');

        $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)
    {
        $action = $this->request->params['action'];

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

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

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

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

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

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

    /**
     * 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');
        $historic = TableRegistry::get('HistoricPatientMovements');

        $historic = $historic->find()
            ->where(['HistoricPatientMovements.hospitalization_id' => $hospitalization_id])
            ->order(['HistoricPatientMovements.created' => 'DESC'])
            ->contain(['Rooms'])
            ->first()
            ->toArray();

        $identificationOfRisk = $this->IdentificationOfRisks->newEntity();
        if ($this->request->is('post')) 
        {
            $identificationOfRisk = $this->IdentificationOfRisks->patchEntity($identificationOfRisk, $this->request->data);
            
            if (isset($historic['room']['sector_id']))
            {
                $identificationOfRisk->sector_id = $historic['room']['sector_id'];
            }

            if ($this->IdentificationOfRisks->save($identificationOfRisk)) 
            {
                $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->IdentificationOfRisks->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('identificationOfRisk', 'hospitalizations'));
        $this->set('_serialize', ['identificationOfRisk']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Identification O f Risk 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)
    {

        $session = $this->request->session();
        $hospitalization_id = $session->read('selected-hospitalization');
        $historic = TableRegistry::get('HistoricPatientMovements');

        $historic = $historic->find()
            ->where(['HistoricPatientMovements.hospitalization_id' => $hospitalization_id])
            ->order(['HistoricPatientMovements.created' => 'DESC'])
            ->contain(['Rooms'])
            ->first()
            ->toArray();

        $identificationOfRisk = $this->IdentificationOfRisks->get($id, [
            'contain' => [],
        ]);

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

            if (isset($historic['room']['sector_id']))
            {
                $identificationOfRisk->sector_id = $historic['room']['sector_id'];
            }

            if ($this->IdentificationOfRisks->save($identificationOfRisk)) 
            {
                $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->IdentificationOfRisks->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('identificationOfRisk', 'hospitalizations', 'historic'));
        $this->set('_serialize', ['identificationOfRisk']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Identification Of Risk 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']);
        $identificationOfRisk = $this->IdentificationOfRisks->get($id);
        if ($this->IdentificationOfRisks->delete($identificationOfRisk)) {
            $this->Flash->success(__('The identification of risk has been deleted.'));
        } else {
            $this->Flash->error(__('The identification of risk could not be deleted. Please, try again.'));
        }
        return $this->redirect(['action' => 'index']);
    }

    public function desactivate($id = null)
    {
        $this->request->allowMethod(['post', 'desactivate']);
        $identificationOfRisks = $this->IdentificationOfRisks->get($id);

        $identificationOfRisks->is_active = false;

        if ($this->IdentificationOfRisks->save($identificationOfRisks)) {
            $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']);

        $identificationOfRisks            = $this->IdentificationOfRisks->get($id);
        $identificationOfRisks->is_active = true;

        if ($this->IdentificationOfRisks->save($identificationOfRisks)) {

            $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']);

    }
}
