<?php
# place 身份入口
class Place
{
    public static $info;
    public static $user;
    public static $uid;
    public static $code;
    public static $channel;
    public static $system;
    public static $sector;
    public static $module;
    public static $id;

    # 生成入口码
    public static function entry($sector_id, $module_id, $user_id, $place_id)
    {
        $code = \Dever\Helper\Secure::encode($sector_id . '-' . $module_id . '-' . $user_id . '-' . $place_id);
        return $code;
    }

    # 初始化
    public static function init()
    {
        self::$code = Dever::input('p');
        $code = Dever\Helper\Secure::decode(self::$code);
        if (!$code) {
            Dever::error('身份码错误');
        }
        list($sector_id, $module_id, $user_id, $place_id) = explode('-', $code);
        self::$system = Dever::db('system', 'manage')->find(array('key' => 'sector'));
        self::$sector = Dever::db(self::$system['info_table'])->find($sector_id);
        if (!self::$sector) {
            Dever::error('领域信息错误');
        }
        # 切换数据库
        Dever::load('common', 'manage')->setAuth(self::$system['partition'], self::$system['id'], self::$sector['id'], $module_id, $user_id);

        # 初始化身份
        self::info($user_id, $place_id);

        # 切换数据库
        self::$module = Dever::db('system_module', 'manage')->find(array('key' => 'sector_place'));
        Dever::load('common', 'manage')->setAuth(self::$system['partition'], self::$system['id'], self::$sector['id'], self::$module['id'], $place_id);

        # 初始化频道
        self::channel();

    }

    # 身份信息
    public static function info($user_id, $place_id)
    {
        $user = Dever::db('user', 'sector')->find($user_id);
        self::$info = Dever::db('info', 'place')->find($place_id, array('col' => 'name,logo,content,bg,type,money_id,uid,pay_account'));
        if (!self::$info) {
            Dever::error('信息有误');
        }
        if (self::$info['uid'] != $user['id']) {
            Dever::error('信息有误');
        }
        self::$id = $place_id;
        self::$info['channel'] = $user['channel'];
        self::$info['content'] = htmlspecialchars_decode(self::$info['content']);
    }

    # 资源信息
    public static function channel()
    {
        self::$channel = Dever::db('channel', 'place_source')->select(['status' => 1], array('col' => 'id,name,icon,icon_select'));
    }

    # 用户信息
    public static function user($uid)
    {
        self::$user = Dever::db('info', 'place_user')->find($uid, array('col' => 'id,name,avatar'));
        if (self::$user) {
            self::$uid = $uid;
        }
    }

    public static function result($data)
    {
        $data['place'] = self::$info;
        $data['channel'] = self::$channel;
        $data['user'] = self::$user;
        return $data;
    }
}
include(DEVER_APP_PATH . '../../../boot.php');