<?php
namespace App\Controller;

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

/**
 * Medications Controller
 *
 * @property \App\Model\Table\MedicationsTable $Medications
 */
class MedicationsController extends AppController
{

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

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

    }

    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()
    {
        $this->paginate = [
            'contain' => ['Prescriptions', 'Signs', 'Professionals'],
        ];
        $medications = $this->paginate($this->Medications);

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

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add($prescription_id = null)
    {
        $historic_table = TableRegistry::get('MedicationsHistoric');
        $historic       = $historic_table->newEntity();

        $medication = $this->Medications->newEntity();
        if ($this->request->is('post')) {

            $medication                  = $this->Medications->patchEntity($medication, $this->request->data);
            $medication->prescription_id = $prescription_id;

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

            if ($this->Medications->save($medication)) {

                $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(['controller' => 'Prescriptions', 'action' => 'edit', $prescription_id]);

            } else {
                $this->Flash->error(__('O registro não foi salvo'));
            }
        }
        //$prescriptions = $this->Medications->Prescriptions->find('list', ['limit' => 200]);
        $signs    = $this->Medications->Signs->find('all', ['limit' => 200]);
        $cultures = $this->Medications->Cultures->find('all', [
            'conditions' => ['Cultures.resultado >' => 'Positivo'],
            'limit'      => 200,
        ]);
        $this->set('prescription_id', $prescription_id);
        //$professionals = $this->Medications->Professionals->find('list', ['limit' => 200]);
        $this->set(compact('medication', 'prescriptions', 'signs', 'professionals', 'cultures'));
        $this->set('_serialize', ['medication']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Medication 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, $prescription_id = null)
    {
        $historic_table = TableRegistry::get('MedicationsHistoric');
        $historic       = $historic_table->newEntity();

        $medication = $this->Medications->get($id, [
            'contain' => ['Signs', 'Cultures'],
        ]);

        if ($this->request->is(['patch', 'post', 'put'])) {

            $medication = $this->Medications->patchEntity($medication, $this->request->data);

            if ($this->Medications->save($medication)) {

                $historic->medication_id = $medication->id;
                $historic->name          = $medication->name;
                $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);
                Log::write('debug', $medication);
                Log::write('debug', 'historic');
                Log::write('debug', $historic);

                $this->Flash->success(__('O registro foi salvo'));
                //return $this->redirect(['controller' => 'MedicationsHistoric', 'action' => 'index', $id, $prescription_id]);
                return $this->redirect(['controller' => 'prescriptions', 'action' => 'edit', $prescription_id]);
            } else {
                $this->Flash->error(__('O registro não foi salvo'));
            }
        }
        $this->set('prescription_id', $prescription_id);

        $prescriptions = $this->Medications->Prescriptions->find('list', ['limit' => 200]);
        $signs         = $this->Medications->Signs->find('all', ['limit' => 200]);
        $professionals = $this->Medications->Professionals->find('list', ['limit' => 200]);
        $cultures      = $this->Medications->Cultures->find('list', [
            'fields'     => ['id', 'germe'],
            'conditions' => ['Cultures.resultado' => 'Positivo'],
            'limit'      => 200,
        ]);
        // $cultures = $cultures->toArray();

        $this->set(compact('medication', 'prescriptions', 'signs', 'professionals', 'cultures'));
        $this->set('_serialize', ['medication']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Medication id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($medication_id = null, $prescription_id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $medication = $this->Medications->get($medication_id);
        if ($this->Medications->delete($medication)) {
            $this->Flash->success(__('O registro foi deletado'));
        } else {
            $this->Flash->error(__('O registro não foi deletado'));
        }
        return $this->redirect(['controller' => 'Prescriptions', 'action' => 'edit', $prescription_id]);
    }
}
