<?php
namespace App\Controller;

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

/**
 * ApacheIiScores Controller
 *
 * @property \App\Model\Table\ApacheIiScoresTable $ApacheIiScores
 */
class ApacheIiScoresController 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)
    {
        $action = $this->request->params['action'];

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

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

        // $this->paginate = [
        //     'contain' => ['Hospitalizations'],
        // ];
        $this->paginate = [
            'contain'    => ['NasScores', 'ApacheIiScores', 'PreDeliricScores', 'SnapIiScores', 'SapsIiiScores', 'SofaEscores', 'CribScores', 'CurbScores'],
            'conditions' => ['Hospitalizations.id =' => $hospitalizations_id],

        ];
        $hospitalizations_table = TableRegistry::get('Hospitalizations');
        $scores                 = $this->paginate($hospitalizations_table);

        //$apacheIiScores = $this->paginate($this->ApacheIiScores);

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

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

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

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

        $patientTable = TableRegistry::get('Patients');
        $patient      = $patientTable->get($pacient_id)->toArray();

        $hospitalizationTable = TableRegistry::get('Hospitalizations');
        $hospitalization      = $hospitalizationTable->get($hospitalization_id)->toArray();

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

    /**
     * Edit method
     *
     * @param string|null $id Apache Ii 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)
    {
        $session            = $this->request->session();
        $pacient_id         = $session->read('selected-pacient');
        $hospitalization_id = $session->read('selected-hospitalization');

        $patientTable = TableRegistry::get('Patients');
        $patient      = $patientTable->get($pacient_id)->toArray();

        $hospitalizationTable = TableRegistry::get('Hospitalizations');
        $hospitalization      = $hospitalizationTable->get($hospitalization_id)->toArray();

        $apacheIiScore = $this->ApacheIiScores->get($id, [
            'contain' => [],
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $apacheIiScore = $this->ApacheIiScores->patchEntity($apacheIiScore, $this->request->data);
            if ($this->ApacheIiScores->save($apacheIiScore)) {
                $this->Flash->success(__('O registro foi salvo..'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('O registro não foi salvo. Por favor, tente novamente.'));
            }
        }
        $hospitalizations = $this->ApacheIiScores->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('apacheIiScore', 'hospitalization', 'patient'));
        $this->set('_serialize', ['apacheIiScore']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Apache Ii 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']);
        $apacheIiScore = $this->ApacheIiScores->get($id);
        if ($this->ApacheIiScores->delete($apacheIiScore)) {
            $this->Flash->success(__('O registro foi deletado'));
        } else {
            $this->Flash->error(__('O registro não foi deletado. Por favor, tente novamente.'));
        }
        return $this->redirect(['action' => 'index']);
    }


    public function printView($id = null)
    {
        $session            = $this->request->session();
        $pacient_id         = $session->read('selected-pacient');
        $hospitalization_id = $session->read('selected-hospitalization');

        $is_print_view = true;
        $units_table   = TableRegistry::get('Units');
        $unit_id       = $session->read('selected-unit');
        $unit          = $units_table->get($unit_id);

        $patientTable = TableRegistry::get('Patients');
        $patient      = $patientTable->get($pacient_id)->toArray();

        $hospitalizationTable = TableRegistry::get('Hospitalizations');
        $hospitalization         = $hospitalizationTable->get($hospitalization_id,['contain'=>['Discharges','Sectors']]);

        $apacheIiScore = $this->ApacheIiScores->get($id, [
            'contain' => [],
        ]);

        if ($this->request->is(['patch', 'post', 'put']))
        {
            $apacheIiScore = $this->ApacheIiScores->patchEntity($apacheIiScore, $this->request->data);
            if ($this->ApacheIiScores->save($apacheIiScore))
            {
                $this->Flash->success(__('O registro foi salvo.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo. Por favor, tente novamente.'));
            }
        }

        $hospitalizations = $this->ApacheIiScores->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('unit','is_print_view','apacheIiScore', 'hospitalization', 'patient'));
        $this->set('_serialize', ['apacheIiScore']);
    }

}