<?php
namespace App\Controller;

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

/**
 * SafeSurgeryBundles Controller
 *
 * @property \App\Model\Table\SafeSurgeryBundlesTable $SafeSurgeryBundles
 */
class SafeSurgeryBundlesController extends AppController
{

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

        // View or Controller
        $this->set('title', 'Bundle de Cirurgia Segura');

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

        $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'], 'SafeSurgeryBundles', $action);
        //return parent::isAuthorized($user);q
    }

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

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

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

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

    /**
     * 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');
        $date = new \DateTime('now');

        $existe_bundle_dia = $this->SafeSurgeryBundles->find('all')
        ->where(['created like'=>$date->format('Y-m-d').'%', 'hospitalization_id'=> $hospitalization_id]);

        $count_existe_bundle_dia = 0;

        foreach ($existe_bundle_dia as $key => $existe_bundle_di) {
            $count_existe_bundle_dia = 1;
         }

         if($count_existe_bundle_dia){
            $this->Flash->error(__('Já foi criado um bundle de cirurgia segura hoje.'));
            return $this->redirect(['controller'=> 'bundles','action' => 'index']);
        }
        else{
            $pacient_id = $session->read('selected-pacient');

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

            $_age = floor((time() - strtotime($patient["birthday"]->i18nFormat('dd-MM-yyyy'))) / 31556926);

            $cid10_table = TableRegistry::get('Cid10');
            $cid10       = $cid10_table->find()->toArray();

            $safeSurgeryBundle = $this->SafeSurgeryBundles->newEntity();
            if ($this->request->is('post')) {
                $safeSurgeryBundle = $this->SafeSurgeryBundles->patchEntity($safeSurgeryBundle, $this->request->data);
                if ($this->SafeSurgeryBundles->save($safeSurgeryBundle)) {
                    // $this->Flash->success(__('The safe surgery bundle has been saved.'));
                    return $this->redirect(['action' => 'printView',$safeSurgeryBundle->id]);
                } else {
                    $x = $safeSurgeryBundle->errors();
                    Log::write('debug', 'bundle');
                    Log::write('debug', $x);
                    Log::write('debug', $safeSurgeryBundle);
                    $this->Flash->error(__('The safe surgery bundle could not be saved. Please, try again.'));
                }
            }
            $hospitalizations = $this->SafeSurgeryBundles->Hospitalizations->find('list', ['limit' => 200]);
            $typeOfAnesthesias     = $this->SafeSurgeryBundles->TypeOfAnesthesias->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
            $this->set(compact('safeSurgeryBundle', 'hospitalizations', 'cid10', 'typeOfAnesthesias', '_age'));
            $this->set('_serialize', ['safeSurgeryBundle']);
        }
    }

    /**
     * Edit method
     *
     * @param string|null $id Safe Surgery Bundle 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();
        $hospitalization_id = $session->read('selected-hospitalization');
        $pacient_id = $session->read('selected-pacient');

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

        $_age = floor((time() - strtotime($patient["birthday"]->i18nFormat('dd-MM-yyyy'))) / 31556926);

        $cid10_table        = TableRegistry::get('Cid10');
        $cid10              = $cid10_table->find()->toArray();

        $safeSurgeryBundle = $this->SafeSurgeryBundles->get($id, [
            'contain'=>['TypeOfAnesthesias'],
            'conditions' => ['SafeSurgeryBundles.hospitalization_id' => $hospitalization_id],
        ]);

        if ($this->request->is(['patch', 'post', 'put'])) {
            $safeSurgeryBundle = $this->SafeSurgeryBundles->patchEntity($safeSurgeryBundle, $this->request->data);
            if ($this->SafeSurgeryBundles->save($safeSurgeryBundle)) {
                $this->Flash->success(__('The safe surgery bundle has been saved.'));
                return $this->redirect(['controller' => 'Bundles', 'action' => 'index']);

            } else {
                $this->Flash->error(__('The safe surgery bundle could not be saved. Please, try again.'));
            }
        }
        $hospitalizations = $this->SafeSurgeryBundles->Hospitalizations->find('list', ['limit' => 200]);
        $typeOfAnesthesias     = $this->SafeSurgeryBundles->TypeOfAnesthesias->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        $this->set(compact('safeSurgeryBundle', 'hospitalizations', 'cid10', 'typeOfAnesthesias', '_age'));
        $this->set('_serialize', ['safeSurgeryBundle']);
    }

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

        $session->write('bundle_id', $id);

        $patientTable             = TableRegistry::get('Patients');
        $cid10_table              = TableRegistry::get('Cid10');
        $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);
        $cid10                   = $cid10_table->find()->toArray();

        $_age = floor((time() - strtotime($patient["birthday"]->i18nFormat('dd-MM-yyyy'))) / 31556926);


        $safeSurgeryBundle = $this->SafeSurgeryBundles->get($id, [
            'contain'=>['TypeOfAnesthesias'],
            'conditions' => ['SafeSurgeryBundles.hospitalization_id' => $hospitalization_id],
        ]);

        if ($this->request->is(['patch', 'post', 'put'])) {
            $safeSurgeryBundle = $this->SafeSurgeryBundles->patchEntity($safeSurgeryBundle, $this->request->data);
            if ($this->SafeSurgeryBundles->save($safeSurgeryBundle)) {
                $this->Flash->success(__('The safe surgery bundle has been saved.'));
                return $this->redirect(['controller' => 'Bundles', 'action' => 'index']);

            } else {
                $this->Flash->error(__('The safe surgery bundle could not be saved. Please, try again.'));
            }
        }
        $hospitalizations = $this->SafeSurgeryBundles->Hospitalizations->find('list', ['limit' => 200]);
        $typeOfAnesthesias     = $this->SafeSurgeryBundles->TypeOfAnesthesias->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        $this->set(compact('is_print_view','unit','safeSurgeryBundle','patient','hospitalization','hospitalizations', 'cid10', 'typeOfAnesthesias', '_age'));
        $this->set('_serialize', ['safeSurgeryBundle']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Safe Surgery Bundle 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']);
        $safeSurgeryBundle = $this->SafeSurgeryBundles->get($id);
        if ($this->SafeSurgeryBundles->delete($safeSurgeryBundle)) {
            $this->Flash->success(__('The safe surgery bundle has been deleted.'));
        } else {
            $this->Flash->error(__('The safe surgery bundle could not be deleted. Please, try again.'));
        }
        return $this->redirect(['controller'=>'Bundles','action' => 'index']);
    }
}
