<?php

namespace App\Business\CustomerProfile\Survies;

use Illuminate\Support\Facades\DB;

class SurveyGetter
{
    public static function getQuestionsBySurvey($survey)
    {
        $questions = DB::table('satis_questions as sq')
            ->join('satis_answers_options as sao', 'sao.question_id', '=', 'sq.id')
            ->join('satis_survies_questions as ssq', 'sq.id', '=', 'ssq.question_id')
            ->where('ssq.survey_id', $survey)
            ->where('sq.is_active', true)
            ->select('sq.*', 'sao.answers as answer_label', 'sao.id as answer' )
            ->get();

        $groupedQuestions = $questions->groupBy('id')->map(function ($group) {
            $question = $group->first();
            return [
                'question' => $question->id,
                'question_label' => $question->question,
                'answer_type' => $question->answer_type,
                'answers' => $group->map(function ($a) {
                    return [
                        'answer_label' => $a->answer_label,
                        'answer' => $a->answer,
                    ];
                })->values()
                // 'answers' => $group->pluck('answer_label', 'answer')->all()
            ];
        })->values();

        return $groupedQuestions;
    }

}
