<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Log\Log;
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);

    }

    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' => ['Hospitalizations'],
        ];
        $prescriptions = $this->paginate($this->Prescriptions);

        $this->set(compact('prescriptions'));
        $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()
    {
        $medication_table = TableRegistry::get('Medications');
        $medication       = $medication_table->newEntity();
        $prescription     = $this->Prescriptions->newEntity();
        $session          = $this->request->session();
        $professional_id  = $session->read('Auth.User.id');

        if ($this->request->is('post')) {

            $prescription = $this->Prescriptions->patchEntity($prescription, $this->request->data);

            // $prescription->start_date = date_create($prescription->start_date);
            // $prescription->end_date   = date_create($prescription->end_date);

            // $prescription->start_date = date_format($prescription->start_date, "Y-m-d");
            // $prescription->end_date   = date_format($prescription->end_date, "Y-m-d");
            //$prescription->professionals_id = $professional_id;

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

                $x = $prescription->errors();
                Log::write('debug', 'x');
                Log::write('debug', $x);
                Log::write('debug', $prescription);
            }
        }
        $hospitalizations = $this->Prescriptions->Hospitalizations->find('list', ['limit' => 200]);
        $signs            = $this->Prescriptions->Medications->Signs->find('all', ['limit' => 200]);
        $this->set(compact('prescription', 'hospitalizations', 'medication', 'signs'));
        $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($id = null)
    {
        $prescription = $this->Prescriptions->get($id, [
            'contain' => ['Medications'],
        ]);
        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'));
            }
        }
        $this->set('prescription_id', $id);
        $hospitalizations = $this->Prescriptions->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('prescription', 'hospitalizations'));
        $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, $prescription_id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $prescription = $this->Prescriptions->get($id);
        if ($this->Prescriptions->delete($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]);
    }
}
