<?php
namespace App\Controller;

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

/**
 * SurgicalChecklists Controller
 *
 * @property \App\Model\Table\SurgicalChecklistsTable $SurgicalChecklists
 */
class SurgicalChecklistsController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Permission');
        $this->loadComponent('Upload');
        $this->set('title', 'Checklist');

    }

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

        $session   = $this->request->session();
        $unit_role = $session->read('selected-unit-role-name');

        if (isset($unit_role)) {
            return $this->Permission->hasPermission($unit_role, 'SurgicalChecklists', $action);
        } else {
            return $this->redirect(['controller' => 'users', 'action' => 'login']);
            //return  $this->Permission->hasPermission($user['role_name'], 'sectors', $action);
        }
        //return parent::isAuthorized($user);
    }

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

        $this->paginate = [
            'contain'    => ['NeonatalChecklists', 'DailySafetyChecklists', 'SurgicalChecklists', 'CardiacSurgeryChecklists', 'ObstetricSurgeryChecklists'],
            'conditions' => ['Hospitalizations.id =' => $hospitalizations_id],

        ];

        $hospitalizations_table = TableRegistry::get('Hospitalizations');

        $checklists = $this->paginate($hospitalizations_table);

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

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

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

    /**
     * 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');

        $surgicalChecklist = $this->SurgicalChecklists->newEntity();

        if ($this->request->is('post')) {
            $surgicalChecklist = $this->SurgicalChecklists->patchEntity($surgicalChecklist, $this->request->data);

            if ($this->SurgicalChecklists->save($surgicalChecklist)) {
                $this->Flash->success(__('O checklist foi salvo.'));
                return $this->redirect(['action' => 'index']);

            } else {
                $this->Flash->error(__('O checklist não pode ser salvo. Por favor, tente novamente.'));
            }
        }

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

    /**
     * Edit method
     *
     * @param string|null $id Surgical Checklist 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)
    {
        $surgicalChecklist = $this->SurgicalChecklists->get($id, [
            'contain' => [],
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $surgicalChecklist = $this->SurgicalChecklists->patchEntity($surgicalChecklist, $this->request->data);
            if ($this->SurgicalChecklists->save($surgicalChecklist)) {
                $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->SurgicalChecklists->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('surgicalChecklist', 'hospitalizations'));
        $this->set('_serialize', ['surgicalChecklist']);
    }

    public function printView($id = null)
    {
        $is_print_view = true;
       
        $session       = $this->request->session();

        $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']]);
        $patient                 = $patientTable->get($pacient_id);

        $surgicalChecklist = $this->SurgicalChecklists->get($id, [
            'contain' => [],
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $surgicalChecklist = $this->SurgicalChecklists->patchEntity($surgicalChecklist, $this->request->data);
            if ($this->SurgicalChecklists->save($surgicalChecklist)) {
                $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->SurgicalChecklists->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('is_print_view','patient','hospitalization','unit','surgicalChecklist', 'hospitalizations'));
        $this->set('_serialize', ['surgicalChecklist']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Surgical Checklist 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']);
        $surgicalChecklist = $this->SurgicalChecklists->get($id);
        if ($this->SurgicalChecklists->delete($surgicalChecklist)) {
            $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(['action' => 'index']);
    }

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

        $checklist = $this->SurgicalChecklists->get($id);

        $checklist['is_active'] = false;

        if ($this->SurgicalChecklists->save($checklist)) {
            $this->Flash->success(__('O checklist foi suspenso com sucesso.'));
        } else {
            $this->Flash->error(__('O checklist não pode ser suspenso. Por favor, tente novamente.'));
        }

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

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

        $checklist            = $this->SurgicalChecklists->get($id);
        $checklist->is_active = true;

        if ($this->SurgicalChecklists->save($checklist)) {
            $this->Flash->success(__('O checklist foi ativado com sucesso.'));
        } else {
            $this->Flash->error(__('O checklist não pode ser ativado. Por favor, tente novamente.'));
        }

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