<?php
namespace App\Controller;

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

/**
 * IndicatorsUnits Controller
 *
 * @property \App\Model\Table\IndicatorsUnitsTable $IndicatorsUnits
 */
class IndicatorsUnitsController extends AppController
{

    public function isAuthorized($user)
    {
        return true;
        $action = $this->request->params['action'];

        return $this->Permission->hasPermission($user['role_name'], 'units', $action);

        //return parent::isAuthorized($user);
    }

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['Units'],
        ];
        $indicatorsUnits = $this->paginate($this->IndicatorsUnits);

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

    public function initialize()
    {
        parent::initialize();
        //$this->loadComponent('Permission');
        $this->set('title', 'Indicador');
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $session = $this->request->session();
        $unit_id = $session->read('selected-unit');
        $indicator = $this->IndicatorsUnits
            ->find('all', ['limit' => 1])
            ->where(['IndicatorsUnits.unit_id' => $unit_id])
            ->toArray();

        $indicatorsUnit = $this->IndicatorsUnits->newEntity();

        if ($this->request->is('post'))
        {
            $indicatorsUnits = $this->IndicatorsUnits->patchEntity($indicatorsUnit, $this->request->data);

            if ($this->IndicatorsUnits->save($indicatorsUnit))
            {
                $this->Flash->success(__('O registro foi salvo com sucesso.'));
                return $this->redirect(['action' => 'index']);
            }
            else
            {
                $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente mais tarde.'));
            }
        }

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

    /**
     * Edit method
     *
     * @param string|null $id Indicators Unit 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($unit_id = null)
    {
        $unitsTable = TableRegistry::get('IndicatorsUnits');
        $indicatorsUnit = $unitsTable->find()
            ->where(['IndicatorsUnits.unit_id =' => $unit_id])
            ->contain(['Units']);
        $indicatorsUnit = $indicatorsUnit->first();

        if ($this->request->is(['patch', 'post', 'put']))
        {
            //Log::write('debug', $this->request->data);

            //verifica se já existe um registro no banco
            if (isset($indicatorsUnit['id']))
            {
                $indicatorsUnits = $this->IndicatorsUnits->patchEntity($indicatorsUnit, $this->request->data);
                $indicatorsUnits->unit_id = $unit_id;

                if ($this->IndicatorsUnits->save($indicatorsUnit))
                {
                    Log::write('debug', "indicatorsUnit inside if");
                    Log::write('debug', $indicatorsUnit);
                    $this->Flash->success(__('O registro foi salvo salvo com sucesso.'));
                    //return $this->redirect(['action' => 'edit', $unit_id]);
                }
                else
                {
                    $this->Flash->error(__('O registro não pode ser salvo. Por favor, tente novamente.'));
                }
            }
            else
            {
                // Log::write('debug', "new record = false");
                $indicatorsUnit = $this->IndicatorsUnits->newEntity();
                $indicatorsUnit = $this->IndicatorsUnits->patchEntity($indicatorsUnit, $this->request->data);

                if ($this->IndicatorsUnits->save($indicatorsUnit))
                {
                    Log::write('debug', "indicatorsUnit inside else");
                    Log::write('debug', $indicatorsUnit);
                    $this->Flash->success(__('O registro foi salvo.'));
                    //return $this->redirect(['action' => 'edit', $unit_id]);
                }
                else
                {
                    $this->Flash->error(__('The indicators unit could not be saved. Please, try again.'));
                }
            }
        }

        //$units = $this->IndicatorsUnits->Units->find('list', ['limit' => 200]);
        $this->set(compact('indicatorsUnit', 'unit_id'));
        $this->set('_serialize', ['indicatorsUnit']);
    }
}