<?php

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;

class AppController extends Controller
{
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'accountLogin'
            ],
            'loginRedirect' => [
                'controller' => 'Users',
                'action' => 'myAccount'
            ],
            'authError' => 'Please login to your account',
            'authenticate' => [
                'Form' => [
                    'fields' => ['username' => 'email', 'password' => 'password'],
                    'userModel' => 'users'
                ]
            ],
            'authorize' => ['Controller'],
            'storage' => 'Session'
        ]);
        $this->loadComponent('Crud.Crud', [
            'actions' => [
                'Crud.Add',
                'Crud.Index',
                'Crud.View',
                'Crud.Delete',
                'Crud.Edit',
            ],
            'listeners' => ['Crud.Api']
        ]);
    }
    
    public function beforeFilter(\Cake\Event\Event $event)
    {
        $loggedUser = $this->request->session()->read('Auth.User');
        if ($loggedUser) {
            $this->set('loggedUser', $loggedUser);
        } else {
            $this->set('loggedUser', false);
        }
    }
    
    public function isAuthorized($user)
    {
        return true;
    }
    
    public function beforeRender(Event $event) {
        // Note: These defaults are just to get started quickly with development
        // and should not be used in production. You should instead set "_serialize"
        // in each action as required.
        if (!array_key_exists('_serialize', $this->viewVars) &&
                in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }

    }
}
