<?php

class Accj_ACL {

    private static $instance = null;

    private $role_service;
    private $permission_service;

    private $user_permissions = [];

    public static function instance(){

        if(self::$instance === null){
            self::$instance = new self();
        }

        return self::$instance;
    }

    private function __construct(){

        $this->role_service = new ACCJ_Role_Service();
        $this->permission_service = new ACCJ_Permission_Service();
    }

    public function user_can($user_id, $permission_code, $action = 'view'){

        $permissions = $this->get_user_permissions($user_id);

        if(!isset($permissions[$permission_code])){
            return false;
        }

        $field = 'can_' . $action;

        return !empty($permissions[$permission_code][$field]);
    }

    private function get_user_permissions($user_id){

        if(isset($this->user_permissions[$user_id])){
            return $this->user_permissions[$user_id];
        }

        $roles = $this->role_service->get_user_roles($user_id);

        $permissions = [];

        foreach($roles as $role){

            $role_permissions = $this->permission_service->get_role_permissions($role['id']);

            foreach($role_permissions as $code => $perm){

                if(!isset($permissions[$code])){
                    $permissions[$code] = $perm;
                }else{

                    foreach($perm as $k=>$v){
                        if($v){
                            $permissions[$code][$k] = 1;
                        }
                    }

                }
            }

        }

        $this->user_permissions[$user_id] = $permissions;

        return $permissions;
    }

}
