<?php

namespace App\Http\Controllers;

use App\Models\Response;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ResponseController extends Controller
{
    // Menampilkan semua respons kuisioner
    public function index()
    {
        // Mengambil semua respons dari tabel 'responses'
        $responses = Response::all();

        return Inertia::render('Responses/Index', [
            'responses' => $responses, // Mengirimkan data respons ke frontend
        ]);
    }

    // Menyimpan respons kuisioner
    public function store(Request $request)
    {
        // Validasi data yang dikirimkan melalui form
        $validated = $request->validate([
            'phone_number' => 'required|string',
            'answers' => 'required|array', // Memastikan bahwa answers adalah array
            'answers.*.question_id' => 'required|integer', // Validasi question_id di dalam answers
            'answers.*.answer' => 'required|string', // Validasi setiap jawaban
        ]);

        // Menyimpan setiap jawaban ke dalam tabel 'responses'
        foreach ($validated['answers'] as $answer) {
            Response::create([
                'phone_number' => $validated['phone_number'],
                'question_id' => $answer['question_id'],
                'answer' => $answer['answer'],
            ]);
        }

        // Redirect kembali dengan pesan sukses
        return redirect()->route('kuisioner.index')->with('success', 'Kuisioner berhasil disubmit!');
    }
}
