<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Exam;
use App\Models\Lecture;
use App\Models\ExamQuestion;
use App\Models\ExamQuestionOption;
use App\Rules\HasCorrectAnswer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

use function PHPUnit\Framework\isArray;

class ExamController extends Controller
{


    /**
     * Show the form for creating a new resource.
     */
    public function exam(Lecture $lecture, Request $request)
    {


        $lecture = Lecture::where('id', $lecture->id)->with('exam.questions.options')->first();

        if (empty($lecture->exam)):
            return view('admin.exam.create', compact('lecture'));
        else:
            // $exam = $lecture->exam;
            return view('admin.exam.edit', compact('lecture'));
        endif;
    }

    public function store(Request $request)
    {
        $request->validate(
            [
                'name' => 'required|string|max:255',
                'status' => 'required|in:Show,Hide',
                'retake' => 'required|boolean',
                'questions' => 'required|array|min:1',
                'questions.*' => 'required|array',
                'questions.*.title' => 'required|string|max:255',
                'questions.*.options' => 'required|array|min:2|max:6',
                'questions.*.options.*' => 'required|string|max:255',
                'questions.*.is_true' => 'required|array|min:2|contains:1',
                'questions.*.is_true.*' => 'required|in:1,0',
            ],
            [
                'questions.*.is_true.contains' => "The :attribute must have at least 1 correct answer."
            ]
        );
        $lecture = Lecture::find($request->lecture_id);
        $exam =  Exam::updateOrCreate([
            'lecture_id' => $request->lecture_id,
        ], [
            'name' => $request->name,
            'status' => $request->status,
            'retake' => $request->retake
        ]);


        foreach ($request->questions as $key => $question):

            $examQuestion =   ExamQuestion::create([
                'exam_id' => $exam->id,
                'question' => $request->questions[$key]['title'],
            ]);

            foreach ($question['options'] as $optionKey => $option):
                ExamQuestionOption::create([
                    'exam_question_id' => $examQuestion->id,
                    'option' => $request->questions[$key]['options'][$optionKey],
                    'is_correct' => $request->questions[$key]['is_true'][$optionKey],
                ]);
            endforeach;
        endforeach;

        return to_route('lectures.index', ['unit_id' => $lecture->unit_id])->with('success', __('trans.alert.success.done_create', ['name' => 'Exam']));
    }


    public function update(Exam $exam, Request $request)
    {

        $request->validate([
            'lecture_id' => 'required|exists:lectures,id',
            'name' => 'required|string|max:255',
            'status' => 'required|in:Show,Hide',
            'retake' => 'required|boolean',
            'questions' => 'required|array|min:1',
            'questions.*' => 'required|array',
            'questions.*.id' => 'nullable|exists:exam_questions,id',
            'questions.*.title' => 'required|string|max:255',
            'questions.*.options' => ['required', 'array', 'min:2', 'max:6', new HasCorrectAnswer],
            'questions.*.options.*' => 'required|array',
            'questions.*.options.*.id' => 'nullable|exists:exam_question_options,id',
            'questions.*.options.*.text' => 'required|string|max:255',
            'questions.*.options.*.is_true' => 'required|in:1,0',
        ]);


        $exam->update([
            'lecture_id' => $request->lecture_id,
            'name' => $request->name,
            'status' => $request->status,
            'retake' => $request->retake
        ]);
        $lecture = Lecture::find($request->lecture_id);

        $newQuestionIds = [];
        $newExamIds = [];
        $newOptionsIds = [];
        $newExamQuestionIds = [];
        foreach ($request->questions as $questionData) {

            $question = ExamQuestion::updateOrCreate(
                ['id' => $questionData['id'] ?? null],
                [
                    'exam_id' => $exam->id,
                    'question' => $questionData['title'],
                ]
            );
            $newQuestionIds[] = $question->id;
            $newExamIds[] = $question->exam_id;
            if (isset($questionData['options']) && is_array($questionData['options'])) {
                foreach ($questionData['options'] as $optionData) {
                    $createdOption =    ExamQuestionOption::updateOrCreate(
                        ['id' => $optionData['id'] ?? null],
                        [
                            'exam_question_id' => $question->id,
                            'option' => $optionData['text'],
                            'is_correct' => $optionData['is_true'],
                        ]
                    );
                    $newOptionsIds[] = $createdOption->id;
                    $newExamQuestionIds[] = $createdOption->exam_question_id;
                }
            }
        }

        ExamQuestion::whereIn('exam_id', $newExamIds)
            ->whereNotIn('id', $newQuestionIds)->delete();
        ExamQuestionOption::whereIn('exam_question_id', $newExamQuestionIds)
            ->whereNotIn('id', $newOptionsIds)->delete();

        return to_route('lectures.index', ['unit_id' => $lecture->unit_id])->with('success', __('trans.alert.success.done_update', ['name' => 'Exam']));
    }


    public function delete(Exam $exam)
    {
        $exam->delete();
        return to_route('lectures.index')->with('success', __('trans.alert.success.done_delete', ['name' => 'Exam']));
    }
}
