<?php

namespace Bongo\Builder\Http\Controllers\Api;

use Bongo\Framework\Http\Controllers\AbstractApiController;
use Bongo\Question\Models\Question;
use Bongo\Question\Models\QuestionCategory;
use Illuminate\Http\Request;
use Throwable;

class QuestionController extends AbstractApiController
{
    /** @throws Throwable */
    public function index(Request $request)
    {
        $questions = $this->getQuestions($request);

        $data = [
            'questions' => $questions,
            'style' => $request->get('style'),
        ];

        $style = make_key($request->get('style', 'style_1'));

        if (view()->exists("builder::frontend.questions.{$style}")) {
            return view("builder::frontend.questions.{$style}")
                ->with($data)
                ->render();
        }

        return view('builder::frontend.questions.style_1')
            ->with($data)
            ->render();
    }

    private function getQuestions(Request $request)
    {
        if (! $request->filled('ref')) {
            return Question::query()
                ->active()
                ->orderBy('name')
                ->get();
        }

        $questionCategory = QuestionCategory::query()
            ->whereUuid($request->get('ref'))
            ->firstOrFail();

        return $questionCategory
            ->questions()
            ->active()
            ->get();
    }
}
