<?php
namespace App\Controller;

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

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

        // View or Controller
        $this->set('title', 'Prescrições');

        $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 = $this->request->session()->read('current-state');
        $this->set('current_state', $current_state);
    }

    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');
        $screening_id = $this->request->session()->read('screening_id');
        $current_state = $this->request->session()->read('current-state');
        $lastPrescriptionId = 0;

        if ($current_state == 'internacao')
        {
            $allPresc = $this->Prescriptions->find('all',
                [
                    'conditions' => ['Prescriptions.hospitalization_id' => $hospitalization_id],
                    'order' => ['id' => 'DESC'],
                    'limit' => 1,
                ]);

            $lastPrescription = $allPresc->toArray();

            if (isset($lastPrescription[0]['id']))
            {
                $lastPrescriptionId = $lastPrescription[0]['id'];
            }

            $this->paginate = [
                'contain' => [],
                'conditions' => [
                    'Prescriptions.is_active' => 1,
                    'Prescriptions.hospitalization_id' => $hospitalization_id,
                ],
                'order' => ['created' => 'desc'],
            ];
        }
        else
        {
            $allPresc = $this->Prescriptions->find('all',
                [
                    'conditions' => ['Prescriptions.screening_id' => $screening_id],
                    'order' => ['id' => 'DESC'],
                    'limit' => 1,
                ]);

            $lastPrescription = $allPresc->toArray();

            if (isset($lastPrescription[0]['id']))
            {
                $lastPrescriptionId = $lastPrescription[0]['id'];
            }

            $this->paginate = [
                'contain' => [],
                'conditions' => [
                    'Prescriptions.is_active' => 1,
                    'Prescriptions.screening_id' => $screening_id,
                ],
                'order' => ['created' => 'desc'],
            ];
        }

        $prescriptions = $this->paginate($this->Prescriptions);

        $this->set(compact('prescriptions', 'lastPrescriptionId', 'lastPrescription', 'screening_id'));
        $this->set('_serialize', ['prescriptions']);
    }

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add($lastPrescriptionId = null)
    {
        $cultures_table = TableRegistry::get('Cultures');
        $medication_table = TableRegistry::get('Medications');
        $historic_table = TableRegistry::get('MedicationsHistoric');
        $patient_movement_table = TableRegistry::get('HistoricPatientMovements');

        $medication = $medication_table->newEntity();
        $prescription = $this->Prescriptions->newEntity();
        $session = $this->request->session();
        $professional_id = $session->read('Auth.User.id');
        $unit_id = $session->read('selected-unit');
        $lastPrescription = [];
        $session = $this->request->session();
        $hospitalization_id = $session->read('selected-hospitalization');
        $associated = ['Medications.Cultures'];

        $cultures_with_germs = $cultures_table->find('list', [
            'fields' => ['id', 'germe'],
            'conditions' => ["Cultures.hospitalization_id" => $hospitalization_id, 'Cultures.resultado' => 1],
        ]);

        if ($lastPrescriptionId)
        {
            $lastPrescription = $medication_table
                ->find('all')
                ->contain(['Cultures'])
                ->where(["Medications.prescription_id" => $lastPrescriptionId])
                ->toArray()
            ;
            $numberOfMedications = count($lastPrescription);
        }

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


            $prescription = $this->Prescriptions->patchEntity($prescription, $this->request->data, ['associated' => [
                'Medications', 'Medications.Cultures',
            ]]);

            $prescription->sector_id = $patient_movement['room']['sector_id'];

            if ($this->Prescriptions->save($prescription, ['associated' => ['Medications', 'Medications.Cultures']]))
            {
                if (isset($prescription->medications))
                {
                    foreach ($prescription->medications as $key => $medication)
                    {
                        $historic = $historic_table->newEntity();
                        $historic->name = $medication->name;
                        $historic->medication_id = $medication->id;
                        $historic->dosage = $medication->dosage;
                        $historic->channel = $medication->channel;
                        $historic->frequency = $medication->frequency;
                        $historic->start_date = $medication->start_date;
                        $historic->end_date = $medication->end_date;
                        $historic->created = $medication->created;
                        $historic->is_antibiotic = $medication->is_antibiotic;
                        $historic->sign_id = $medication->sign_id;

                        $historic_table->save($historic);
                    }
                }

                $this->Flash->success(__('O registro  foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
        }

        $signs = $this->Prescriptions->Medications->Signs
            ->find('all', ['limit' => 200])
            ->where(["Signs.unit_id" => $unit_id]);
        $this->set(compact('prescription', 'hospitalizations', 'signs', 'lastPrescription', 'cultures_with_germs', 'numberOfMedications'));
        $this->set('_serialize', ['prescription']);
    }

/**
 * Edit method
 *
 * @param string|null $id Prescription 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($prescription_id = null)
    {
        $cultures_table = TableRegistry::get('Cultures');
        $session = $this->request->session();
        $unit_id = $session->read('selected-unit');
        $hospitalization_id = $session->read('selected-hospitalization');

        $cultures_with_germs = $cultures_table->find('list')
            ->where(["Cultures.hospitalization_id" => $hospitalization_id, 'Cultures.resultado' => 1])
        ;

        $i = 0;
        $cultures_ids = [];

        foreach ($cultures_with_germs as $key => $culture)
        {
            $cultures_ids[$i] = $culture['id'];
            $i++;
        }

        $prescription = $this->Prescriptions->get($prescription_id, [
            'contain' => ['Medications.Cultures'],
        ]);

        // inicio filtrando só as medicações ativas na prescrição
        $active_medications = [];
        $i = 0;

        if (isset($prescription->medications))
        {
            foreach ($prescription->medications as $key => $medication)
            {
                if ($medication['is_active'])
                {
                    $active_medications[$i] = $medication;
                }

                $i++;
            }
        }

        $prescription->medications = $active_medications;

        // fim filtrando só as medicações ativas na prescrição

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

            if ($this->Prescriptions->save($prescription))
            {
                $this->Flash->success(__('O registro  foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo'));
            }
        }

        $signs = $this->Prescriptions->Medications->Signs
            ->find('all', ['limit' => 200])
            ->where(["Signs.unit_id" => $unit_id]);
        $this->set(compact('prescription', 'prescription_id', 'cultures_with_germs', 'cultures_ids', 'active_medications'));
        $this->set('_serialize', ['prescription']);
    }

    public function printView($prescription_id = null)
    {
        $session = $this->request->session();

        $patientTable = TableRegistry::get('Patients');
        $hospitalizations_table = TableRegistry::get('Hospitalizations');
        $cultures_table = TableRegistry::get('Cultures');
        $units_table = TableRegistry::get('Units');

        $unit_id = $session->read('selected-unit');
        $pacient_id = $session->read('selected-pacient');
        $hospitalization_id = $session->read('selected-hospitalization');
        $unit_id = $session->read('selected-unit');
        $is_print_view = true;

        $hospitalization = $hospitalizations_table->get($hospitalization_id, ['contain' => 'Discharges']);
        $unit = $units_table->get($unit_id);
        $patient = $patientTable->get($pacient_id);

        $cultures_with_germs = $cultures_table->find('list', [
            'fields' => ['germe', 'tipo_resistencia'],
            'conditions' => ["Cultures.hospitalization_id" => $hospitalization_id, 'Cultures.resultado' => 1],
        ])->toArray();

        //monatndo uma escala niveis de resistencia
        $niveis_resistencia = [
            'Sem resistência' => 0,
            'Resistente' => 1,
            'Multiresistente' => 2,
            'Panresistente' => 3,
        ];

        // montando um array das resistências de todos os germes e atribuindo os valores numéricos dos níveis
        $resistesncias = [];
        foreach ($cultures_with_germs as $key => $resistencia)
        {
            if ($resistencia)
            {
                $resistesncias[$resistencia] = $niveis_resistencia[$resistencia];
            }
        }
        //pegando a resistencia de nível mais alto
        $top_resitence = '';
        if( count($resistesncias) > 0 ){
            $top_resitence = array_search(max($resistesncias), $resistesncias);
        }

        $prescription = $this->Prescriptions->get($prescription_id, [
            'contain' => ['Medications.Cultures'],
        ]);

        // inicio filtrando só as medicações ativas na prescrição
        $active_medications = [];
        $i = 0;

        if (isset($prescription->medications))
        {
            foreach ($prescription->medications as $key => $medication)
            {
                if ($medication['is_active'])
                {
                    $active_medications[$i] = $medication;
                }

                $i++;
            }
        }

        $prescription->medications = $active_medications;

        // fim filtrando só as medicações ativas na prescrição

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

            if ($this->Prescriptions->save($prescription))
            {
                $this->Flash->success(__('O registro  foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo'));
            }
        }

        $signs = $this->Prescriptions->Medications->Signs
            ->find('all', ['limit' => 200])
            ->where(["Signs.unit_id" => $unit_id]);
        $this->set(compact('top_resitence', 'hospitalization', 'patient', 'is_print_view', 'unit', 'prescription', 'prescription_id', 'cultures_with_germs', 'active_medications'));
        $this->set('_serialize', ['prescription']);
    }

    public function printRecipes($prescription_id = null)
    {
        $session = $this->request->session();

        $patientTable = TableRegistry::get('Patients');
        $hospitalizations_table = TableRegistry::get('Hospitalizations');
        $cultures_table = TableRegistry::get('Cultures');
        $units_table = TableRegistry::get('Units');

        $unit_id = $session->read('selected-unit');
        $pacient_id = $session->read('selected-pacient');
        $hospitalization_id = $session->read('selected-hospitalization');
        $unit_id = $session->read('selected-unit');
        $is_print_view = true;

        $hospitalization = $hospitalizations_table->get($hospitalization_id, ['contain' => 'Discharges']);
        $unit = $units_table->get($unit_id);
        $patient = $patientTable->get($pacient_id);

        $cultures_with_germs = $cultures_table->find('list', [
            'fields' => ['germe', 'tipo_resistencia'],
            'conditions' => ["Cultures.hospitalization_id" => $hospitalization_id, 'Cultures.resultado' => 1],
        ])->toArray();

        // echo"<pre>";
        //   print_r($cultures_with_germs);
        // echo"</pre>";

        //monatndo uma escala niveis de resistencia
        $niveis_resistencia = [
            'Sem resistência' => 0,
            'Resistente' => 1,
            'Multiresistente' => 2,
            'Panresistente' => 3,
        ];

        // montando um array das resistências de todos os germes e atribuindo os valores numéricos dos níveis
        $resistesncias = [];
        foreach ($cultures_with_germs as $key => $resistencia)
        {
            if ($resistencia)
            {
                $resistesncias[$resistencia] = $niveis_resistencia[$resistencia];
            }
        }
        //pegando a resistencia de nível mais alto
        $top_resitence = '';
        if( count($resistesncias) > 0 ){
            $top_resitence = array_search(max($resistesncias), $resistesncias);
        }
        
        $prescription = $this->Prescriptions->get($prescription_id, [
            'contain' => ['Medications.Cultures'],
        ]);

        // inicio filtrando só as medicações ativas na prescrição
        $active_medications = [];
        $i = 0;

        if (isset($prescription->medications))
        {
            foreach ($prescription->medications as $key => $medication)
            {
                if ($medication['is_active'])
                {
                    $active_medications[$i] = $medication;
                }

                $i++;
            }
        }

        $prescription->medications = $active_medications;

// fim filtrando só as medicações ativas na prescrição

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

            if ($this->Prescriptions->save($prescription))
            {
                $this->Flash->success(__('O registro  foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo'));
            }
        }

        $signs = $this->Prescriptions->Medications->Signs
            ->find('all', ['limit' => 200])
            ->where(["Signs.unit_id" => $unit_id]);
        $this->set(compact('top_resitence', 'hospitalization', 'patient', 'is_print_view', 'unit', 'prescription', 'prescription_id', 'cultures_with_germs', 'active_medications'));
        $this->set('_serialize', ['prescription']);
    }

    public function printJustification($prescription_id = null)
    {
        $session = $this->request->session();

        $patientTable = TableRegistry::get('Patients');
        $hospitalizations_table = TableRegistry::get('Hospitalizations');
        $cultures_table = TableRegistry::get('Cultures');
        $units_table = TableRegistry::get('Units');

        $unit_id = $session->read('selected-unit');
        $pacient_id = $session->read('selected-pacient');
        $hospitalization_id = $session->read('selected-hospitalization');
        $unit_id = $session->read('selected-unit');
        $is_print_view = true;

        $hospitalization = $hospitalizations_table->get($hospitalization_id, ['contain' => 'Discharges']);
        $unit = $units_table->get($unit_id);
        $patient = $patientTable->get($pacient_id);

        $cultures_with_germs = $cultures_table->find('list', [
            'fields' => ['germe', 'tipo_resistencia'],
            'conditions' => ["Cultures.hospitalization_id" => $hospitalization_id, 'Cultures.resultado' => 1],
        ])->toArray();

        // echo"<pre>";
        //   print_r($cultures_with_germs);
        // echo"</pre>";

        //monatndo uma escala niveis de resistencia
        $niveis_resistencia = [
            'Sem resistência' => 0,
            'Resistente' => 1,
            'Multiresistente' => 2,
            'Panresistente' => 3,
        ];

        // montando um array das resistências de todos os germes e atribuindo os valores numéricos dos níveis
        $resistesncias = [];
        foreach ($cultures_with_germs as $key => $resistencia)
        {
            if ($resistencia)
            {
                $resistesncias[$resistencia] = $niveis_resistencia[$resistencia];
            }
        }
        //pegando a resistencia de nível mais alto
        $top_resitence = '';
        if( count($resistesncias) > 0 ){
            $top_resitence = array_search(max($resistesncias), $resistesncias);
        }

        $prescription = $this->Prescriptions->get($prescription_id, [
            'contain' => ['Medications.Cultures'],
        ]);

        // inicio filtrando só as medicações ativas na prescrição
        $active_medications = [];
        $i = 0;

        if (isset($prescription->medications))
        {
            foreach ($prescription->medications as $key => $medication)
            {
                if ($medication['is_active'])
                {
                    $active_medications[$i] = $medication;
                }

                $i++;
            }
        }

        $prescription->medications = $active_medications;

// fim filtrando só as medicações ativas na prescrição

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

            if ($this->Prescriptions->save($prescription))
            {
                $this->Flash->success(__('O registro  foi salvo'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não foi salvo'));
            }
        }

        $signs = $this->Prescriptions->Medications->Signs
            ->find('all', ['limit' => 200])
            ->where(["Signs.unit_id" => $unit_id]);
        $this->set(compact('top_resitence', 'hospitalization', 'patient', 'is_print_view', 'unit', 'prescription', 'prescription_id', 'cultures_with_germs', 'active_medications'));
        $this->set('_serialize', ['prescription']);
    }

/**
 * Delete method
 *
 * @param string|null $id Prescription 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']);

        $prescription = $this->Prescriptions->get($id);

        //somente desativar a Prescription e não deletar
        $prescription['is_active'] = 0;

        if ($this->Prescriptions->save($prescription))
        {
            $this->Flash->success(__('O registro foi deletado'));
        }
        else
        {

            $this->Flash->error(__('O registro não foi deletado'));
        }

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