<?php
namespace App\Controller;

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

/**
 * PavPreventionBundles Controller
 *
 * @property \App\Model\Table\PavPreventionBundlesTable $PavPreventionBundles
 */
class PavPreventionBundlesController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Permission');
        $this->set('title', 'Bundles');

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

        $screening_id = $session->read('screening_id');
        $this->set('screening_id', $screening_id);

        $hospitalization_id = $session->read('selected-hospitalization');
        $this->set('hospitalization_id', $hospitalization_id);

        $bundle_id = $session->read('bundle_id');
        $this->set('bundle_id', $bundle_id);

    }

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

        return $this->Permission->hasPermission($user['role_name'], 'PavPreventionBundles', $action);

        //return parent::isAuthorized($user);
    }

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

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

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

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

    /**
     * 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->PavPreventionBundles->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 pav hoje.'));
            return $this->redirect(['controller'=> 'bundles','action' => 'index']);
        }
        else{
            $pavPreventionBundle = $this->PavPreventionBundles->newEntity();
            if ($this->request->is('post')) {
                $pavPreventionBundle = $this->PavPreventionBundles->patchEntity($pavPreventionBundle, $this->request->data);
                //echo "<pre>";
                //print_r($pavPreventionBundle);
                if ($this->PavPreventionBundles->save($pavPreventionBundle)) {
                    // $this->Flash->success(__('The pav prevention bundle has been saved.'));
                    return $this->redirect(['action' => 'printView',$pavPreventionBundle->id]);
                } else {
                    $this->Flash->error(__('The pav prevention bundle could not be saved. Please, try again.'));
                }
            }
            $hospitalizations       = $this->PavPreventionBundles->Hospitalizations->find('list', ['limit' => 200]);
            $professionals          = $this->PavPreventionBundles->Professionals->find('list', ['limit' => 200]);
            $immediateComplications = $this->PavPreventionBundles->ImmediateComplications->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])->where(["ImmediateComplications.type <> '1'", "ImmediateComplications.type <> '3'"]);
            $this->set(compact('pavPreventionBundle', 'hospitalizations', 'professionals', 'immediateComplications'));
            $this->set('_serialize', ['pavPreventionBundle']);
        }
    }

    /**
     * Edit method
     *
     * @param string|null $id Pav Prevention 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();
        $bundle_id = $session->write('bundle_id', $id);

        $pavPreventionBundle = $this->PavPreventionBundles->get($id, [
            'contain' => ["ImmediateComplications"],
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $pavPreventionBundle = $this->PavPreventionBundles->patchEntity($pavPreventionBundle, $this->request->data);
            if ($this->PavPreventionBundles->save($pavPreventionBundle)) {
                $this->Flash->success(__('The pav prevention bundle has been saved.'));
                return $this->redirect(['controller' => 'Bundles', 'action' => 'index']);
            } else {
                $this->Flash->error(__('The pav prevention bundle could not be saved. Please, try again.'));
            }
        }
        $hospitalizations       = $this->PavPreventionBundles->Hospitalizations->find('list', ['limit' => 200]);
        $professionals          = $this->PavPreventionBundles->Professionals->find('list', ['limit' => 200]);
        $immediateComplications = $this->PavPreventionBundles->ImmediateComplications->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])->where(["ImmediateComplications.type <> '1'", "ImmediateComplications.type <> '3'"]);
        $this->set(compact('immediateComplications', 'pavPreventionBundle', 'hospitalizations', 'professionals', 'bundle_id'));
        $this->set('_serialize', ['pavPreventionBundle']);
    }

     public function printView($id = null)
    {
        $is_print_view = true;

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

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

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

        $pavPreventionBundle = $this->PavPreventionBundles->get($id, [
            'contain' => ["ImmediateComplications"],
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $pavPreventionBundle = $this->PavPreventionBundles->patchEntity($pavPreventionBundle, $this->request->data);
            if ($this->PavPreventionBundles->save($pavPreventionBundle)) {
                $this->Flash->success(__('The pav prevention bundle has been saved.'));
                return $this->redirect(['controller' => 'Bundles', 'action' => 'index']);
            } else {
                $this->Flash->error(__('The pav prevention bundle could not be saved. Please, try again.'));
            }
        }
        $hospitalizations       = $this->PavPreventionBundles->Hospitalizations->find('list', ['limit' => 200]);
        $professionals          = $this->PavPreventionBundles->Professionals->find('list', ['limit' => 200]);
        $immediateComplications = $this->PavPreventionBundles->ImmediateComplications->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])->where(["ImmediateComplications.type <> '1'"]);
        $this->set(compact('is_print_view','unit','immediateComplications','patient','hospitalization','pavPreventionBundle', 'hospitalizations', 'professionals', 'bundle_id'));
        $this->set('_serialize', ['pavPreventionBundle']);
    }

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