<?php

namespace App\Http\Controllers\Admin;

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

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

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

    public function create()
    {
        $elements = ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9'];
        return view('admin.questions.create', compact('elements'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'code' => 'required|string|max:10|unique:questions,code',
            'element' => 'required|string|max:255',
            'question' => 'required|string',
            'order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
            'answer_options' => 'required|array|min:1',
            'answer_options.*.label' => 'required|string|max:255',
            'answer_options.*.score' => 'required|integer|min:1',
            'answer_options.*.weight' => 'required|numeric|min:0',
            'answer_options.*.order' => 'nullable|integer|min:0',
        ]);

        $question = Question::create([
            'code' => $request->code,
            'element' => $request->element,
            'question' => $request->question,
            'order' => $request->order ?? 0,
            'is_active' => $request->has('is_active'),
        ]);

        // Create answer options
        foreach ($request->answer_options as $index => $optionData) {
            AnswerOption::create([
                'question_id' => $question->id,
                'label' => $optionData['label'],
                'text' => $optionData['label'], // Keep for backward compatibility
                'score' => $optionData['score'],
                'weight' => $optionData['weight'],
                'order' => $optionData['order'] ?? $index,
                'is_active' => true,
            ]);
        }

        return redirect()->route('admin.questions.index')
            ->with('success', 'Pertanyaan berhasil ditambahkan.');
    }

    public function show($id)
    {
        $question = Question::with('answerOptions')->findOrFail($id);
        return view('admin.questions.show', compact('question'));
    }

    public function edit($id)
    {
        $question = Question::with('answerOptions')->findOrFail($id);
        $elements = ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9'];
        return view('admin.questions.edit', compact('question', 'elements'));
    }

    public function update(Request $request, $id)
    {
        $question = Question::findOrFail($id);

        $request->validate([
            'code' => 'required|string|max:10|unique:questions,code,' . $id,
            'element' => 'required|string|max:255',
            'question' => 'required|string',
            'order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
            'answer_options' => 'required|array|min:1',
            'answer_options.*.id' => 'nullable|exists:answer_options,id',
            'answer_options.*.label' => 'required|string|max:255',
            'answer_options.*.score' => 'required|integer|min:1',
            'answer_options.*.weight' => 'required|numeric|min:0',
            'answer_options.*.order' => 'nullable|integer|min:0',
        ]);

        $question->update([
            'code' => $request->code,
            'element' => $request->element,
            'question' => $request->question,
            'order' => $request->order ?? 0,
            'is_active' => $request->has('is_active'),
        ]);

        // Update or create answer options
        $existingOptionIds = [];
        foreach ($request->answer_options as $index => $optionData) {
            if (isset($optionData['id']) && $optionData['id']) {
                // Update existing
                $option = AnswerOption::where('id', $optionData['id'])
                    ->where('question_id', $question->id)
                    ->first();
                if ($option) {
                    $option->update([
                        'label' => $optionData['label'],
                        'text' => $optionData['label'],
                        'score' => $optionData['score'],
                        'weight' => $optionData['weight'],
                        'order' => $optionData['order'] ?? $index,
                    ]);
                    $existingOptionIds[] = $option->id;
                }
            } else {
                // Create new
                $option = AnswerOption::create([
                    'question_id' => $question->id,
                    'label' => $optionData['label'],
                    'text' => $optionData['label'],
                    'score' => $optionData['score'],
                    'weight' => $optionData['weight'],
                    'order' => $optionData['order'] ?? $index,
                    'is_active' => true,
                ]);
                $existingOptionIds[] = $option->id;
            }
        }

        // Delete answer options that are no longer in the request
        AnswerOption::where('question_id', $question->id)
            ->whereNotIn('id', $existingOptionIds)
            ->delete();

        return redirect()->route('admin.questions.index')
            ->with('success', 'Pertanyaan berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $question = Question::findOrFail($id);
        
        // Check if question is being used
        if ($question->responses()->count() > 0) {
            return redirect()->route('admin.questions.index')
                ->with('error', 'Pertanyaan tidak dapat dihapus karena sedang digunakan dalam response.');
        }

        // Delete answer options
        $question->answerOptions()->delete();
        
        // Delete question
        $question->delete();

        return redirect()->route('admin.questions.index')
            ->with('success', 'Pertanyaan berhasil dihapus.');
    }
}



