<?php

namespace App\Http\Controllers;

use App\Models\Survey;
use App\Models\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StaffSurveyController extends Controller
{
    public function show(Survey $survey)
    {
        $survey->load('sections.questions.options');
        return view('staff.surveys.soalan', compact('survey'));
    }

    public function store(Request $request, Survey $survey)
    {
        $request->validate([
            'respondent_name' => 'required|string|max:255',
            'respondent_no_pekerja' => 'required|string|max:255',
            'respondent_jabatan' => 'required|string|max:255',
            'answers' => 'required|array',
            'answers.*' => 'required',
        ], [
            'answers.*.required' => 'Sila jawab semua soalan yang bertanda *.'
        ]);

        try {
            DB::beginTransaction();

            // 1. Cipta rekod Response utama
            $response = $survey->responses()->create([
                'user_id' => null, // Always null for public
                'respondent_name' => $request->respondent_name,
                'respondent_no_pekerja' => $request->respondent_no_pekerja,
                'respondent_jabatan' => $request->respondent_jabatan,
            ]);

            // 2. Simpan setiap jawapan soalan
            foreach ($request->answers as $question_id => $answer_data) {
                if (is_array($answer_data)) {
                    // Untuk soalan jenis Checkbox atau Multiple Select
                    foreach ($answer_data as $single_answer) {
                        $response->answers()->create([
                            'question_id' => $question_id,
                            'answer_text' => $single_answer,
                        ]);
                    }
                } else {
                    // Untuk soalan jenis Radio, Text, atau Textarea
                    $response->answers()->create([
                        'question_id' => $question_id,
                        'answer_text' => $answer_data,
                    ]);
                }
            }

            DB::commit();

            return redirect()->route('surveys.success');

        } catch (\Exception $e) {
            DB::rollBack();
            // Log ralat jika perlu: \Log::error($e->getMessage());
            return redirect()->back()->with('error', 'Gagal menghantar jawapan. Sila cuba lagi.');
        }
    }
}
