<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Questions;
use App\Models\Answers;
use App\Models\Hints;

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

    public function answers_get_data(Request $request)
    {
        $questions_all  = Questions::all();
        $questions      = Questions::findOrFail($request->id);
        $answers        = Answers::where('question_id', $request->id)->get();
        $hints          = Hints::where('question_id', $request->id)->first();

        return response()->json([
            'questions_all' => $questions_all,
            'questions'     => $questions,
            'answers'       => $answers,
            'hints'         => $hints,
        ]);
    }

    public function answers_store(Request $request)
    {
        $validatedData = $request->validate([
            'question_id'        => 'required|integer|exists:questions,id',
            'answer_id'          => 'array',
            'answer_id.*'        => 'nullable|integer|exists:answers,id',
            'answer_text'        => 'required|array',
            'answer_text.*'      => 'required|string',
            'next_question_id'   => 'array',
            'next_question_id.*' => 'nullable|integer|exists:questions,id',
            'is_correct'         => 'required|array',
            'is_correct.*'       => 'required|boolean',
            'hint_text'          => 'nullable|string',
        ]);

        try {
            $answers = [];

            foreach ($validatedData['answer_text'] as $index => $answerText) {
                if (isset($validatedData['answer_id'][$index]) && !empty($validatedData['answer_id'][$index])) {
                    $answer = Answers::find($validatedData['answer_id'][$index]);
                    if (!$answer) {
                        continue;
                    }
                } else {
                    $answer = new Answers();
                }

                $answer->question_id      = $validatedData['question_id'];
                $answer->answer_text      = $answerText;
                $answer->next_question_id = $validatedData['next_question_id'][$index];
                $answer->is_correct       = $validatedData['is_correct'][$index];
                $answer->save();

                $answers[] = $answer;
            }

            if (!empty($validatedData['hint_text'])) {
                $hint = Hints::updateOrCreate(
                    ['question_id' => $validatedData['question_id']],
                    ['hint_text' => $validatedData['hint_text']]
                );
            }

            return response()->json([
                'status' => 'success',
                'message' => 'บันทึกข้อมูลสำเร็จ',
                'answers' => $answers,
                'hint' => $hint ?? null
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'เกิดข้อผิดพลาดในการบันทึกข้อมูล',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function answers_delete(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:answers,id',
        ]);

        try {
            $answer = Answers::find($request->id);

            if ($answer) {
                $answer->delete();
                return response()->json([
                    'status' => 'success',
                    'message' => 'ลบคำตอบสำเร็จแล้ว'
                ]);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => 'ไม่พบคำตอบที่ต้องการลบ'
                ], 404);
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'เกิดข้อผิดพลาดในการลบคำตอบ',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
