<?php
namespace App\Controller;

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

/**
 * MedicalCares Controller
 *
 * @property \App\Model\Table\MedicalCaresTable $MedicalCares
 */
class MedicalCaresController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Auth', [
            'authorize' => 'Controller',
        ]);
        $this->loadComponent('Permission');

        // View or Controller
        $this->set('title', 'Atendimento Médico');

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

        // $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()
    {
        $this->paginate = [
            'contain' => ['Screenings'],
            'order'=>['created'=>'desc']
        ];
        $medicalCares = $this->paginate($this->MedicalCares);

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

    /**
     * View method
     *
     * @param string|null $id Medical Care id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $medicalCare = $this->MedicalCares->get($id, [
            'contain' => ['Screenings', 'Diagnostics', 'MedicationReconciliations'],
        ]);

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $medicalCare = $this->MedicalCares->newEntity();
        if ($this->request->is('post')) {
            $medicalCare = $this->MedicalCares->patchEntity($medicalCare, $this->request->data);
            if ($this->MedicalCares->save($medicalCare)) {
                $this->Flash->success(__('O registro foi salvo'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('O registro não pode ser salvo.'));
            }
        }
        $screenings = $this->MedicalCares->Screenings->find('list', ['limit' => 200]);
        $this->set(compact('medicalCare', 'screenings'));
        $this->set('_serialize', ['medicalCare']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Medical Care 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)
    {
        $medicalCare = $this->MedicalCares->get($id, [
            'contain' => ['HabitualMedications'],
        ]);
        $screening_table = TableRegistry::get('Screenings');
        //$discharge_exist = $hospitalization_table->Discharges->find('all',['limit' => 200])->first() );

        if ($this->request->is(['patch', 'post', 'put'])) {
            $medicalCare = $this->MedicalCares->patchEntity($medicalCare, $this->request->data);
            if ($this->MedicalCares->save($medicalCare)) {
                $this->Flash->success(__('O registro foi salvo'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('O registro não pode ser salvo.'));
            }
        }
        $screenings = $this->MedicalCares->Screenings->find('list', ['limit' => 200]);
        $this->set(compact('medicalCare', 'screenings'));
        $this->set('_serialize', ['medicalCare']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Medical Care 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']);
        $medicalCare = $this->MedicalCares->get($id);
        if ($this->MedicalCares->delete($medicalCare)) {
            $this->Flash->success(__('O registro foi deletado'));
        } else {
            $this->Flash->error(__('O registro não pode ser deletado.'));
        }
        return $this->redirect(['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);


        $medicalCare = $this->MedicalCares->get($id, [
            'contain' => ['HabitualMedications'],
        ]);
        $screening_table = TableRegistry::get('Screenings');
        //$discharge_exist = $hospitalization_table->Discharges->find('all',['limit' => 200])->first() );

        if ($this->request->is(['patch', 'post', 'put'])) {
            $medicalCare = $this->MedicalCares->patchEntity($medicalCare, $this->request->data);
            if ($this->MedicalCares->save($medicalCare)) {
                $this->Flash->success(__('O registro foi salvo'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('O registro não pode ser salvo.'));
            }
        }
        $screenings = $this->MedicalCares->Screenings->find('list', ['limit' => 200]);
        $this->set(compact('unit','is_print_view','patient','medicalCare', 'screenings'));
        $this->set('_serialize', ['medicalCare']);
    }
}
