<?php
App::uses('Component', 'Controller');

class PermissionComponent extends Component
{

    /**
     * @var AppModel|bool|mixed|Model|object|string|null
     */
    private $GroupSetting;
    private $PermissionTable;
    private  $permission = NO_PERMIT;
    private $restricted_modes = ['ON' => 1, 'OFF' => 0];

    public function initialize(Controller $controller)
    {
        $this->GroupSetting = ClassRegistry::init('GroupSetting');
        $this->PermissionTable = ClassRegistry::init('PermissionTable');
    }

    public function PermissionByUserId($unique_url, $user_id)
    {
        $group_setting = $this->GroupSetting->getGroupSettingByURL($unique_url);
        if (empty($group_setting)) {
            return PUBLIC_PERMIT;
        }
        $restricted_mode = $group_setting['is_restricted_mode'] ;

        if($restricted_mode == $this->restricted_modes['OFF']){
            return PUBLIC_PERMIT;
        }

        if ($restricted_mode == $this->restricted_modes['ON']) {
            $user_permission = $this->PermissionTable->getPermissionByUrlAndUserId($unique_url, $user_id);
            if (!empty($user_permission['PermissionTable'])) {
                $this->permission = $user_permission['PermissionTable']['role'];
            }
        }

        return $this->permission;

    }

}
