<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AnswerOption;
use Illuminate\Http\Request;

class AnswerOptionController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $answerOptions = AnswerOption::orderBy('order')->get();
        return view('admin.answer-options.index', compact('answerOptions'));
    }

    public function create()
    {
        return view('admin.answer-options.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'text' => 'required|string|max:255',
            'score' => 'required|integer|min:1',
            'weight' => 'required|numeric|min:0',
            'order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
        ]);

        AnswerOption::create([
            'text' => $request->text,
            'score' => $request->score,
            'weight' => $request->weight,
            'order' => $request->order ?? 0,
            'is_active' => $request->has('is_active'),
        ]);

        return redirect()->route('admin.answer-options.index')
            ->with('success', 'Opsi jawaban berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $answerOption = AnswerOption::findOrFail($id);
        return view('admin.answer-options.edit', compact('answerOption'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'text' => 'required|string|max:255',
            'score' => 'required|integer|min:1',
            'weight' => 'required|numeric|min:0',
            'order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
        ]);

        $answerOption = AnswerOption::findOrFail($id);
        $answerOption->update([
            'text' => $request->text,
            'score' => $request->score,
            'weight' => $request->weight,
            'order' => $request->order ?? 0,
            'is_active' => $request->has('is_active'),
        ]);

        return redirect()->route('admin.answer-options.index')
            ->with('success', 'Opsi jawaban berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $answerOption = AnswerOption::findOrFail($id);
        
        // Check if answer option is being used
        if ($answerOption->responses()->count() > 0) {
            return redirect()->route('admin.answer-options.index')
                ->with('error', 'Opsi jawaban tidak dapat dihapus karena sedang digunakan dalam response.');
        }

        $answerOption->delete();

        return redirect()->route('admin.answer-options.index')
            ->with('success', 'Opsi jawaban berhasil dihapus.');
    }
}



