<?php
class Acl_action extends MY_Model
{
	const DB_TABLE = 'acl_action';
    const DB_TABLE_PK = 'acl_action_id';

	private static $loaded = false;

	public function __construct()
	{
		parent::__construct();

		if(!self::$loaded)
		{
			$actions = $this->getConstants();

			//Because this class is auto-loaded before NCMS is installed, we need an additional check to avoid fatal errors.
			if(!is_array($actions))
			{
				return false;
			}

			foreach($actions as $action)
			{
				$constant = 'ACTION_'.strtoupper($action->constant);
				$constant = str_ireplace(" ", "_", $constant);

				$value = $action->acl_action_id;
				if(!defined($constant)) define($constant, $value);
			}

			self::$loaded = true;
		}
	}

	public function getConstants()
	{
		if(($actions = $this->cache->get("acl_actions")) === false)
		{
			$actions = $this->db->query("SELECT `acl_action_id`, `constant` FROM `acl_action`");
			$actions = $actions->result();
			$this->cache->save("acl_actions", $actions, 86400);
		}

		return $actions;
	}

    public function loadByRoleID($acl_role_id)
    {
    	$query = $this->db->query("SELECT a.*, r.acl_role_id, IF(r.acl_role_id IS NULL, 0, 1) AS `active`
    	                          FROM `acl_action` AS a
    	                          LEFT JOIN `acl_role_action` AS r ON a.acl_action_id=r.acl_action_id AND r.acl_role_id=?
    	                          ORDER BY a.`action`",
    	                          array($acl_role_id));

        return $query->result();
    }
}
