<?php

/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link      https://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   https://opensource.org/licenses/mit-license.php MIT License
 */

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\I18n\I18n;
use Cake\Core\Configure;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link https://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

    protected $selectEmptyMsg = '---- please select ----';

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * e.g. `$this->loadComponent('Security');`
     *
     * @return void
     */
    public function initialize() {
        parent::initialize();
        //$this->viewBuilder()->theme('Porto');
	 I18n::setLocale('th_TH');
        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');

        /*
         * Enable the following components for recommended CakePHP security settings.
         * see https://book.cakephp.org/3.0/en/controllers/components/security.html
         */

        $this->loadComponent('Auth', [
            'loginRedirect' => ['controller' => 'Homes', 'action' => 'index'],
            'logoutRedirect' => ['controller' => 'Users', 'action' => 'signin'],
            'authenticate' => [
                'Form' => [
                    'fields' => ['username' => 'username', 'password' => 'password'],
                    'userModel' => 'Users'
                ]
            ],
            'loginAction' => ['controller' => 'Users', 'action' => 'signin'],
            'authorize' => ['Controller'],
            'unauthorizedRedirect' => $this->referer()// If unauthorized, return them to page they were just on
        ]);


        //$this->loadComponent('Security');
        //$this->loadComponent('Csrf');
    }

    /**
     * 
     * Function trigger before filter process
     * @author sarawutt.b
     * @param Event $event
     */
    public function beforeFilter(Event $event) {
        parent::beforeFilter($event);

        /**
         * 
         * Set appication language this can be thai|english
         * @author Sarawutt.b
         * @since 2018-02-28
         * @return void
         */
        if ($this->request->session()->check('SessionLanguage') == false) {
            $this->request->session()->write('SessionLanguage', 'tha');
        }

        $this->checkSessionAuth();
        $this->Auth->allow(['signin', 'signout', 'signup', 'verify']);
    }

    /**
     * 
     * Function check for session
     * @author sarawutt.b
     * @return void
     */
    public function checkSessionAuth() {
        $currentPath = strtolower(trim($this->request->here));
        if (!empty($this->Auth->user('id')) && ($currentPath == '/')) {
            return $this->redirect(Configure::read('RedirectApplicationURL'));
        }
    }

    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return \Cake\Http\Response|null|void
     */
    public function beforeRender(Event $event) {
        //$this->viewBuilder()->theme('Gentelella');
        //$this->viewBuilder()->theme('AdminLTE');
        //$this->viewBuilder()->theme('Porto');
        //$this->viewBuilder()->className('AdminLTE.AdminLTE');
        //$this->viewBuilder()->theme('Porto');
        //$this->viewBuilder()->className('Porto.Porto');
        // 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);
            //$this->set('theme', Configure::read('Theme'));
        }
        //$this->set('theme', Configure::read('Theme'));
    }

    /**
     * 
     * Function check authorize
     * @author sarawutt.b
     * @param type $user
     * @return boolean
     */
    public function isAuthorized($user) {
        return true;
    }

    /**
     * 
     * Function check fore token
     * @return type
     */
    function checkToken() {
        if (empty($this->request->getHeaderLine('Authorization'))) {
            return $this->redirect(['controller' => 'Users', 'action' => 'signin']);
        }
    }

    /**
     * Set language used this in mutiple language application concept
     * @author Sarawutt.b
     * @since 2016/03/21 10:23:33
     * @return void
     */
    public function _setLanguage() {
        $this->L10n = new L10n();
        $language = $this->request->session()->read('SessionLanguage');
        Configure::write('Config.language', $language);
        $this->L10n->get($language);
    }

    /**
     * 
     * Function get for current session user language
     * @author sarawutt.b
     * @return string
     */
    public function getCurrentLanguage() {
        return $this->request->session()->read('SessionLanguage');
    }

    /**
     *
     * Function used fro generate _VERSION_
     * @author  sarawutt.b
     * @return  biginteger of the version number
     */
    public function VERSION() {
        $parts = explode(' ', microtime());
        $micro = $parts[0] * 1000000;
        return(substr(date('YmdHis'), 2) . sprintf("%06d", $micro));
    }

    /**
     *
     * Function used for generate UUID key patern
     * @author  sarawutt.b
     * @return  string uuid in version
     */
    public function UUID() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
    }

    /**
     * 
     * Function get for current session user authentication full name
     * @author  sarawutt.b
     * @since   2018/02/06
     * @return  string of authentication user full name
     */
    protected function getAuthFullname() {
        return $this->readAuth('Auth.User.first_name') . ' ' . $this->readAuth('Auth.User.last_name');
    }

    /**
     * 
     * Function get for current session user authentication user id
     * @author  sarawutt.b
     * @since   2018/02/06
     * @return  string of authentication user id
     */
    protected function getAuthUserId() {
        return $this->readAuth('Auth.User.id');
    }

    /**
     * 
     * Function get for current session user authentication role id
     * @author  sarawutt.b
     * @since   2018/02/06
     * @return  string of authentication user id
     */
    protected function getAuthUserRoleId() {
        return $this->readAuth('Auth.User.role_id');
    }

    /**
     * 
     * Function get for current session with user authentication
     * @author  sarawutt.b
     * @since   2018/02/06
     * @return  string of authentication session info
     */
    protected function readAuth($name = null) {
        return $this->request->session()->read($name);
    }

    /**
     * Function get for empty option in DDL
     * @author sarawutt.b
     * @return array() of empty select DDL
     */
    public function getEmptySelect() {
        return ['' => __($this->selectEmptyMsg)];
    }

}
