<?php
namespace App\Controller;

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

/**
 * HistoricPatientMovements Controller
 *
 * @property \App\Model\Table\HistoricPatientMovementsTable $HistoricPatientMovements
 */
class HistoricPatientMovementsController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Permission');
        $this->set('title', 'Evolução na Unidade');
    }

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

        return $this->Permission->hasPermission($user['role_name'], 'HistoricPatientMovements', $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', 'Rooms' => ['Sectors']],
            'conditions' => ['HistoricPatientMovements.hospitalization_id' => $hospitalization_id],
            'order' => ['created' => 'desc'],
        ];

        $historicPatientMovements = $this->paginate($this->HistoricPatientMovements);

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

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $sectors_table = TableRegistry::get('Sectors');
        $sectors       = $sectors_table
            ->find()
            ->contain(['Rooms'])
            // ->where(['UnitsUsers.unit_id =' => $id, 'UnitsUsers.user_id =' => $user_id])
            //->first();
            ->toArray();

        $historicPatientMovement = $this->HistoricPatientMovements->newEntity();
        if ($this->request->is('post')) {
            $historicPatientMovement = $this->HistoricPatientMovements->patchEntity($historicPatientMovement, $this->request->data);
            if ($this->HistoricPatientMovements->save($historicPatientMovement)) {
                $this->Flash->success(__('O registro foi salvo.'));
                return $this->redirect(['action' => 'index']);
            } else {
                Log::write('debug', $historicPatientMovement);
                Log::write('debug', $historicPatientMovement->errors());
                $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente novamente.'));
            }
        }
        //$hospitalizations = $this->HistoricPatientMovements->Hospitalizations->find('list', ['limit' => 200]);

        $rooms = $this->HistoricPatientMovements->Rooms->find('list', ['limit' => 200]);
        $this->set(compact('historicPatientMovement', 'hospitalizations', 'rooms', 'sectors'));
        $this->set('_serialize', ['historicPatientMovement']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Historic Patient Movement 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)
    {
        $historicPatientMovement = $this->HistoricPatientMovements->get($id, [
            'contain' => ['Rooms'],
        ]);

        $sectors_table = TableRegistry::get('Sectors');
        $sectors       = $sectors_table
            ->find()
            ->contain(['Rooms'])
            // ->where(['UnitsUsers.unit_id =' => $id, 'UnitsUsers.user_id =' => $user_id])
            //->first();
            ->toArray();

        if ($this->request->is(['patch', 'post', 'put'])) {
            $historicPatientMovement = $this->HistoricPatientMovements->patchEntity($historicPatientMovement, $this->request->data);
            if ($this->HistoricPatientMovements->save($historicPatientMovement)) {
                $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->HistoricPatientMovements->Hospitalizations->find('list', ['limit' => 200]);
        $rooms = $this->HistoricPatientMovements->Rooms->find('list', ['limit' => 200]);
        $this->set(compact('historicPatientMovement', 'hospitalizations', 'rooms', 'sectors'));
        $this->set('_serialize', ['historicPatientMovement']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Historic Patient Movement 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']);
        $historicPatientMovement = $this->HistoricPatientMovements->get($id);
        if ($this->HistoricPatientMovements->delete($historicPatientMovement)) {
            $this->Flash->success(__('The historic patient movement has been deleted.'));
        } else {
            $this->Flash->error(__('The historic patient movement could not be deleted. Please, try again.'));
        }
        return $this->redirect(['action' => 'index']);
    }
}
