<?php
namespace App\Controller;

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

/**
 * DailySafetyChecklists Controller
 *
 * @property \App\Model\Table\DailySafetyChecklistsTable $DailySafetyChecklists
 */
class DailySafetyChecklistsController extends AppController
{

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

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

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

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

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

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

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $dailySafetyChecklist = $this->DailySafetyChecklists->newEntity();

        if ($this->request->is('post')) {
            $dailySafetyChecklist = $this->DailySafetyChecklists->patchEntity($dailySafetyChecklist, $this->request->data);
            if ($this->DailySafetyChecklists->save($dailySafetyChecklist)) {
                $this->Flash->success(__('The daily safety checklist has been saved.'));
                return $this->redirect(['controller' => 'SurgicalChecklists', 'action' => 'index']);
            } else {
                $this->Flash->error(__('The daily safety checklist could not be saved. Please, try again.'));
                Log::write('debug', $dailySafetyChecklist);
                Log::write('debug', $dailySafetyChecklist->errors());
            }
        }
        $hospitalizations = $this->DailySafetyChecklists->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('dailySafetyChecklist', 'hospitalizations'));
        $this->set('_serialize', ['dailySafetyChecklist']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Daily Safety 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)
    {
        $dailySafetyChecklist = $this->DailySafetyChecklists->get($id, [
            'contain' => [],
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $dailySafetyChecklist = $this->DailySafetyChecklists->patchEntity($dailySafetyChecklist, $this->request->data);
            if ($this->DailySafetyChecklists->save($dailySafetyChecklist)) {
                $this->Flash->success(__('The daily safety checklist has been saved.'));
                return $this->redirect(['controller' => 'SurgicalChecklists', 'action' => 'index']);
            } else {
                $this->Flash->error(__('The daily safety checklist could not be saved. Please, try again.'));
            }
        }
        $hospitalizations = $this->DailySafetyChecklists->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('dailySafetyChecklist', 'hospitalizations'));
        $this->set('_serialize', ['dailySafetyChecklist']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Daily Safety 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']);
        $dailySafetyChecklist = $this->DailySafetyChecklists->get($id);
        if ($this->DailySafetyChecklists->delete($dailySafetyChecklist)) {
            $this->Flash->success(__('The daily safety checklist has been deleted.'));
        } else {
            $this->Flash->error(__('The daily safety checklist could not be deleted. Please, try again.'));
        }
        return $this->redirect(['controller' => 'SurgicalChecklists', 'action' => 'index']);
    }

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

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

        $checklist['is_active'] = false;

        if ($this->DailySafetyChecklists->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->DailySafetyChecklists->get($id);
        $checklist->is_active = true;

        if ($this->DailySafetyChecklists->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']);
    }

    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);

        $dailySafetyChecklist = $this->DailySafetyChecklists->get($id, [
            'contain' => [],
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $dailySafetyChecklist = $this->DailySafetyChecklists->patchEntity($dailySafetyChecklist, $this->request->data);
            if ($this->DailySafetyChecklists->save($dailySafetyChecklist)) {
                $this->Flash->success(__('The daily safety checklist has been saved.'));
                return $this->redirect(['controller' => 'SurgicalChecklists', 'action' => 'index']);
            } else {
                $this->Flash->error(__('The daily safety checklist could not be saved. Please, try again.'));
            }
        }
        $hospitalizations = $this->DailySafetyChecklists->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('is_print_view','unit','patient','hospitalization','dailySafetyChecklist', 'hospitalizations'));
        $this->set('_serialize', ['dailySafetyChecklist']);
    }
}