<?php
namespace App\Controller;

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

/**
 * SuspectedMeProtocols Controller
 *
 * @property \App\Model\Table\SuspectedMeProtocolsTable $SuspectedMeProtocols
 */
class SuspectedMeProtocolsController extends AppController
{

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

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

        $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()
    {
        $session = $this->request->session();
        $hospitalization_id = $session->read('selected-hospitalization');

        $this->paginate = [
            'contain' => ['Hospitalizations'],
            'conditions' => ['SuspectedMeProtocols.hospitalization_id' => $hospitalization_id],
            'order' => ['created' => 'desc'],
        ];
        $suspectedMeProtocols = $this->paginate($this->SuspectedMeProtocols);

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

    /**
     * View method
     *
     * @param string|null $id Suspected Me Protocol id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $suspectedMeProtocol = $this->SuspectedMeProtocols->get($id, [
            'contain' => ['Hospitalizations', 'SupplementaryExaminations'],
        ]);

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

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

        $exam_table = TableRegistry::get('SupplementaryExaminations');
        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $suspectedMeProtocol = $this->SuspectedMeProtocols->newEntity();

        if ($this->request->is('post'))
        {
            $session = $this->request->session();
            $hospitalization_id = $session->read('selected-hospitalization');

            //clear null values in organs sedative drugs
            if (isset($this->request->data['sedative_drugs']))
            {
                foreach ($this->request->data['sedative_drugs'] as $key => $value)
                {
                    if (array_key_exists("nome", $value)) {
                        if ($value['nome'] == '' || $value['nome'] == null)
                        {
                            unset($this->request->data['sedative_drugs'][$key]);
                        }
                    }

                }
            }

            //clear null values in organs
            if (isset($this->request->data['obtained_organs_from_corpses']))
            {
                foreach ($this->request->data['obtained_organs_from_corpses'] as $key => $value)
                {
                    if (array_key_exists("name", $value)) {
                        if ($value['name'] == '' || $value['name'] == null)
                        {
                            unset($this->request->data['obtained_organs_from_corpses'][$key]);
                        }
                    }
                }
            }

            $suspectedMeProtocol = $this->SuspectedMeProtocols->patchEntity($suspectedMeProtocol, $this->request->data,[
             'associated' => ['LaboratoryExaminations','SupplementaryExaminations', 'SedativeDrugs', 'Organs', 'ObtainedOrgansFromCorpses','PotentialOrgans']
            ]);

            $exam = $exam_table->patchEntity($suspectedMeProtocol, $this->request->data['supplementary_examinations']);

            $suspectedMeProtocol->hospitalization_id = $hospitalization_id;

            $data_confirmacao = '';
            $me_confirmada = 0;
            if(isset($suspectedMeProtocol['supplementary_examinations'])){
                foreach ($suspectedMeProtocol['supplementary_examinations'] as $key => $supplementary_examination) {
                    if($supplementary_examination['me_confirmada']){
                        $data_confirmacao = $supplementary_examination['data_confirmacao'];
                        $me_confirmada = 1;
                    }
                }
            }
            if($suspectedMeProtocol['me_confirmada']){
                $data_confirmacao = $suspectedMeProtocol['data_confirmacao'];
                $me_confirmada = 1;
            }

            //verifica se o paciente morreu
            if ($suspectedMeProtocol->nao_houve_captacao ||
                !empty($suspectedMeProtocol->obtained_organs_from_corpses) ||
                !empty($suspectedMeProtocol->organs) || $me_confirmada)
            {

                $hospitalization = $hospitalization_table->get($hospitalization_id);
                $hospitalization->status = 'obito';
                if($me_confirmada){
                    $hospitalization->data_alta_obito = $data_confirmacao;
                }
                $hospitalization_table->save($hospitalization);
            }

            Log::write('debug', '$suspectedMeProtocol');
            Log::write('debug', $suspectedMeProtocol);

            if ($this->SuspectedMeProtocols->save($suspectedMeProtocol))
            {
                $this->Flash->success(__('O registro foi salvo.'));
                //return $this->redirect(['controller' => 'SepseProtocols', 'action' => 'index']);

                return $this->redirect(['action' => 'index']);
            }
            else
            {

                Log::write('debug', '$suspectedMeProtocol');
                Log::write('debug', $suspectedMeProtocol);
                Log::write('debug', $suspectedMeProtocol->errors());

                $this->Flash->error(__('O registro não pode ser salvo.'));
            }
        }

        $organs = $this->SuspectedMeProtocols->Organs
            ->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])
            ->toArray()

        ;
        $potential_organs = $this->SuspectedMeProtocols->PotentialOrgans
            ->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])
            ->toArray()
        ;

        $this->set(compact('suspectedMeProtocol', 'organs', 'potential_organs'));
        $this->set('_serialize', ['suspectedMeProtocol']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Suspected Me Protocol 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)
    {
        $organsSuspectedMeProtocol_table = TableRegistry::get('OrgansSuspectedMeProtocols');
        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $sedativeDrugs_table             = TableRegistry::get('SedativeDrugs');
        $obtainedOrgansFromCorpses_table = TableRegistry::get('ObtainedOrgansFromCorpses');

        $suspectedMeProtocol = $this->SuspectedMeProtocols->get($id, [
            'contain' => ['LaboratoryExaminations','SupplementaryExaminations', 'SedativeDrugs', 'Organs', 'ObtainedOrgansFromCorpses', 'PotentialOrgans'],
        ]);

        if ($this->request->is(['patch', 'post', 'put']))
        {
            //clear null values in organs sedative drugs
            if (isset($this->request->data['sedative_drugs']))
            {
                foreach ($this->request->data['sedative_drugs'] as $key => $value)
                {
                    if (array_key_exists("nome", $value)) {
                        if ($value['nome'] == '' || $value['nome'] == null)
                        {
                            unset($this->request->data['sedative_drugs'][$key]);
                        }
                    }

                }
            }

            //clear null values in organs
            if (isset($this->request->data['obtained_organs_from_corpses']))

            {
                foreach ($this->request->data['obtained_organs_from_corpses'] as $key => $value)
                {
                    if (array_key_exists("name", $value)) {
                        if ($value['name'] == '' || $value['name'] == null)
                        {
                            unset($this->request->data['obtained_organs_from_corpses'][$key]);
                        }
                    }
                }
            }

            // exclusão de drogas sedativas
            if (isset($this->request->data['delete_sedative_drugs']))//clear null values
            {
                $delete_array = $this->request->data['delete_sedative_drugs'];

                $condition = array('SedativeDrugs.id in' => $delete_array);

                $sedativeDrugs_table->deleteAll($condition,false);
            }

            // exclusão de orgãos
            if (isset($this->request->data['delete_obtained_organs']))//clear null values
            {
                $delete_array = $this->request->data['delete_obtained_organs'];

                $condition = array('ObtainedOrgansFromCorpses.id in' => $delete_array);

                $obtainedOrgansFromCorpses_table->deleteAll($condition,false);
            }

            $suspectedMeProtocol = $this->SuspectedMeProtocols->patchEntity($suspectedMeProtocol, $this->request->data);

            //move os órgãos potencias para o atributo correto e seta a flag

            // foreach ($suspectedMeProtocol->potential_organs['_ids'] as $key => $value)

            // {

            //     $obj = new \stdClass();

            //     $obj->id = $value;

            //     $obj->potential_organ = true;

            //     array_push($suspectedMeProtocol->organs, $obj);

            // }
            $data_confirmacao = '';
            $me_confirmada = 0;
            if(isset($suspectedMeProtocol['supplementary_examinations'])){
                foreach ($suspectedMeProtocol['supplementary_examinations'] as $key => $supplementary_examination) {
                    if($supplementary_examination['me_confirmada']){
                        $data_confirmacao = $supplementary_examination['data_confirmacao'];
                        $me_confirmada = 1;
                    }
                }
            }
            if($suspectedMeProtocol['me_confirmada']){
                $data_confirmacao = $suspectedMeProtocol['data_confirmacao'];
                $me_confirmada = 1;
            }

            //verifica se o paciente morreu
            if ($suspectedMeProtocol->nao_houve_captacao ||
                !empty($suspectedMeProtocol->obtained_organs_from_corpses) ||
                !empty($suspectedMeProtocol->organs) || $me_confirmada)
            {

                $hospitalization = $hospitalization_table->get($hospitalization_id);
                $hospitalization->status = 'obito';
                if($me_confirmada){
                    $hospitalization->data_alta_obito = $data_confirmacao;
                }
                $hospitalization_table->save($hospitalization);
            }

            if ($this->SuspectedMeProtocols->save($suspectedMeProtocol))
            {
                $this->Flash->success(__('O Registro foi salvo.'));

                return $this->redirect(['action' => 'index']);
            }
            else
            {
                Log::write('debug', '$suspectedMeProtocol');
                Log::write('debug', $suspectedMeProtocol);
                Log::write('debug', $suspectedMeProtocol->errors());
                $this->Flash->error(__('O registro não pode ser salvo.'));
            }
        }

        $organs = $this->SuspectedMeProtocols->Organs
            ->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])
        ;
        $potential_organs = $this->SuspectedMeProtocols->PotentialOrgans
            ->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])
        ;
        $this->set(compact('suspectedMeProtocol', 'organs', 'potential_organs'));
        $this->set('_serialize', ['suspectedMeProtocol']);
    }


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

        $organsSuspectedMeProtocol_table = TableRegistry::get('OrgansSuspectedMeProtocols');

        $suspectedMeProtocol = $this->SuspectedMeProtocols->get($id, [
            'contain' => ['SupplementaryExaminations', 'SedativeDrugs', 'Organs', 'ObtainedOrgansFromCorpses', 'PotentialOrgans'],
        ]);

        if ($this->request->is(['patch', 'post', 'put']))
        {
            if (isset($this->request->data['sedative_drugs'])) //clear null values
            {
                foreach ($this->request->data['sedative_drugs'] as $key => $value)
                {
                    if (!$value['nome'])
                    {
                        unset($this->request->data['sedative_drugs'][$key]);
                    }
                }
            }

            if (isset($this->request->data['obtained_organs_from_corpses']))//clear null values

            {
                foreach ($this->request->data['obtained_organs_from_corpses'] as $key => $value)
                {
                    if (!$value['nome'])
                    {
                        unset($this->request->data['obtained_organs_from_corpses'][$key]);
                    }
                }
            }

            $suspectedMeProtocol = $this->SuspectedMeProtocols->patchEntity($suspectedMeProtocol, $this->request->data);

            //move os órgãos potencias para o atributo correto e seta a flag

            // foreach ($suspectedMeProtocol->potential_organs['_ids'] as $key => $value)

            // {

            //     $obj = new \stdClass();

            //     $obj->id = $value;

            //     $obj->potential_organ = true;

            //     array_push($suspectedMeProtocol->organs, $obj);

            // }

            if ($this->SuspectedMeProtocols->save($suspectedMeProtocol))
            {
                $this->Flash->success(__('O Registro foi salvo.'));

                return $this->redirect(['action' => 'index']);
            }
            else
            {
                Log::write('debug', '$suspectedMeProtocol');
                Log::write('debug', $suspectedMeProtocol);
                Log::write('debug', $suspectedMeProtocol->errors());
                $this->Flash->error(__('O registro não pode ser salvo.'));
            }
        }

        $organs = $this->SuspectedMeProtocols->Organs
            ->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])
        ;
        $potential_organs = $this->SuspectedMeProtocols->PotentialOrgans
            ->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])
        ;
        $this->set(compact('is_print_view','hospitalization','unit','patient','suspectedMeProtocol', 'organs', 'potential_organs'));
        $this->set('_serialize', ['suspectedMeProtocol']);
    }


    public function printDeathDeclaration($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);

        $organsSuspectedMeProtocol_table = TableRegistry::get('OrgansSuspectedMeProtocols');

        $suspectedMeProtocol = $this->SuspectedMeProtocols->get($id, [
            'contain' => ['SupplementaryExaminations', 'SedativeDrugs', 'Organs', 'ObtainedOrgansFromCorpses', 'PotentialOrgans'],
        ]);

        if ($this->request->is(['patch', 'post', 'put']))
        {
            if (isset($this->request->data['sedative_drugs'])) //clear null values
            {
                foreach ($this->request->data['sedative_drugs'] as $key => $value)
                {
                    if (!$value['nome'])
                    {
                        unset($this->request->data['sedative_drugs'][$key]);
                    }
                }
            }

            if (isset($this->request->data['obtained_organs_from_corpses']))//clear null values

            {
                foreach ($this->request->data['obtained_organs_from_corpses'] as $key => $value)
                {
                    if (!$value['nome'])
                    {
                        unset($this->request->data['obtained_organs_from_corpses'][$key]);
                    }
                }
            }

            $suspectedMeProtocol = $this->SuspectedMeProtocols->patchEntity($suspectedMeProtocol, $this->request->data);

            //move os órgãos potencias para o atributo correto e seta a flag

            // foreach ($suspectedMeProtocol->potential_organs['_ids'] as $key => $value)

            // {

            //     $obj = new \stdClass();

            //     $obj->id = $value;

            //     $obj->potential_organ = true;

            //     array_push($suspectedMeProtocol->organs, $obj);

            // }

            if ($this->SuspectedMeProtocols->save($suspectedMeProtocol))
            {
                $this->Flash->success(__('O Registro foi salvo.'));

                return $this->redirect(['action' => 'index']);
            }
            else
            {
                Log::write('debug', '$suspectedMeProtocol');
                Log::write('debug', $suspectedMeProtocol);
                Log::write('debug', $suspectedMeProtocol->errors());
                $this->Flash->error(__('O registro não pode ser salvo.'));
            }
        }

        $organs = $this->SuspectedMeProtocols->Organs
            ->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])
        ;
        $potential_organs = $this->SuspectedMeProtocols->PotentialOrgans
            ->find('list', ['limit' => 200, 'fields' => ['id', 'nome']])
        ;
        $this->set(compact('is_print_view','hospitalization','unit','patient','suspectedMeProtocol', 'organs', 'potential_organs'));
        $this->set('_serialize', ['suspectedMeProtocol']);
    }





    /**
     * Delete method
     *
     * @param string|null $id Suspected Me Protocol 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']);
        $suspectedMeProtocol = $this->SuspectedMeProtocols->get($id);

        if ($this->SuspectedMeProtocols->delete($suspectedMeProtocol))
        {
            $this->Flash->success(__('The suspected me protocol has been deleted.'));
        }
        else
        {
            $this->Flash->error(__('The suspected me protocol could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}
