<?php
namespace App\Controller;

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

/**
 * MedicalOpinionRequests Controller
 *
 * @property \App\Model\Table\MedicalOpinionRequestsTable $MedicalOpinionRequests
 */
class MedicalOpinionRequestsController extends AppController
{
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('Permission');

        // View or Controller
        $this->set('title', 'Parecer 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);

        $unit_role_name = $session->read('selected-unit-role-nameQualidade');
        $this->set('unit_role_name', $unit_role_name);
    }

    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()
    {
        $user_id = $this->request->session()->read('Auth.User.id');

        $session = $this->request->session();
        $hospitalization_id = $session->read('selected-hospitalization');

        $this->paginate = [
            'contain' => ['Users', 'Hospitalizations', 'Specialties', 'MedicalOpinionAnswers'],
            'conditions' => ['MedicalOpinionRequests.hospitalization_id' => $hospitalization_id],
            'order' => ['created' => 'desc'],
        ];

        $medicalOpinionRequests = $this->paginate($this->MedicalOpinionRequests);

        $professionalTable = TableRegistry::get('Professionals');
        $professionals = $professionalTable->find()
            ->contain(['Specialties'])
            ->where(['Professionals.user_id =' => $user_id])
        ;
        $professionals = $professionals->toArray();

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

    /**
     * View method
     *
     * @param string|null $id Medical Opinion Request id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $medicalOpinionRequest = $this->MedicalOpinionRequests->get($id, [
            'contain' => ['Users', 'Hospitalizations', 'MedicalOpinionAnswers', 'Specialties'],
        ]);

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

    /**
     * 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');
        $pacient_id = $session->read('selected-pacient');

        $hospitalization_table = TableRegistry::get('Hospitalizations');

        // $specialtiesTable = TableRegistry::get('Specialties');
        // $specialties = $specialtiesTable->find('list', ['limit' => 200]);

        $medicalOpinionRequest = $this->MedicalOpinionRequests->newEntity();

        if ($this->request->is('post'))
        {
            $patient_movement_table = TableRegistry::get('HistoricPatientMovements');
            $patient_movement = $patient_movement_table
                ->find('all')
                ->where(['HistoricPatientMovements.hospitalization_id' => $hospitalization_id])
                ->contain(['Rooms' => ['Sectors' => ['Types']]])
                ->order(['HistoricPatientMovements.created' => 'DESC'])
                ->first();

            $medicalOpinionRequest = $this->MedicalOpinionRequests->patchEntity($medicalOpinionRequest, $this->request->data);
            $medicalOpinionRequest->sector_id = $patient_movement['room']['sector_id'];

            // Log::write('debug', '$errors');

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

            $hospitalization = $hospitalization_table
                ->find()
                ->where(['Hospitalizations.id' => $hospitalization_id])
                ->first()
                ->toArray()
            ;

            // Log::write('debug', '$hospitalization');

            // Log::write('debug', $hospitalization);

            //verifica qual o setor o paciente foi internado e vincula no parecer
            if ($hospitalization['sector_id'])
            {
                $medicalOpinionRequest->sector_id = $hospitalization['sector_id'];
            }

            if ($this->MedicalOpinionRequests->save($medicalOpinionRequest))
            {
                $this->Flash->success(__('O parecer médico foi salvo.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                //Log::write('debug', $medicalOpinionRequest->errors());

                $this->Flash->error(__('O parecer médico não pode ser salvo. Por favor, tente novamente.'));
            }
        }

        $this->set('hospitalization_id', $hospitalization_id);
        $specialties = $this->MedicalOpinionRequests->Specialties->find('list', ['limit' => 200]);
        //$professionals = $this->MedicalOpinionRequests->Professionals->find('list', ['limit' => 200]);

        $hospitalizations = $this->MedicalOpinionRequests->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('medicalOpinionRequest', 'hospitalizations', 'specialties'));
        $this->set('_serialize', ['medicalOpinionRequest']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Medical Opinion Request 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();
        $hospitalization_id = $session->read('selected-hospitalization');
        $hospitalization_table = TableRegistry::get('Hospitalizations');

        $medicalOpinionRequest = $this->MedicalOpinionRequests->get($id, [
            'contain' => ['MedicalOpinionAnswers'],
        ]);

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

            $hospitalization = $hospitalization_table
                ->find()
                ->where(['Hospitalizations.id' => $hospitalization_id])
                ->first()
                ->toArray()
            ;

            if ($hospitalization['sector_id'])
            {
                $medicalOpinionRequest->sector_id = $hospitalization['sector_id'];
            }

            if ($this->MedicalOpinionRequests->save($medicalOpinionRequest))
            {
                $this->Flash->success(__('O parecer médico foi salvo.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O parecer médico não foi salvo. Por favor, tente novamente.'));
            }
        }

        $this->set('hospitalization_id', $hospitalization_id);
        $specialties = $this->MedicalOpinionRequests->Specialties->find('list', ['limit' => 200]);
        //$professionals = $this->MedicalOpinionRequests->Professionals->find('list', ['limit' => 200]);
        $hospitalizations = $this->MedicalOpinionRequests->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('medicalOpinionRequest', 'hospitalizations', 'specialties'));
        $this->set('_serialize', ['medicalOpinionRequest']);
    }

    public function printView($id = null)
    {
        $session = $this->request->session();
        $hospitalization_id = $session->read('selected-hospitalization');
        $patientTable = TableRegistry::get('Patients');
        $historicPatientMovementsTable = TableRegistry::get('HistoricPatientMovements');
        $sectorsTable = TableRegistry::get('Sectors');
        $hospitalization_table = TableRegistry::get('Hospitalizations');
        $roomsTable = TableRegistry::get('Rooms');

        $medicalOpinionRequest = $this->MedicalOpinionRequests->get($id, [
            'contain' => ['Users', 'MedicalOpinionAnswers.Users'],
        ]);

        $is_print_view = true;
        $units_table = TableRegistry::get('Units');
        $pacient_id = $session->read('selected-pacient');
        $unit_id = $session->read('selected-unit');
        $unit = $units_table->get($unit_id);
        $patient = $patientTable->get($pacient_id);

        // hospitalização
        $hospitalization = $hospitalization_table
            ->find()
            ->where(['Hospitalizations.id' => $hospitalization_id])
            ->first()
        ;

        // ultima movimentação do paciente
        $historicPatientMovement = $historicPatientMovementsTable->find()
            ->where(['HistoricPatientMovements.hospitalization_id' => $hospitalization_id])
            ->order(['id' => 'DESC'])
            ->first()
        ;

        // ultimo leito relacionado ao paciente
        $room = $roomsTable->get($historicPatientMovement['room_id'], ['contain' => 'Sectors.Types']);

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

            if ($hospitalization['sector_id'])
            {
                $medicalOpinionRequest->sector_id = $hospitalization['sector_id'];
            }

            if ($this->MedicalOpinionRequests->save($medicalOpinionRequest))
            {
                $this->Flash->success(__('O parecer médico foi salvo.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O parecer médico não foi salvo. Por favor, tente novamente.'));
            }
        }

        $this->set('hospitalization_id', $hospitalization_id);
        $specialties = $this->MedicalOpinionRequests->Specialties->find('list', ['limit' => 200]);
        //$professionals = $this->MedicalOpinionRequests->Professionals->find('list', ['limit' => 200]);
        $hospitalizations = $this->MedicalOpinionRequests->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('room', 'historicPatientMovement', 'hospitalization', 'patient', 'unit', 'is_print_view', 'medicalOpinionRequest', 'hospitalizations', 'specialties'));
        $this->set('_serialize', ['medicalOpinionRequest']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Medical Opinion Request 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']);
        $medicalOpinionRequest = $this->MedicalOpinionRequests->get($id);

        if ($this->MedicalOpinionRequests->delete($medicalOpinionRequest))
        {
            $this->Flash->success(__('O parecer médico foi deletado.'));
        }
        else
        {
            $this->Flash->error(__('O parecer médico não pode ser deletado. Por favor, tente novamente.'));
        }

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

    public function toggleMedicalRequest($id = null, $status = false)
    {
        //if ($id && $status) {
        $this->request->allowMethod(['post', 'toggleMedicalRequest']);
        $MedicalOpinionRequests = $this->MedicalOpinionRequests->get($id);

        $MedicalOpinionRequests['is_active'] = $status;

        if ($this->MedicalOpinionRequests->save($MedicalOpinionRequests))
        {
            $this->Flash->success(__('O registro foi suspenso com sucesso.'));
        }
        else
        {
            $this->Flash->error(__('O registro não pode ser suspenso. Por favor, tente novamente.'));
        }

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