<?php

namespace App\Services\Admin\Products;

use App\Models\Question;
use Illuminate\Http\Request;

class ProductQuestionsService
{
    /** get questions list */
    public function getQuestions(Request $request)
    {
        /** @var LengthAwarePaginator */
        $questions = Question::query()->when($request->input('publish'), function ($query, $publish) {
            if ($publish) {
                $query->where('status', 'publish')->orderBy('created_at', 'desc');
            }
        })->when($request->input('awaiting_questions'), function ($query, $awaiting_questions) {
            if ($awaiting_questions) {
                $query->where('status', 'awaiting')->orderBy('created_at', 'asc');
            }
        })->when($request->input('awaiting_answers'), function ($query, $awaiting_answers) {
            if ($awaiting_answers) {
                $query->whereHas('questionAnswers', function ($query) {
                    $query->where('status', 'awaiting');
                });
            }
        })->orderByRaw("FIELD(questions.status , 'awaiting', 'publish') ASC")
            ->orderBy('questions.created_at', 'desc')->with('user')->with('product')->with('questionAnswers')->paginate(8)->through(fn($question) => [
                'id' => $question->id,
                'question' => $question->question,
                'jalali_created_at' => $question->jalali_created_at,
                'status' => $question->status,

                'answers' => $question->questionAnswers->map(fn($answer) => [
                    'id' => $answer->id,
                    'answer' => $answer->answer,
                    'is_buyer' => $answer->is_buyer,
                    'vote_up' => $answer->vote_up,
                    'vote_down' => $answer->vote_down,
                    'status' => $answer->status,
                    'user' => [
                        'id' => $answer->user->id,
                        'get_name' => $answer->user->get_name,
                        'type' => $answer->user->type,
                        'seller' => $answer->user->seller
                    ],
                ]),
                'product' => [
                    'id' => $question->product->id,
                    'title' => $question->product->title,
                    'slug' => $question->product->slug,
                ],
                'user' => [
                    'id' => $question->user->id,
                    'get_name' => $question->user->get_name,
                ],
            ]);

        $questions->withQueryString();

        return $questions;
    }
}
