<?php

namespace App\Http\Controllers;

use App\Models\OPD;
use App\Models\Question;
use App\Models\Response;
use App\Models\AnswerOption;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PublicController extends Controller
{
    public function index()
    {
        $opds = OPD::where('is_active', true)->orderBy('name')->get();
        return view('public.index', compact('opds'));
    }

    public function survey($opdId)
    {
        $opd = OPD::findOrFail($opdId);
        $questions = Question::where('is_active', true)
            ->with(['activeAnswerOptions' => function($query) {
                $query->orderBy('order');
            }])
            ->orderBy('order')
            ->get();
        return view('public.survey', compact('opd', 'questions'));
    }

    public function submit(Request $request, $opdId)
    {
        $opd = OPD::findOrFail($opdId);
        
        $request->validate([
            'responses' => 'required|array',
            'responses.*.question_id' => 'required|exists:questions,id',
            'responses.*.answer_option_id' => 'required|exists:answer_options,id',
            'respondent_name' => 'nullable|string|max:255',
            'respondent_phone' => 'nullable|string|max:20',
            'respondent_email' => 'nullable|email|max:255',
        ]);

        DB::transaction(function () use ($request, $opd) {
            foreach ($request->responses as $responseData) {
                $answerOption = AnswerOption::findOrFail($responseData['answer_option_id']);
                Response::create([
                    'opd_id' => $opd->id,
                    'question_id' => $responseData['question_id'],
                    'answer_option_id' => $responseData['answer_option_id'],
                    'rating' => $answerOption->score, // Keep for backward compatibility
                    'comment' => $responseData['comment'] ?? null,
                    'respondent_name' => $request->respondent_name,
                    'respondent_phone' => $request->respondent_phone,
                    'respondent_email' => $request->respondent_email,
                    'ip_address' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ]);
            }
        });

        return redirect()->route('public.thankyou')->with('success', 'Terima kasih atas partisipasi Anda dalam survey ini.');
    }

    public function thankyou()
    {
        return view('public.thankyou');
    }
}

