<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Datasource\ConnectionManager;

/**
 * Rooms Controller
 *
 * @property \App\Model\Table\RoomsTable $Rooms
 */
class RoomsController extends AppController
{

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Permission');
        $this->loadComponent('Upload');
        $this->set('title', 'Salas e Leitos');

    }

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

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

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

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index($sector_id = null, $limit_of_rooms = null)
    {
        //$roomEntity = $this->Rooms->newEntity();

        // $room = $this->Rooms->get($sector_id, [
        //     'contain' => []
        // ]);
        $this->request->session()->write('sector_id', $sector_id);

        $room = $this->Rooms->find()
            ->where(['Rooms.sector_id =' => $sector_id])
        ;

        $rooms          = $this->paginate($room);
        $total_of_rooms = null;
        $total_of_rooms = $room->count();

        // $this->paginate = [
        //     'contain' => ['Sectors']
        // ];

        // $rooms = $this->paginate($this->Rooms
        //    ->find()
        //    ->where(['Rooms.sector_id =' => $sector_id])
        //    )
        // ;

        // $this->set(compact('rooms'));
        // $this->set('_serialize', ['rooms']);

        // $typesTable = TableRegistry::get('Types');
        // $types = $typesTable->find();
        // $types = $types->toArray();

        // $session = $this->request->session();
        // $unit_id = $session->read('selected-unit');

        // $roomsTable = TableRegistry::get('Rooms');

        // $rooms = $this->Rooms->find()
        //     ->contain(['Sectors'])
        // ;

        // $rooms->innerJoinWith('Sectors')
        //     ->distinct(['Rooms.id'])
        //     ->where(['Sectors.id =' =>  $sector_id])
        // ;

        if ($this->request->is(['patch', 'post', 'put'])) {
            //return;
            //$room = $this->Rooms->patchEntity($room, $this->request->data);
            $roomEntity = $this->Rooms->newEntity($this->request->data(), ['validate' => false]);

            // $x = $roomEntity->errors();

            // Log::write('debug','$x');
            // Log::write('debug',$x);

            // Log::write('debug','$roomEntity');
            // Log::write('debug',$roomEntity);

            foreach ($this->request->data() as $room) {
                // Log::write('debug','$room');
                // Log::write('debug', $room);

                $conn = ConnectionManager::get('default');
                $stmt = $conn->execute(
                    'UPDATE rooms SET name=? where id=?',
                    [$room['name'], $room['id']]
                );
            }
            $this->Flash->success(__('O registro foi salvo.'));
            return $this->redirect(['action' => 'index', $sector_id]);

            if ($this->Rooms->save($roomEntity)) {
                $this->Flash->success(__('O registro foi salvo.'));
                return $this->redirect(['action' => 'index', $sector_id]);
            } else {

                $this->Flash->error(__('O registro não pode ser Salvo. Por favor, tente novamente.'));
            }
        }

        // $users = $this->paginate($this->Users);
        // $sectors = $this->paginate($rooms);

        // $this->set("types",$types);$
        $this->set("total_of_rooms", $total_of_rooms);
        $this->set("sector_id", $sector_id);
        $this->set("limit_of_rooms", $limit_of_rooms);
        // $this->set("unit_id", $unit_id);
        //$this->set(compact('rooms'));
        //$this->set('_serialize', ['rooms']);
        $this->set(compact('rooms'));
        $this->set(compact('room'));
        $this->set('_serialize', ['rooms']);
        $this->set('_serialize', ['room']);
    }

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

        $this->set("sector_id", $sector_id);
        $this->set('room', $room);
        $this->set('_serialize', ['room']);
    }

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

        if ($this->request->is('post')) {
            $room = $this->Rooms->patchEntity($room, $this->request->data);

            if ($this->Rooms->save($room)) {
                $this->Flash->success(__('O registro foi salvo.'));
                //return $this->redirect(['action' => 'index']);
                return $this->redirect($this->referer());

            } else {
                $this->Flash->error(__('O registro não pode ser deletado. Por favor, tente novamente.'));
            }
        }

        $this->set("sector_id", $sector_id);
        $sectors = $this->Rooms->Sectors->find('list', ['limit' => 200]);
        $this->set(compact('room', 'sectors'));
        $this->set('_serialize', ['room']);
    }

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

        if ($this->request->is(['patch', 'post', 'put'])) {
            $room = $this->Rooms->patchEntity($room, $this->request->data);
            if ($this->Rooms->save($room)) {
                $this->Flash->success(__('O registro foi salvo.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('O registro não pode ser deletado. Por favor, tente novamente.'));
            }
        }

        $this->set("sector_id", $sector_id);
        $sectors = $this->Rooms->Sectors->find('list', ['limit' => 200]);
        $this->set(compact('room', 'sectors'));
        $this->set('_serialize', ['room']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Room id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($room_id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $session   = $this->request->session();
        $sector_id = $session->read('sector_id');

        $room = $this->Rooms->get($room_id);

        if ($this->Rooms->delete($room)) {
            $this->Flash->success(__('O registro foi deletado.'));
        } else {
            $this->Flash->error(__('O registro não pode ser deletado. Por favor, tente novamente.'));
        }

        // Log::write('debug', '$x');
        // Log::write('debug', $this->request->params['pass']);

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