<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Comment;
use App\Models\Course;

class CommentController extends Controller
{
    //列表
    public function list(Request $request)
    {
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);
        $course_name=$request->input('course_name');
        $agent_phone=$request->input('agent_phone');
        $data=Comment::query();
        if($course_name){
            $data->whereHas('course',function($query)use($course_name){
                $query->where('title','like','%'.$course_name.'%');
            });
        }
        if($agent_phone){
            $data->whereHas('user',function($query)use($agent_phone){
                $query->where('mobile',$agent_phone);
            });
        }
        $count=$data->count();
        $list=$data->with('course:id,title,deleted_at','user:id,headimgurl,nickname')
            ->orderBy('id','desc')
            ->skip($num)->take($page_size)
            ->get();
        return $this->success_list($list,'',$count);
    }

    //审核评论
    public function auditComment(Request $request)
    {
        $id=$request->input('id');
        $comment=Comment::where('id',$id)->first();
        $comment->state=$comment->state?0:1;
        try{
            $comment->save();
            Course::where('id',$comment->course_id)->increment('comms');
            return $this->success([]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }
    }

    //删除评论
    public function deleteComment(Request $request)
    {
        $id=$request->input('id');
        $res=Comment::where('id',$id)->delete();
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }
}
