<?php
/**
 * @desc: Created by PhpStorm.
 * @Author: Dr.Xing <ezfwork@foxmail.com>
 * @Since: 2018/1/25 22:40
 */

namespace seven;

use fast\Form;
use app\admin\model\Sites;

class Seven
{
    /**
     * 生成多国语言版本的选择项
     * @param string $name     input名称
     * @param string $type     input类型(radio|checkbox)
     * @param null $selected   选定项
     * @param array $options   扩展选项
     * @return string
     */
    public static function build_langs($name, $selected=null, $options=[])
    {
        $request = request();
        $MultiLanguages = include EXTEND_PATH.'seven/multilanguage.php';
        $list = [];

        $siteid = isset($options['siteid'])?$options['siteid'] : '';
        $type = isset($options['type'])? $options['type'] : 'radio';

        //从站点后台进入，只显示当前站点允许的语言版本
        if (!empty($siteid) || !empty($request->param('domain'))) {
            if(!empty($siteid)) {
                $domain = Sites::get(['id' => $siteid]);
            }else{
                $domain = Sites::get(['domain' => $request->param('domain')]);
            }
            $langs = explode(',', $domain['lang']);
                foreach ($langs as $k => $v) {
                $list[$v] = $MultiLanguages[$v];
            }
        } else {
            foreach ($MultiLanguages as $k => $v) {
                $list[$k] = $v;
            }
        }

        $html=[];
        $selected = empty($selected) ? 'zh-cn' : $selected;
        //$class = empty($class)? $type.'-inline' : $class;
        if ($type == "checkbox") {
            $name .= substr($name, -2) != '[]' ? '[]' : '';
            $selected = is_null($selected) ? [] : $selected;
            $selected = is_array($selected) ? $selected : explode(',', $selected);
            foreach ($list as $k => $v)
            {
                $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
            }
            return '<div class="checkbox">' . implode(' ', $html) . '</div>';

        } else {
            $selected = is_null($selected) ? key($list) : $selected;
            $selected = is_array($selected) ? $selected : explode(',', $selected);
            foreach ($list as $k => $v)
            {
                $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::radio($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
            }
            return '<div class="radio">' . implode(' ', $html) . '</div>';
        }
    }
}