<?php
namespace App\Controller;

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

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

        // View or Controller
        $this->set('title', 'Evolução');

        $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 = $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()
    {
        $query = null;
        $cond  = [];
        $param = $this->request;

        if (isset($param->query['status']) || isset($param->query['profession']) || isset($param->query['date_of_completion'])) {

            if ($param->query['status'] != "") {
                $cond[] = 'Evolutions.status LIKE "%' . $param->query['status'] . '%"';
            }

            if ($param->query['profession'] != "") {
                $cond[] = 'Evolutions.profissao LIKE "%' . $param->query['profession'] . '%"';
            }

            if ($param->query['date_of_completion'] != "") {
                $cond[] = 'Evolutions.date_of_completion LIKE "%' . $param->query['date_of_completion'] . '%"';
            }

            // echo "<pre>";
            // print_r($cond);
            // exit;

            $query = $this->Evolutions->find()
                ->where($cond);
            //->contain(['Units'])
            //->leftJoinWith('Units.Sectors')
            //->order(['Users.created' => 'desc']);
        } else {
            $query = $this->Evolutions->find();
        }

        $evolutions = $this->paginate($query);
        // $this->paginate = [
        //     'contain' => ['Professionals', 'Hospitalizations'],
        // ];

        // $evolutions = $this->paginate($this->Evolutions);

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

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $evolution = $this->Evolutions->newEntity();

        if ($this->request->is('post')) {
            $session          = $this->request->session();
            $selected_unit_id = $session->read('selected-unit');
            $user_id          = $session->read('Auth.User.id');

            $professional_table = TableRegistry::get('Professionals');
            $professional       = $professional_table->find()
                ->where(['unit_id' => $selected_unit_id, 'user_id' => $user_id])
                ->first();

            // if ($this->request->data['date_of_completion']) {
            //     $date_of_completion = \DateTime::createFromFormat('d/m/Y', $this->request->data['date_of_completion']);
            //     $this->request->data['date_of_completion'] = $date_of_completion->format("Y-m-d");
            // }

            $evolution                     = $this->Evolutions->patchEntity($evolution, $this->request->data);
            $evolution->professional_id    = $professional['id'];
            $evolution->nome_prof          = $session->read('Auth.User.name');
            $evolution->profissao          = $professional['name'];
            $evolution->numero_do_conselho = $professional['concil_number'];
            // echo "<pre>";
            // print_r($this->request->data);
            // exit;

            if ($this->Evolutions->save($evolution)) {
                $this->Flash->success(__('The register has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                // $x = $evolution->errors();
                // debug($evolution);
                // debug($x);
                // echo "<pre> professional";
                // print_r($professional);
                // exit;
                $this->Flash->error(__('The register could not be saved. Please, try again.'));
            }
        }

        //$professionals = $this->Evolutions->Professionals->find('list', ['limit' => 200]);
        //$hospitalizations = $this->Evolutions->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('evolution', 'professionals', 'hospitalizations'));
        $this->set('_serialize', ['evolution']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Evolution 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)
    {
        $evolution = $this->Evolutions->get($id, [
            'contain' => [],
        ]);

        if ($this->request->is(['patch', 'post', 'put'])) {
            // if ($this->request->data['date_of_completion']) {
            //     $date_of_completion = \DateTime::createFromFormat('d/m/Y', $this->request->data['date_of_completion']);
            //     $this->request->data['date_of_completion'] = $date_of_completion->format("Y-m-d");
            // }

            $evolution = $this->Evolutions->patchEntity($evolution, $this->request->data);

            if ($this->Evolutions->save($evolution)) {
                $this->Flash->success(__('The register has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The register could not be saved. Please, try again.'));
            }
        }

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

    /**
     * Delete method
     *
     * @param string|null $id Evol ution 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']);
        $evolution = $this->Evolutions->get($id);
        if ($this->Evolutions->delete($evolution)) {
            $this->Flash->success(__('The register has been deleted.'));
        } else {
            $this->Flash->error(__('The register could not be deleted. Please, try again.'));
        }
        return $this->redirect(['action' => 'index']);
    }

    public function printView($id = null)
    {
        $session          = $this->request->session();
        $selected_unit_id = $session->read('selected-unit');
        $pacient_id            = $session->read('selected-pacient');

        $patientTable             = TableRegistry::get('Patients');
        $hospitalizations_table   = TableRegistry::get('Hospitalizations');
        $units_table              = TableRegistry::get('Units');
        $hospitalization_id    = $session->read('selected-hospitalization');

        $unit      = $units_table->get($selected_unit_id);
        $evolution = $this->Evolutions->get($id);
        $hospitalization         = $hospitalizations_table->get($hospitalization_id,['contain'=>['Discharges','Sectors']]);
        $patient                 = $patientTable->get($pacient_id);

        
        $this->set(compact('evolution', 'unit', 'patient', 'hospitalization'));
        $this->set('_serialize', ['evolution', 'patient', 'hospitalization']);
    }
}
