<?php

namespace Forum\Src;

use Dever;

class Cate
{
    public function __construct()
    {
        $this->id = Dever::input('cate');
    }

    /**
     * 获取栏目列表
     *
     * @return mixed
     */
    public function get()
    {
        $data = Dever::load('forum/cate-main');

        if ($data) {
            $child = Dever::load('forum/cate-child');

            foreach ($data as $k => $v) {
                if (isset($child[$k])) {
                    $data[$k]['child'] = $child[$k];
                }
            }
        }

        return $data;
    }

    /**
     * 验证权限
     *
     * @return mixed
     */
    public function auth($cate)
    {
        if (is_numeric($cate)) {
            $cate = Dever::load('forum/cate-one', $cate);
        }

        $user = Dever::load('passport/user.data');

        if (!$cate) {
            return false;
        }

        if ($cate['uid'] && ($user['id'] <= 0 || strpos(',' . $cate['uid'], ',' . $user['id']) === false)) {
            return false;
        }

        return true;
    }

    /**
     * 获取所有栏目列表
     *
     * @return mixed
     */
    public function all()
    {
        $data = Dever::load('forum/cate-mainAll');

        if ($data) {
            $child = Dever::load('forum/cate-childAll');

            foreach ($data as $k => $v) {
                if (isset($child[$k])) {
                    $data[$k]['child'] = $child[$k];
                }
            }
        }

        return $data;
    }

    public function info()
    {
        $data['display'] = 'display:none;';
        if ($this->id > 0) {
            $data = Dever::load('forum/cate-one', $this->id);
            $data['display'] = '';
            $data['total'] = '[' . Dever::total("current") . ']';
            $data['info'] = Dever::markdown($data['info']);
        }

        return $data;
    }

    public function select()
    {
        $data = $this->get();

        $html = '<option value="" disabled="" selected="">请选择' . Dever::load('main/config-one#catename', 1) . '</option>';

        foreach ($data as $k => $v) {
            $html .= '<optgroup label="' . $v['name'] . '">';

            if (isset($v['child'])) {
                foreach ($v['child'] as $k1 => $v1) {
                    $selected = '';
                    if ($this->id == $v1['id']) {
                        $selected = 'selected';
                    }
                    $html .= '<option value="' . $v1['id'] . '" ' . $selected . '>' . $v1['name'] . '</option>';
                }
            }

            $html .= '</optgroup>';
        }

        return $html;
    }
}
