<?php

namespace App\Http\Controllers\Admin\Invite;

use App\Http\Resources\Admin\Invite\QuestionCollection;
use App\Models\Invite\QuestionTemplateModel;
use App\Models\User\LikeInviteQuestionModel;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class QuestionController extends Controller
{


    /**
     * 问题列表
     * @param  Request  $request
     * @return QuestionCollection
     */
    public function index(Request $request)
    {
        $questions = LikeInviteQuestionModel::when($request->filled('uid'), function ($query) use ($request) {
            return $query->where('uid', $request->uid);
        })->when($request->get('sex'), function ($query) use ($request) {
            return $query->where('sex', $request->sex);
        })->when($request->filled('template_id'), function ($query) use ($request) {
            return $query->where('template_id', $request->template_id);
        })->when($request->get('system'), function ($query) use ($request) {
            if ($request->system == 1) {
                return $query->where('select', 1);
            } else {
                return $query->where('select', 0);
            }
        })->when($request->filled('question_type'), function ($query) use ($request) {
            return $query->where('question_type', $request->question_type);
        })
            ->orderBy($request->get('sort_by', 'thumbs'), 'desc')
            ->paginate($request->input('per_page', 20));
        foreach ($questions as $question) {
            $question->question = QuestionTemplateModel::find($question->template_id);
        }
        return new QuestionCollection($questions);
    }


    /**
     * 推荐
     * @param  Request  $request
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function recommend(Request $request, $id)
    {
        $question = LikeInviteQuestionModel::findOrFail($id);
        $question->select = true;
        $question->save();

        QuestionTemplateModel::where('id', $question->template_id)->increment('select_count');

        return response([
            'code' => 200,
            'message' => 'OK',
            'data' => $question
        ]);
    }
}
