<?php
namespace App\Controller;

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

/**
 * Bundles Controller
 *
 * @property \App\Model\Table\BundlesTable $Bundles
 */
class BundlesController extends AppController
{

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

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

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

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

    }

    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');
        $entity_table        = null;

        if ($current_state == 'internacao') {
            $this->paginate = [
                'contain'    => ['Bundles', 'PavPreventionBundles', 'SafeSurgeryBundles', 'ItuPreventionBundles'],
                'conditions' => ['Hospitalizations.id =' => $hospitalizations_id],

            ];
            $entity_table = TableRegistry::get('Hospitalizations');
        } else {
            $this->paginate = [
                'contain'    => ['Bundles', 'PavPreventionBundles', 'SafeSurgeryBundles', 'ItuPreventionBundles'],
                'conditions' => ['Screenings.id =' => $screening_id],

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

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

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

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

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

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

        $existe_bundle_dia = $this->Bundles->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 hoje.'));
            return $this->redirect(['action' => 'index']);
        }
        else{
            //exit;
            if ($itu != null) {
                $itu = true;
            } else {
                $itu = false;
            }
            $bundle = $this->Bundles->newEntity();

            if ($this->request->is('post')) {
                $bundle = $this->Bundles->patchEntity($bundle, $this->request->data);
                /*echo "<pre>";
                print_r($bundle);*/
                if ($this->Bundles->save($bundle)) {
                    // $this->Flash->success(__('O registro foi salvo.'));
                    return $this->redirect(['action' => 'printView',$bundle->id]);
                } else {
                    $x = $bundle->errors();
                    Log::write('debug', 'bundle');
                    Log::write('debug', $x);
                    Log::write('debug', $bundle);
                    $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente novamente.'));
                }
            }
            $professionals          = $this->Bundles->Professionals->find('list', ['limit' => 200]);
            $hospitalizations       = $this->Bundles->Hospitalizations->find('list', ['limit' => 200]);
            $screenings             = $this->Bundles->Screenings->find('list', ['limit' => 200]);
            $immediateComplications = $this->Bundles->ImmediateComplications->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])->where(["ImmediateComplications.type <> '2'", "ImmediateComplications.type <> '3'"]);
            $this->set(compact('bundle', 'professionals', 'hospitalizations', 'screenings', 'itu', 'immediateComplications'));
            $this->set('_serialize', ['bundle']);
        }


    }

    /**
     * Edit method
     *
     * @param string|null $id 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, $itu = null)
    {
        if ($itu != null) {
            $itu = true;
        } else {
            $itu = false;
        }

        $session    = $this->request->session();
        $pacient_id = $session->write('bundle_id', $id);

        $bundle = $this->Bundles->get($id, [
            'contain' => ['ImmediateComplications'],
        ]);

        if ($this->request->is(['patch', 'post', 'put'])) {
            $bundle = $this->Bundles->patchEntity($bundle, $this->request->data);
            if ($this->Bundles->save($bundle)) {
                $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.'));
            }
        }
        $professionals          = $this->Bundles->Professionals->find('list', ['limit' => 200]);
        $hospitalizations       = $this->Bundles->Hospitalizations->find('list', ['limit' => 200]);
        $screenings             = $this->Bundles->Screenings->find('list', ['limit' => 200]);
        $immediateComplications = $this->Bundles->ImmediateComplications->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])->where(["ImmediateComplications.type <> '2'", "ImmediateComplications.type <> '3'"]);
        $this->set(compact('bundle', 'professionals', 'hospitalizations', 'screenings', 'itu', 'immediateComplications'));
        $this->set('_serialize', ['bundle']);
    }

    public function printView($id = null, $itu = 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);


        if ($itu != null)
        {
            $itu = true;
        }
        else
        {
            $itu = false;
        }







        $bundle = $this->Bundles->get($id, [
            'contain' => ['ImmediateComplications'],
        ]);

        if ($this->request->is(['patch', 'post', 'put'])) {
            $bundle = $this->Bundles->patchEntity($bundle, $this->request->data);
            if ($this->Bundles->save($bundle)) {
                $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.'));
            }
        }
        $professionals          = $this->Bundles->Professionals->find('list', ['limit' => 200]);
        $hospitalizations       = $this->Bundles->Hospitalizations->find('list', ['limit' => 200]);
        $screenings             = $this->Bundles->Screenings->find('list', ['limit' => 200]);
        $immediateComplications = $this->Bundles->ImmediateComplications->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        $this->set(compact('is_print_view','unit','bundle', 'professionals','patient','hospitalization', 'hospitalizations', 'screenings', 'itu', 'immediateComplications'));
        $this->set('_serialize', ['bundle']);
    }

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