<?php
namespace App\Controller;

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

/**
 * Hospitalizations Controller
 *
 * @property \App\Model\Table\HospitalizationsTable $Hospitalizations
 */
class HospitalizationsController extends AppController
{
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('Permission');

        // View or Controller
        $this->set('title', 'Internação');

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

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

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

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $pacient_id = $this->request->session()->read('selected-pacient');

        $this->paginate = [];

        $hospitalization = $this->Hospitalizations->find()
            ->where(['Hospitalizations.patient_id =' => $pacient_id])
            ->order(['Hospitalizations.date_of_hospitalization' => 'desc']);

        $hospitalizations = $this->paginate($hospitalization);

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

    /**
     * View method
     *
     * @param string|null $id Hospitalization id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $hospitalization = $this->Hospitalizations->get($id, [
            //'contain' => ['Patients', 'Screenings', 'Origins', 'Units', 'Bundle', 'CardiacSurgeryChecklists', 'DailySafetyChecklists', 'FugulinAndBraden', 'Infections', 'InitialNutritionalAssessment', 'MedicalBulletins', 'MedicalOpinionRequests', 'Prescriptions']
            'contain' => ['Patients'],
        ]);

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

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

        $hospitalization = $this->Hospitalizations->newEntity();

        $session = $this->request->session();
        $unit_id = $session->read('selected-unit');

        $screeningsTable = TableRegistry::get('Screenings');
        $sectorsTable = TableRegistry::get('Sectors');
        $sectors = $sectorsTable->find()
            ->contain(['Rooms'])

            ->where(['Sectors.unit_id =' => $unit_id])
            ->toArray()
        ;

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

            ->toArray()
        ;

        $cid_groups_table = TableRegistry::get('DiagnosticGroups');
        $cid_groups = $cid_groups_table->find()
            ->toArray()
        ;

        if ($this->request->is('post'))
        {
            $hospitalization = $this->Hospitalizations->patchEntity($hospitalization, $this->request->data);
            $hospitalization['sector_id'] = $hospitalization['historic_patient_movements']['0']['sector_id'];
            if ($this->Hospitalizations->save($hospitalization))
            {
                $this->Flash->success(__('O registro foi salvo.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('The hospitalization could not be saved. Please, try again.'));
            }
        }

        // $comorbidities = $this->Hospitalizations->Comorbidities->find('list', ['limit' => 200]);
        //$systemic_diagnosis = $this->Hospitalizations->SystemicDiagnosis->find('all', ['limit' => 200, 'fields' => ['id', 'name', 'type']]);
        $patients = $this->Hospitalizations->Patients->find('list', ['limit' => 200]);
        $screenings = $screeningsTable->find('list', ['limit' => 200, 'fields' => ['id', 'created']]);
        //$screenings = $this->Hospitalizations->Screenings->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        $origins = $this->Hospitalizations->Origins->find('list', ['limit' => 200]);
        $units = $this->Hospitalizations->Units->find('list', ['limit' => 200]);
        $this->set(compact('systemic_diagnosis', 'hospitalization', 'patients', 'screenings', 'origins', 'units', 'sectors', 'cid_groups', 'cid10'));
        $this->set('_serialize', ['hospitalization']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Hospitalization 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();

        $unit_id = $session->read('selected-unit');
        $sectorsTable = TableRegistry::get('Sectors');
        // $comorbity_table    = TableRegistry::get('Comorbidities');
        // $malformation_table = TableRegistry::get('SystemicDiagnosis');
        $screeningsTable = TableRegistry::get('Screenings');
        $roomsTable = TableRegistry::get('Rooms');
        $sectors = $sectorsTable->find()
            ->contain(['Rooms'])
            ->where(['Sectors.unit_id =' => $unit_id])
            ->toArray()
        ;

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

            ->toArray()
        ;

        $cid_groups_table = TableRegistry::get('DiagnosticGroups');
        $cid_groups = $cid_groups_table->find()
            ->toArray()
        ;

        $hospitalization = $this->Hospitalizations->get($id, [
            'contain' => ['HistoricPatientMovements'],
        ]);

        $roomSelect = $roomsTable->get($hospitalization['historic_patient_movements']['0']['room_id']);

        $sector_id = $roomSelect['sector_id'];

        if ($this->request->is(['patch', 'post', 'put']))
        {
            Log::write('debug', 'data');
            Log::write('debug', $this->request->data);
            $hospitalization = $this->Hospitalizations->patchEntity($hospitalization, $this->request->data);

            $x = $hospitalization->errors();
            Log::write('debug', 'hospitalization');
            Log::write('debug', $hospitalization);
            if (isset($hospitalization->date_of_hospitalization))
            {
                $hospitalization->date_of_hospitalization = new \DateTime($hospitalization->date_of_hospitalization->format('Y-m-d'));
            }

            if ($this->Hospitalizations->save($hospitalization))
            {
                if (isset($this->request->data['delete-comorbity']))
                {
                    // foreach ($this->request->data['delete-comorbity'] as $key => $value) {
                    //     $comorbity = $comorbity_table->get($value['id']);
                    //     $comorbity_table->delete($comorbity);
                    // }
                }

                if (isset($this->request->data['delete-malformation']))
                {
                    // foreach ($this->request->data['delete-malformation'] as $key => $value) {
                    //     $malformation = $malformation_table->get($value['id']);
                    //     $malformation_table->delete($malformation);
                    // }
                }

                $this->Flash->success(__('O registro foi salvo.'));
                return $this->redirect(['action' => 'edit', $id]);
                Log::write('debug', 'hospitalization');
                Log::write('debug', $hospitalization);
            }
            else
            {
                $this->Flash->error(__('The hospitalization could not be saved. Please, try again.'));
                Log::write('debug', 'erro');
                Log::write('debug', $hospitalization->errors());
            }
        }
        //$systemic_diagnosis = $this->Hospitalizations->SystemicDiagnosis->find('all', ['limit' => 200, 'fields' => ['id', 'name', 'type']]);
        //$comorbidities = $this->Hospitalizations->Comorbidities->find('all', ['limit' => 200, 'fields' => ['id', 'name']]);
        $patients = $this->Hospitalizations->Patients->find('list', ['limit' => 200]);
        //$screenings = $this->Hospitalizations->Screenings->find('list', ['limit' => 200]);
        $screenings = $screeningsTable->find('list', ['limit' => 200, 'fields' => ['id', 'created']]);
        $origins = $this->Hospitalizations->Origins->find('list', ['limit' => 200]);
        $units = $this->Hospitalizations->Units->find('list', ['limit' => 200]);
        //$rooms      = $roomsTable->find('list', ['fields' => ['id', 'sector_id']]);
        $this->set(compact('hospitalization', 'patients', 'screenings', 'origins', 'units', 'sectors', 'cid_groups', 'cid10', 'comorbidities', 'sector_id'));
        $this->set('_serialize', ['hospitalization']);
    }

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

    //guarda o id do pacienta na session e redireciona pra pagina de internacao
    public function selectHospitalization($hospitalization_id = null, $action = null, $internation_date = null)
    {
        if ($hospitalization_id !== null && $action !== null)
        {
            $session = $this->request->session();
            $session->write('selected-hospitalization-date', $internation_date);
            $session->write('selected-hospitalization', $hospitalization_id);

            return $this->redirect(['controller' => 'hospitalizations', 'action' => $action, $hospitalization_id]);
        }
    }
}
