<?php
namespace App\Controller;

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

/**
 * Cultures Controller
 *
 * @property \App\Model\Table\CulturesTable $Cultures
 */
class CulturesController extends AppController
{

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

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

        $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'], 'CribScores', $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');

        $this->paginate = [
            'contain' => ['Hospitalizations'],
            'conditions' => ['Cultures.hospitalization_id' => $hospitalization_id],
            'order' => ['created' => 'desc'],
        ];
        $cultures = $this->paginate($this->Cultures);

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

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $culture = $this->Cultures->newEntity();
        //$culture = $this->ListAntibioticsCultures->newEntity();
        $list_antibiotics_culture_table = TableRegistry::get('ListAntibioticsCultures');

        //$antibiotics_culture;
        if ($this->request->is('post'))
        {
            $culture = $this->Cultures->patchEntity($culture, $this->request->data);

            if ($culture_save = $this->Cultures->save($culture))
            {
                foreach ($culture['list_antibiotics_cultures'] as $key => $data)
                {
                    $data['culture_id'] = $culture_save->id;

                    $list_antibiotics_culture_save = $list_antibiotics_culture_table->newEntity();
                    $list_antibiotics_culture_save = $list_antibiotics_culture_table->patchEntity($list_antibiotics_culture_save, $data, [
                        'validate' => false,
                    ]);

                    /*echo "<pre>";
                    print_r($list_antibiotics_culture_save);*/
                    if (isset($list_antibiotics_culture_save['list_antibiotic_id']))
                    {
                        $list = $list_antibiotics_culture_table->find('all', [
                            'condition' => [
                                "list_antibiotic_id" => $list_antibiotics_culture_save['list_antibiotic_id'],
                                'culture_id' => $list_antibiotics_culture_save['culture_id'],
                            ],
                        ]);

                        /*echo "<pre>";
                        print($list);*/
                        if (isset($list))
                        {
                            $list_antibiotics_culture_table->save($list_antibiotics_culture_save);
                        }
                    }
                }

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

        $hospitalizations = $this->Cultures->Hospitalizations->find('list', ['limit' => 200]);
        $list_antibiotics = $this->Cultures->ListAntibiotics->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        $antibiotics = $this->Cultures->ListAntibiotics->find('all', ['limit' => 200, 'fields' => ['id', 'nome']])->toArray();
        //$antibiotics      = $antibiotics->toArray();

        $this->set(compact('culture', 'hospitalizations', 'list_antibiotics', 'antibiotics'));
        $this->set('_serialize', ['culture']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Culture 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)
    {
        $culture = $this->Cultures->get($id, [
            'contain' => ['ListAntibiotics', 'AntibioticsInUse'],
        ]);

        $list_antibiotics_culture_table = TableRegistry::get('ListAntibioticsCultures');

        $list_antibiotics_cultures = $list_antibiotics_culture_table
            ->find('all', [
                'contain' => ['ListAntibiotics'],
            ])
            ->where(['ListAntibioticsCultures.culture_id' => $id]);

        //echo "<pre>";

        //print_r($list_antibiotics_cultures);

        /*foreach ($list_antibiotics_cultures as $key => $value) {
        echo "<pre>";
        print_r($value);
        }*/

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

            /*echo "<pre>";
            print_r($culture);*/

            if ($culture_save = $this->Cultures->save($culture))
            {
                //$list_antibiotics_cultures_delete = $this->Cultures->find('all')
                //->where(['ListAntibioticsCultures.culture_id' => $id]);

                $list_antibiotics_culture_table->deleteAll(['ListAntibioticsCultures.culture_id' => $id]);

                foreach ($culture['antibiotics_in_use'] as $key => $data)
                {
                    $data['culture_id'] = $culture_save->id;
                    $data = $data->toArray();
                    // echo "<pre>";
                    // print_r($data);

                    $list_antibiotics_culture_save = $list_antibiotics_culture_table->newEntity();
                    $list_antibiotics_culture_save = $list_antibiotics_culture_table->patchEntity($list_antibiotics_culture_save, $data, [
                        'validate' => false,
                    ]);

                    if (isset($list_antibiotics_culture_save['list_antibiotic_id']))
                    {
                        $list = $list_antibiotics_culture_table->find('all', [
                            'condition' => [
                                "list_antibiotic_id" => $list_antibiotics_culture_save['list_antibiotic_id'],
                                'culture_id' => $list_antibiotics_culture_save['culture_id'],
                            ],
                        ]);

                        if (isset($list))
                        {
                            $list_antibiotics_culture_table->save($list_antibiotics_culture_save);
                        }
                    }
                };

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

        $antibiotics = $this->Cultures->ListAntibiotics->find('all', ['limit' => 200, 'fields' => ['id', 'nome']])->toArray();
        $list_antibiotics = $this->Cultures->ListAntibiotics->find('list', ['limit' => 200, 'fields' => ['id', 'nome']]);
        $hospitalizations = $this->Cultures->Hospitalizations->find('list', ['limit' => 200]);
        $this->set(compact('culture', 'hospitalizations', 'list_antibiotics', 'antibiotics', 'list_antibiotics_cultures'));
        $this->set('_serialize', ['culture']);
    }

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

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

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