<?php

namespace App\Http\Controllers\User;

use App\Events\AuditMedia;
use App\Http\Controllers\Miniprogram\Auth;
use App\Models\Interlocution\AnswerModel;
use App\Models\Interlocution\QuestionModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class InterlocutionController extends Controller
{
    //
    public function questions(Request $request)
    {
        $questions = QuestionModel::get();
        return response([
            'code' => 200,
            'message' => 'OK',
            'data' => $questions
        ]);
    }


    public function answers(Request $request, $uid)
    {
        $answers = AnswerModel::where('uid', $uid)->get();
        foreach ($answers as $answer) {
            $answer->question;
        }
        return response([
            'code' => 200,
            'data' => $answers
        ]);
    }


    /**
     * @param  Request  $request
     * @param $question_id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @deprecated UserInterlocution/CreateAnswer
     */
    public function createAnswer(Request $request, $question_id)
    {
        $this->validate($request, [
            'content' => 'required|max:100',
        ]);
        $uid = Auth::auth();
        $answer = AnswerModel::updateOrCreate([
            'uid' => $uid,
            'question_id' => $question_id
        ], $request->all());

        // 文本检测
        event(new AuditMedia($uid, 'text', $request->input('content'), 'question', "id={$answer->id}"));
        return response([
            'code' => 200,
            'data' => $answer
        ]);
    }


    public function getAnswer(Request $request, $question_id)
    {
        $uid = Auth::auth();
        $question = QuestionModel::findOrFail($question_id);
        $question->answer = AnswerModel::where(['uid' => $uid, 'question_id' => $question_id])->first();
        return response([
            'code' => 200,
            'data' => $question
        ]);
    }
}
