<?php
namespace App\Controller;

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

/**
 * Diagnostics Controller
 *
 * @property \App\Model\Table\DiagnosticsTable $Diagnostics
 */
class DiagnosticsController extends AppController
{

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

        // View or Controller
        $this->set('title', 'Diagnóstico');

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

        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $hospitalization       = $hospitalization_table->get($hospitalization_id, []);
        $this->set('hospitalization_data', $hospitalization);

    }

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

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

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

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['Patients', 'Hospitalizations', 'Origins', 'MedicalCares'],
        ];
        $diagnostics = $this->paginate($this->Diagnostics);

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

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

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

    /**
     * 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');

        $diagnostic = $this->Diagnostics->newEntity();
        $param      = $this->request;
        $cid10_code = null;

        // if (isset($param->query['cid10_code']) && $param->query['cid10_code'] !== null) {
        //     $cid10      = TableRegistry::get('Cid10');
        //     $cid10_code = $param->query['cid10_code'];

        //     $query = $cid10->find()
        //         ->where(['Cid10.cid_cod LIKE' => $cid10_code . '%'])
        //         ->first()
        //     //    ->toArray()
        //     ;

        //     //  $query->innerJoinWith('Units')
        //     //     ->distinct(['Patients.id'])
        //     //     ->where(['Units.id =' =>  $unit_id])
        //     // ;
        //     $this->set('cid10', $query);

        // }

        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $hospitalizations      = $hospitalization_table->findById($hospitalization_id)
            ->first()
            ->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')) {
            $diagnostic = $this->Diagnostics->patchEntity($diagnostic, $this->request->data);

            if ($this->Diagnostics->save($diagnostic)) {
                $this->Flash->success(__('O registro foi salvo.'));
                return $this->redirect(['action' => 'index']);

            } else {
                Log::write('debug', $diagnostic);
                Log::write('debug', $diagnostic->errors());
                //return;
                $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente novamente.'));
            }
        }

        $malformations         = $this->Diagnostics->Malformations->find('all', ['limit' => 200, 'fields' => ['id', 'name', 'type']]);
        $systemic_diagnosis    = $this->Diagnostics->SystemicDiagnosis->find('all', ['limit' => 200, 'fields' => ['id', 'name', 'type']]);
        $defects_and_anomalies = $this->Diagnostics->DefectsAndAnomalies->find('all', ['limit' => 200]);
        $comorbidities         = $this->Diagnostics->Comorbidities->find('list', ['limit' => 200]);
        $otherComorbidities    = $this->Diagnostics->OtherComorbidities->find('list', ['limit' => 200]);
        $patients              = $this->Diagnostics->Patients->find('list', ['limit' => 200]);
        $hospitalizations      = $this->Diagnostics->Hospitalizations->find('list', ['limit' => 200]);
        $origins               = $this->Diagnostics->Origins->find('list', ['limit' => 200]);
        $medicalCares          = $this->Diagnostics->MedicalCares->find('list', ['limit' => 200]);
        $this->set(compact('hospitalizations', 'diagnostic', 'patients', 'hospitalizations', 'origins', 'comorbidities', 'cid10', 'malformations', 'defects_and_anomalies', 'cid_groups', 'systemic_diagnosis'));
        $this->set('_serialize', ['diagnostic']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Diagnostic 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)
    {
        $comorbity_table          = TableRegistry::get('Comorbidities');
        $systemic_diagnosis_table = TableRegistry::get('SystemicDiagnosis');
        $malformation_table       = TableRegistry::get('Malformations');

        $diagnostic = $this->Diagnostics->get($id, [
            'contain' => ['Comorbidities', 'SystemicDiagnosis', 'Malformations'],
        ]);

        $cid10_table = TableRegistry::get('Cid10');
        $cid10       = $cid10_table->find()
            ->contain(['DiagnosticGroups'])
            ->toArray()
        ;

        if ($this->request->is(['patch', 'post', 'put'])) {
            $diagnostic = $this->Diagnostics->patchEntity($diagnostic, $this->request->data);
            if ($this->Diagnostics->save($diagnostic)) {

                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-systemic-diagnosis'])) {
                    foreach ($this->request->data['delete-systemic-diagnosis'] as $key => $value) {
                        $systemic_diagnosis = $systemic_diagnosis_table->get($value['id']);
                        $systemic_diagnosis_table->delete($systemic_diagnosis);
                    }
                }

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

        $malformations    = $this->Diagnostics->Malformations->find('all', ['limit' => 200, 'fields' => ['id', 'name', 'type']]);
        $comorbidities    = $this->Diagnostics->Comorbidities->find('list', ['limit' => 200]);
        $patients         = $this->Diagnostics->Patients->find('list', ['limit' => 200]);
        $hospitalizations = $this->Diagnostics->Hospitalizations->find('list', ['limit' => 200]);
        $origins          = $this->Diagnostics->Origins->find('list', ['limit' => 200]);
        $medicalCares     = $this->Diagnostics->MedicalCares->find('list', ['limit' => 200]);
        $this->set(compact('malformations', 'diagnostic', 'patients', 'hospitalizations', 'origins', 'medicalCares', 'cid10', 'comorbidities'));
        $this->set('_serialize', ['diagnostic']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Diagnostic 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']);
        $diagnostic = $this->Diagnostics->get($id);
        if ($this->Diagnostics->delete($diagnostic)) {
            $this->Flash->success(__('O registro foi deletado.'));
        } else {
            $this->Flash->error(__('O registro não pode ser deletado. Por favor, tente novamente.'));
        }
        return $this->redirect(['action' => 'index']);
    }

}
