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

use app\admin\AdminBaseController;
use app\wendasns\model\Category;
use app\wendasns\model\Question as byQuestion;
use app\wendasns\model\User;

class Question extends AdminBaseController
{

	public function index()
	{
		$category = Category::where('type','question')->select();
		return view('index',['category'=>$category]);
	}
	
	public function list()
	{
		$limit = input('get.limit',20,'intval');
		$keyword = input('get.keyword','');
		$username = input('get.username','');
		$min_time = input('get.min_time','');
		$max_time = input('get.max_time','');
		$category = input('get.category',0,'intval');
		$status = input('get.status','');
		
		$sql = [];
		if($keyword){
			$sql[] = ['title','like',"%{$keyword}%"];
		}
		if($username){
			$user = User::where('username',$username)->find();
			if($user){
				$sql[] = ['user_id','=',$user->id];
			}
		}
		if($category){
			$sql[] = ['category_id','=',$category];
		}
		if($min_time){
			$mintime = strtotime($min_time);
			$sql[] = ['create_time','>',$mintime];
		}
		if($max_time){
			$maxtime = strtotime($max_time);
			$sql[] = ['create_time','<',$maxtime];
		}
		if($status){
			if($status=='remove'){
				$sql[] = ['remove','=',1];
			}else{
				$sql[] = ['status','=',$status];
			}
		}
		$dm = byQuestion::where($sql)->order('create_time','desc')->paginate($limit);

		foreach($dm as $k=>$v){
			$dm[$k]->category = isset($v->categorys->name)?$v->categorys->name:'';
			$dm[$k]->username = isset($v->users->username)?$v->users->username:'';
		}
        $data = $dm->toArray();
		success('ok', $data['data'], ['count'=>$data['total']]);
    }

    //编辑
    public function edit()
	{
		if(request()->isPost()){
			$post = input('post.',[]);
			isset($post['create_time']) && $post['create_time'] = strtotime($post['create_time']);
			byQuestion::update($post);
			success('操作成功');
		}
		$id = input('get.id',0,'intval');
		$dm = byQuestion::find($id);
		$category = Category::where('type','question')->select();
		return view('edit',['category'=>$category,'data'=>$dm]);
    }
    
    //删除
    public function remove()
	{
		$id = input('post.id', []);
		if(is_array($id)){
			foreach($id as $v){
				byQuestion::update(['remove'=>1, 'id'=>$v]);
			}
		}
		success('操作完成');
    }
    
    //彻底删除
    public function del()
	{
		$id = input('post.id', []);
		if(is_array($id)){
			byQuestion::destroy($id);
		}
		success('操作完成');
    }
    
    //审核通过
    public function check()
	{
		$id = input('post.id', []);
		if(is_array($id)){
			foreach($id as $v){
				byQuestion::update(['status'=>'normal', 'id'=>$v]);
			}
		}
		success('操作完成');
    }
}