<?php
namespace App\Controller;

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

/**
 * Screenings Controller
 *
 * @property \App\Model\Table\ScreeningsTable $Screenings
 */
class ScreeningsController extends AppController
{

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

        // View or Controller
        $this->set('title', 'Triagem');

        $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()
    {
        $pacient_id = $this->request->session()->read('selected-pacient');
        
        $this->paginate = [
            'contain' => ['Patients', 'Units'],
            'order' => ['created' => 'desc'],
            'conditions' => ['Screenings.patient_id' => $pacient_id],
        ];
        $screenings = $this->paginate($this->Screenings);

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

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {

        $session = $this->request->session();
        $patient_id = $session->read('selected-pacient');
        $patient_table = TableRegistry::get('Patients');
        $patient = $patient_table->get($patient_id);
        $unit_id = $session->read('selected-unit');
        $user = $session->read('Auth');

//echo '<pre>';
        //print_r($user);

        $user_id = $user['User']['id'];
        //echo $professional_id;

        $screening = $this->Screenings->newEntity();

        if ($this->request->is('post'))
        {
            $professional_table = TableRegistry::get('Professionals');
            $professionals = $professional_table->find('all', [
                'conditions' => ['user_id' => $user_id, 'unit_id' => $unit_id],
            ]);
            $professional_id = '';

            foreach ($professionals as $key => $professional)
            {
                $professional_id = $professional['id'];
            }

            $screening = $this->Screenings->patchEntity($screening, $this->request->data);
            $screening['professional_id'] = $professional_id;

//echo '<pre>';

//print_r($screening);
            if ($this->Screenings->save($screening))
            {
                $this->Flash->success(__('O registro foi salvo.'));
                $this->redirect(['action' => 'index']);
            }
            else
            {
                $x = $screening->errors();
                Log::write('debug', $x);
                Log::write('error', $x);
                $this->Flash->error(__('O registro não pode ser salvo.'));
            }
        }

        $pain_characteristics = $this->Screenings->PainCharacteristics->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        //$patients             = $this->Screenings->Patients->find('all', ['limit' => 200]);
        $this->set(compact('screening', 'patient', 'pain_characteristics'));
        $this->set('_serialize', ['screening']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Screening 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)
    {
        $screening = $this->Screenings->get($id, [
            'contain' => ['PainCharacteristics','PediatricScreenings'],
        ]);
        
        $session = $this->request->session();
        $session->write('screening_id', $id);
        $session->write('current-state', 'emergencia');
        $patient_id = $session->read('selected-pacient');
        $patient_table = TableRegistry::get('Patients');
        $patient = $patient_table->get($patient_id);

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

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

        $this->set('screening_id', $id);
        //$patients             = $this->Screenings->Patients->find('list', ['limit' => 200]);
        $pain_characteristics = $this->Screenings->PainCharacteristics->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        $this->set(compact('screening', 'patient', 'pain_characteristics'));
        $this->set('_serialize', ['screening']);
    }


    public function printView($id = null)
    {

        $is_print_view = true;
        $session = $this->request->session();

        $hospitalizations_table   = TableRegistry::get('Hospitalizations');    
        $patient_table = TableRegistry::get('Patients');
        $units_table   = TableRegistry::get('Units');

        
        $session->write('screening_id', $id);
        $session->write('current-state', 'emergencia');

        $unit_id                = $session->read('selected-unit');
        $patient_id             = $session->read('selected-pacient');
        // $hospitalization_id     = $session->read('selected-hospitalization');
        // echo "<pre>";
        //     print_r($hospitalization_id);
        // echo "</pre>";

        $patient         = $patient_table->get($patient_id);
        $unit            = $units_table->get($unit_id);
        // $hospitalization = $hospitalizations_table->get($hospitalization_id,['contain'=>['Discharges','Sectors']]);

         $screening = $this->Screenings->get($id, [
            'contain' => ['PainCharacteristics','PediatricScreenings'],
        ]);

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

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

        $this->set('screening_id', $id);
        //$patients             = $this->Screenings->Patients->find('list', ['limit' => 200]);
        $pain_characteristics = $this->Screenings->PainCharacteristics->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        $this->set(compact('unit','is_print_view','screening', 'patient', 'pain_characteristics'));
        $this->set('_serialize', ['screening']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Screening 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']);
        $screening = $this->Screenings->get($id);

        if ($this->Screenings->delete($screening))
        {
            $this->Flash->success(__('The screening has been deleted.'));
        }
        else
        {
            $this->Flash->error(__('The screening could not be deleted. Please, try again.'));
        }

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