<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
namespace app\wendasns\admin;

use app\admin\AdminBaseController;
use app\wendasns\model\Config as byConfig;
use wendasns\facade\WendFile;
use think\facade\Filesystem;

class Config extends AdminBaseController
{
    //站点设置
    public function website()
    {
        $dm = byConfig::where('namespace','website')->select();
		if(!$dm){
			error('配置不存在');
		}
		foreach($dm as $v){
			$data[$v->name] = $v->value;
		}
		return view('website',['data'=>$data]);
    }
    
    //更新配置信息
	public function post()
	{
		$type = input('post.type','');
		$post = input('post.',[]);
		$list = [];
		$dm = byConfig::where('namespace',$type)->select();
		foreach($dm as $v){
			if(isset($post[$v->name])){
				$value = $post[$v->name];
				$list[] = ['id'=>$v->id,'value'=>$value,'vtype'=>$v->vtype];
			}
		}
		$config = new byConfig;
		$config->saveAll($list);
		success('操作成功');
	}
	
	//上传网站logo
    public function upload()
    {
    	$file = request()->file('file');
    	try {
    		validate(['file'=>'fileExt:jpg,png,gif'])->check(['file'=>$file]);
    		$path = root_path('public'.DIRECTORY_SEPARATOR.'static'.DIRECTORY_SEPARATOR.'wendasns');
    		Filesystem::getAdapter()->setPathPrefix($path);
        	Filesystem::putFileAs('images', $file, 'logo.png');
    	} catch (\think\exception\ValidateException $e) {
        	error($e->getMessage());
    	}
    	success('操作成功');
    }
    
	//设置网址后缀
    public function urlsuffix()
    {
    	$suffix = input('post.suffix','');
    	$path = config_path().'route.php';
    	$content = file_get_contents($path);
    	$content = preg_replace('/url_html_suffix\'.*?\'(.*?)\'/',"url_html_suffix'       => '{$suffix}'",$content);
    	file_put_contents($path,$content);
    	success('操作成功');
    }
    
    //模板设置
    public function view()
    {
    	$view = config('view.view_dir_name');
    	$path = root_path($view).'wendasns'.DIRECTORY_SEPARATOR;
    	
    	$dm = byConfig::where('namespace','view')->select();
    	foreach($dm as $v){
    		$config[$v->name] = $v->value;
    	}
    	$data = array_map(function($val)use($path){
    		$dir_path = $path.$val;
    		if(!is_dir($dir_path)){
    			return [];
    		}
    		$dh = opendir($dir_path);
	    	$data = [];
		    while (($file = readdir($dh)) !== false){
		    	if($file != '.' && $file != '..'){
		    		if(is_dir($dir_path.DIRECTORY_SEPARATOR.$file)){
		    			$data[] = $file;
		    		}
		    	}
		    }
		    closedir($dh);
		    return $data;
    	},['computer'=>'computer','wap'=>'wap']);
	    
    	return view('view',['data'=>$data,'config'=>$config]);
    }
}