<?php

namespace App\Http\Controllers\Admin;

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

class QuizQuestionController extends Controller
{
    public function index()
    {
        $questions = QuizQuestion::orderBy('level')->orderBy('id', 'desc')->paginate(15);
        return view('admin.quiz.index', compact('questions'));
    }

    public function create()
    {
        return view('admin.quiz.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'level' => 'required|integer|min:1|max:5',
            'question_text' => 'required|string',
            'option_a' => 'required|string',
            'option_b' => 'required|string',
            'option_c' => 'required|string',
            'option_d' => 'required|string',
            'correct_option' => 'required|in:A,B,C,D',
            'explanation' => 'nullable|string',
        ]);

        foreach (['option_a', 'option_b', 'option_c', 'option_d'] as $field) {
            $validated[$field] = $this->cleanEmojis($validated[$field]);
        }

        QuizQuestion::create($validated);

        return redirect()->route('admin.quiz.index')->with('success', 'Soal kuis level ' . $validated['level'] . ' berhasil ditambahkan!');
    }

    public function edit(QuizQuestion $quiz)
    {
        return view('admin.quiz.edit', compact('quiz'));
    }

    public function update(Request $request, QuizQuestion $quiz)
    {
        $validated = $request->validate([
            'level' => 'required|integer|min:1|max:5',
            'question_text' => 'required|string',
            'option_a' => 'required|string',
            'option_b' => 'required|string',
            'option_c' => 'required|string',
            'option_d' => 'required|string',
            'correct_option' => 'required|in:A,B,C,D',
            'explanation' => 'nullable|string',
        ]);

        foreach (['option_a', 'option_b', 'option_c', 'option_d'] as $field) {
            $validated[$field] = $this->cleanEmojis($validated[$field]);
        }

        $quiz->update($validated);

        return redirect()->route('admin.quiz.index')->with('success', 'Soal kuis berhasil diperbarui!');
    }

    public function destroy(QuizQuestion $quiz)
    {
        $quiz->delete();
        return redirect()->route('admin.quiz.index')->with('success', 'Soal kuis berhasil dihapus.');
    }

    private function cleanEmojis($text)
    {
        if (is_null($text)) return null;
        $clean = preg_replace('/[\x{1F300}-\x{1F9FF}]|[\x{2700}-\x{27BF}]|[\x{2600}-\x{26FF}]|\x{200d}/u', '', $text);
        return trim(preg_replace('/\s+/', ' ', $clean));
    }
}
