<?php

namespace App\Http\Controllers\Admin;

use App\Models\Survey;
use App\Models\Response;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ResponseController extends Controller
{

    public function list(Request $request)
    {
        $query = Survey::withCount('responses');

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('title', 'like', "%{$search}%");
        }

        $surveys = $query->latest()->get();

        return view('admin.responses.list', compact('surveys'));
    }

    public function showRespondents(Survey $survey)
    {
        $responses = $survey->responses()
            ->with('user')
            ->orderByDesc('created_at')
            ->get();

        return view('admin.responses.respondents', compact('survey', 'responses'));
    }


    public function detail(Response $response)
    {
        $response->load([
            'survey.sections.questions',
            'answers.question'
        ]);

        $answersByQuestionId = $response->answers->keyBy('question_id');

        return view('admin.responses.detail', compact('response', 'answersByQuestionId'));
    }
}
