<?php namespace Phpcmf\Model\Cms;

/**
 * 内容权限（站点 / 模块 / 栏目）
 * 调用：\Phpcmf\Service::M('member_auth', 'cms')
 */
class Member_auth extends \Phpcmf\Model {

    public $auth;
    public $auth_type;
    public $is_category_public;

    public function __construct() {
        parent::__construct();
        $this->_reload_auth();
    }

    // 每次从会员缓存重新读取，避免单例构造过早导致 auth 为空
    protected function _reload_auth() {
        $this->auth = isset(\Phpcmf\Service::C()->member_cache['auth2'][SITE_ID])
            ? \Phpcmf\Service::C()->member_cache['auth2'][SITE_ID] : [];
        $auth_type = \Phpcmf\Service::C()->member_cache['auth_type'] ?? 0;
        // [] / null / "" 都按全局 0 处理（dr_string2array("0") 会得到 []）
        $this->auth_type = is_numeric($auth_type) ? intval($auth_type) : 0;
    }

    // 当前登录会员的权限标识
    protected function _get_groupid($member) {

        $auth_type = is_numeric($this->auth_type) ? intval($this->auth_type) : 0;

        if ($auth_type == 1) {
            $groupid = $member && !empty($member['groupid']) ? $member['groupid'] : [0];
        } elseif ($auth_type == 2) {
            $groupid = $member && !empty($member['authid']) ? $member['authid'] : [0];
        } else {
            $groupid = ['public'];
        }

        if (!is_array($groupid)) {
            $groupid = [$groupid];
        }

        return $groupid ? array_values($groupid) : [0];
    }

    // 取某一 aid 下的栏目权限配置
    protected function _category_auth_row($gid, $module, $catid) {

        $mid = isset($module['dirname']) ? $module['dirname'] : '';
        if (!$mid && defined('APP_DIR')) {
            $mid = APP_DIR;
        }

        if (!empty($module['share'])) {
            if (!empty($this->auth[$gid]['home']['is_category'])) {
                $this->is_category_public = 0;
                return isset($this->auth[$gid]['share_category'][$catid])
                    ? $this->auth[$gid]['share_category'][$catid] : [];
            }
            $this->is_category_public = 1;
            return isset($this->auth[$gid]['share_category_public'])
                ? $this->auth[$gid]['share_category_public'] : [];
        }

        if (!empty($this->auth[$gid]['module'][$mid]['is_category'])) {
            $this->is_category_public = 0;
            return isset($this->auth[$gid]['category'][$mid][$catid])
                ? $this->auth[$gid]['category'][$mid][$catid] : [];
        }
        $this->is_category_public = 1;
        return isset($this->auth[$gid]['category_public'][$mid])
            ? $this->auth[$gid]['category_public'][$mid] : [];
    }

    // 站点权限
    public function home_auth($name, $member = []) {

        $this->_reload_auth();
        $values = [];
        foreach ($this->_get_groupid($member) as $gid) {
            if (isset($this->auth[$gid]['home'][$name])) {
                $values[] = $this->auth[$gid]['home'][$name];
            }
        }

        return $values ? max($values) : null;
    }

    // 模块权限
    public function module_auth($mid, $name, $member = []) {

        $this->_reload_auth();
        $values = [];
        foreach ($this->_get_groupid($member) as $gid) {
            if (isset($this->auth[$gid]['module'][$mid][$name])) {
                $values[] = $this->auth[$gid]['module'][$mid][$name];
            }
        }

        return $values ? max($values) : null;
    }

    // 栏目权限
    public function category_auth($module, $catid, $name, $member = []) {

        $this->_reload_auth();
        $values = [];
        $this->is_category_public = 0;
        $groupid = $this->_get_groupid($member);
        $has_config = false;

        foreach ($groupid as $gid) {
            $auth = $this->_category_auth_row($gid, $module, $catid);
            if ($auth) {
                // 本组已有栏目权限配置：未勾选的项视为关闭，不能再回退 public
                $has_config = true;
                if (isset($auth[$name])) {
                    $values[] = $auth[$name];
                }
            } elseif ($name === 'show') {
                $values[] = 1; // 默认没勾选时访问开放
            }
        }

        // 按用户组/等级时，仅当本组完全没有栏目权限配置，才回退 public
        if (!$has_config && !$values && !in_array('public', $groupid, true) && isset($this->auth['public'])) {
            $auth = $this->_category_auth_row('public', $module, $catid);
            if (isset($auth[$name])) {
                $values[] = $auth[$name];
            } elseif (!$auth && $name === 'show') {
                $values[] = 1;
            }
        }

        return $values ? max($values) : null;
    }

}
