<?php
namespace App\Controller;

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


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

    /**
     * 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');        
    }

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

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

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $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(__('The indicators unit has been saved.'));
                return $this->redirect(['action' => 'index']);
            } 
            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', 'units'));
        $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)
    {
        // $indicatorsUnit = $this->IndicatorsUnits->get($id, [
        //     'contain' => ['Units']
        // ]);
        
        $unitsTable = TableRegistry::get('IndicatorsUnits');
        $indicatorsUnit = $unitsTable->find()
        ->where(['IndicatorsUnits.unit_id =' => $unit_id])
        ->contain(['Units']);
        $indicatorsUnit = $indicatorsUnit->first();


        // $indicatorsUnit->leftJoinWith('IndicatorsUnits')
        // ->where(['Units.id' => 1]);


        //$indicatorsUnit =  $this->IndicatorsUnits->get($id, ['contain' => ['Units'] ]) ;    
       


        // $query->leftJoinWith('Units')
        // ->where(['Units.id = ' => $id]);


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

            //verifica se já existe um registro no banco
            if ( $this->request->data['new_record'] == 1)
            {
               // Log::write('debug', "new record = true");

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

                $indicatorsUnits = $this->IndicatorsUnits->patchEntity($indicatorsUnit, $this->request->data);
                $indicatorsUnits->unit_id = $unit_id;

                if ($this->IndicatorsUnits->save($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->patchEntity($indicatorsUnit, $this->request->data);

                if ($this->IndicatorsUnits->save($indicatorsUnit)) 
                {
                    $this->Flash->success(__('The indicators unit has been saved.'));
                    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']);
    }

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