<?php
namespace App\Controller;

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

/**
 * SepseProtocols Controller
 *
 * @property \App\Model\Table\SepseProtocolsTable $SepseProtocols
 */
class SepseProtocolsController extends AppController
{

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Auth', [
            'authorize' => 'Controller',
        ]);
        $this->loadComponent('Permission');

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

        $session = $this->request->session();
        $current_state = $session->read('current-state');
        $this->set('current_state', $current_state);
    }

    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');
        $screening_id = $this->request->session()->read('screening_id');
        $current_state = $this->request->session()->read('current-state');
        $patient_id = $this->request->session()->read('selected-pacient');

        if ($current_state == 'internacao')
        {
            $this->paginate = [
                'contain' => ['SepseProtocols', 'ChestPainProtocols', 'SurgicalTevProtocols', 'ClinicTevProtocols'],
                'conditions' => ['Hospitalizations.id =' => $hospitalizations_id],

            ];
            $entity_table = TableRegistry::get('Hospitalizations');
        }
        else
        {
            $this->paginate = [
                'contain' => ['SepseProtocols', 'ChestPainProtocols', 'SurgicalTevProtocols', 'ClinicTevProtocols'],
                'conditions' => ['Screenings.id =' => $screening_id],

            ];
            $entity_table = TableRegistry::get('Screenings');
        }

        $protocols = $this->paginate($entity_table);

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

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

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

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

        $sofa_table = TableRegistry::get('SofaEscores');
        $sofa = $sofa_table
            ->find("all", ['order' => ['SofaEscores.created' => 'DESC']])
            ->where(['SofaEscores.hospitalization_id' => $hospitalization_id])
            //->first()
        ;

        $sepseProtocol = $this->SepseProtocols->newEntity();

        if ($this->request->is('post'))
        {
            $sepseProtocol = $this->SepseProtocols->patchEntity($sepseProtocol, $this->request->data, [
                'associated' => ['SofaEscores'],
            ]);

            if ($this->SepseProtocols->save($sepseProtocol))
            {
                $this->Flash->success(__('O registro foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo'));
                $x = $sepseProtocol->errors();
                Log::write('debug', 'error');
                Log::write('debug', $x);
            }
        }

        $sectors = $this->SepseProtocols->Sectors
            ->find('list', ['limit' => 200, 'fields' => ['id', 'name']])
            ->where(["Sectors.unit_id" => $unit_id])

        ;
        $this->set(compact('sepseProtocol', 'sectors', 'sofa'));
        $this->set('_serialize', ['sepseProtocol']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Sepse Protocol 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();
        $unit_id = $session->read('selected-unit');

        $sepseProtocol = $this->SepseProtocols->get($id, [
            'contain' => ['SofaEscores', 'Sectors'],
        ]);

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

            if ($this->SepseProtocols->save($sepseProtocol))
            {
                $this->Flash->success(__('O registro foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo'));
            }
        }

// $hospitalizations = $this->SepseProtocols->Hospitalizations->find('list', ['limit' => 200]);
        // $screenings       = $this->SepseProtocols->Screenings->find('list', ['limit' => 200]);
        $sectors = $this->SepseProtocols->Sectors
            ->find('list', ['limit' => 200, 'fields' => ['id', 'name']])
            ->where(["Sectors.unit_id" => $unit_id])

        ;

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

    /**
     * Delete method
     *
     * @param string|null $id Sepse Protocol 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']);
        $sepseProtocol = $this->SepseProtocols->get($id);

        if ($this->SepseProtocols->delete($sepseProtocol))
        {
            $this->Flash->success(__('O registro  foi deletado'));
        }
        else
        {
            $this->Flash->error(__('O registro não foi deletado'));
        }

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

    public function printView($id = null)
    {

        
        $session        = $this->request->session();
        $is_print_view  = true;


        $patientTable             = TableRegistry::get('Patients');
        $hospitalizations_table   = TableRegistry::get('Hospitalizations');    
        $units_table              = TableRegistry::get('Units');

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

        
        $unit                    = $units_table->get($unit_id);
        $hospitalization         = $hospitalizations_table->get($hospitalization_id,['contain'=>['Discharges','Sectors']]);
        $unit                    = $units_table->get($unit_id);
        $patient                 = $patientTable->get($pacient_id);

       
        $sepseProtocol = $this->SepseProtocols->get($id, [
            'contain' => ['SofaEscores', 'Sectors'],
        ]);

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

            if ($this->SepseProtocols->save($sepseProtocol))
            {
                $this->Flash->success(__('O registro foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo'));
            }
        }

         // $hospitalizations = $this->SepseProtocols->Hospitalizations->find('list', ['limit' => 200]);
        // $screenings       = $this->SepseProtocols->Screenings->find('list', ['limit' => 200]);
        $sectors = $this->SepseProtocols->Sectors
            ->find('list', ['limit' => 200, 'fields' => ['id', 'name']])
            ->where(["Sectors.unit_id" => $unit_id])
            ->toArray();

        $this->set(compact('is_print_view','hospitalization','patient','unit','sepseProtocol', 'sectors'));
        $this->set('_serialize', ['sepseProtocol']);
    }
}