<?php

namespace App\Http\Controllers\Admin;

use App\Models\Remark;
use App\Models\RemarkDetail;
use Illuminate\Http\Request;

class RemarkController extends Controller
{
    protected $redirect_index = '/admin/Remark/index';

    protected $view_path = 'admin.remarks.';

    protected $pre_uri = '/admin/Remark/';

    protected $model_name = '评价';

    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new Remark();
    }

    public function index(Request $request)
    {
        $list = $this->model->where('id', '>', 0)->orderBy('created_at', 'desc');
        $list = $list->get();

        if(!empty($request->input('keyword')) && !empty(trim($request->input('keyword')))) {
            $keyword = trim($request->input('keyword'));
            $list = $list->filter(function ($value) use($keyword) {
                if(!empty($value->teacher) && !(strpos($value->teacher->name, $keyword) === false)) {
                    return true;
                }
                if(!empty($value->course) && !(strpos($value->course->name, $keyword) === false)) {
                    return true;
                }
                if(!empty($value->student) && !(strpos($value->student->name, $keyword) === false)) {
                    return true;
                }
                return false;
            });
        }

        foreach($list as $item) {
            $item->average_score = RemarkDetail::where('remark_id', $item->id)->get()->avg('score');
            $item->average_score = round($item->average_score, 1);
        }

        $list = $this->paginate($list);

        list($pre_uri, $model_name) = array($this->pre_uri, $this->model_name);
        return view($this->view_path . 'index', compact('list', 'pre_uri', 'model_name'));
    }

    public function detail(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) {
            return $this->showWarning('参数错误');
        }
        $list = RemarkDetail::where('remark_id', $item->id)->paginate();
        list($pre_uri, $model_name) = array($this->pre_uri, $this->model_name);
        return view($this->view_path . 'detail', compact('item', 'list', 'pre_uri', 'model_name'));
    }

    public function delete(Request $request)
    {
        if(!$request->isMethod('POST')) {
            return $this->showWarning('访问错误');
        }
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) {
            return $this->showWarning('访问错误');
        }

        RemarkDetail::where('remark_id', $item->id)->delete();
        $res = $item->delete();
        if(!$res) {
            return $this->showWarning('数据库删除失败');
        }
        return $this->showMessage('操作成功');
    }
}
