<?php

namespace App\Http\Controllers\Admin;

use App\Models\Exam;
use App\Models\Lesson;
use App\Models\Classroom;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ExamController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Inertia\Response|\Inertia\ResponseFactory
     */
    public function index()
    {
        //get exams
        $exams = Exam::when(request()->q, function ($exams) {
            $exams = $exams->where('title', 'like', '%' . request()->q . '%');
        })->with(['lesson', 'classroom'])->withCount('questions')->latest()->paginate(5);

        //append query string to pagination links
        $exams->appends(['q' => request()->q]);

        //render with inertia
        return inertia('Admin/Exams/Index', [
            'exams' => $exams,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Inertia\Response|\Inertia\ResponseFactory
     */
    public function create()
    {
        //get lessons
        $lessons = Lesson::all();

        //get classrooms
        $classrooms = Classroom::all();

        //render with inertia
        return inertia('Admin/Exams/Create', [
            'lessons' => $lessons,
            'classrooms' => $classrooms,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        //validate request
        $request->validate([
            'title' => 'required',
            'lesson_id' => 'required|integer',
            'classroom_id' => 'required|integer',
            'duration' => 'required|integer',
            'description' => 'required',
            'random_question' => 'required',
            'random_answer' => 'required',
            'show_answer' => 'required',
            'question_weights' => 'nullable|array',
            'question_weights.pg' => 'nullable|numeric|min:0|max:100',
            'question_weights.pg_kompleks' => 'nullable|numeric|min:0|max:100',
            'question_weights.menjodohkan' => 'nullable|numeric|min:0|max:100',
            'question_weights.isian' => 'nullable|numeric|min:0|max:100',
            'question_weights.uraian' => 'nullable|numeric|min:0|max:100',
        ]);

        //create exam
        $exam = Exam::create([
            'title' => $request->title,
            'lesson_id' => $request->lesson_id,
            'classroom_id' => $request->classroom_id,
            'duration' => $request->duration,
            'description' => $request->description,
            'random_question' => $request->random_question,
            'random_answer' => $request->random_answer,
            'show_answer' => $request->show_answer,
            'question_weights' => $request->question_weights,
        ]);

        //redirect
        return redirect()->back()->with([
            'new_exam_id' => $exam->id,
            'new_exam_title' => $exam->title,
        ]);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Inertia\Response|\Inertia\ResponseFactory
     */
    public function show($id)
    {
        //get exam
        $exam = Exam::with('lesson', 'classroom')->findOrFail($id);

        $alreadyAssignedIds = $exam->questions()->pluck('questions.id')->toArray();

        $availableQuestions = \App\Models\Question::where('lesson_id', $exam->lesson_id)
            ->whereNotIn('id', $alreadyAssignedIds)
            ->get();

        //get relation questions with pagination
        $exam->setRelation('questions', $exam->questions()->paginate(5));

        //render with inertia
        return inertia('Admin/Exams/Show', [
            'exam' => $exam,
            'availableQuestions' => $availableQuestions,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Inertia\Response|\Inertia\ResponseFactory
     */
    public function edit($id)
    {
        //get exam
        $exam = Exam::findOrFail($id);

        //get lessons
        $lessons = Lesson::all();

        //get classrooms
        $classrooms = Classroom::all();

        //render with inertia
        return inertia('Admin/Exams/Edit', [
            'exam' => $exam,
            'lessons' => $lessons,
            'classrooms' => $classrooms,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Exam $exam)
    {
        //validate request
        $request->validate([
            'title' => 'required',
            'lesson_id' => 'required|integer',
            'classroom_id' => 'required|integer',
            'duration' => 'required|integer',
            'description' => 'required',
            'random_question' => 'required',
            'random_answer' => 'required',
            'show_answer' => 'required',
            'question_weights' => 'nullable|array',
            'question_weights.pg' => 'nullable|numeric|min:0|max:100',
            'question_weights.pg_kompleks' => 'nullable|numeric|min:0|max:100',
            'question_weights.menjodohkan' => 'nullable|numeric|min:0|max:100',
            'question_weights.isian' => 'nullable|numeric|min:0|max:100',
            'question_weights.uraian' => 'nullable|numeric|min:0|max:100',
        ]);

        //update exam
        $exam->update([
            'title' => $request->title,
            'lesson_id' => $request->lesson_id,
            'classroom_id' => $request->classroom_id,
            'duration' => $request->duration,
            'description' => $request->description,
            'random_question' => $request->random_question,
            'random_answer' => $request->random_answer,
            'show_answer' => $request->show_answer,
            'question_weights' => $request->question_weights,
        ]);

        //redirect
        return redirect()->route('admin.exams.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        //get exam
        $exam = Exam::findOrFail($id);

        //delete exam
        $exam->delete();

        //redirect
        return redirect()->route('admin.exams.index');
    }

    /**
     * Assign Random Questions from Bank Soal
     */
    public function assignQuestionsRandom(Request $request, Exam $exam)
    {
        $request->validate([
            'question_count' => 'required|integer|min:1'
        ]);

        $questionsToAssign = \App\Models\Question::where('lesson_id', $exam->lesson_id)
            ->inRandomOrder()
            ->limit($request->question_count)
            ->pluck('id');

        if ($questionsToAssign->isEmpty()) {
            return back()->with('error', 'Tidak ada soal tersedia di bank soal untuk Mata Pelajaran ini.');
        }

        // Attach without detaching existing
        $exam->questions()->syncWithoutDetaching($questionsToAssign);

        return back()->with('success', count($questionsToAssign) . ' Soal berhasil ditambahkan secara acak.');
    }

    /**
     * Assign Manual Questions from Bank Soal
     */
    public function assignQuestionsManual(Request $request, Exam $exam)
    {
        $request->validate([
            'question_ids' => 'required|array'
        ]);

        $exam->questions()->syncWithoutDetaching($request->question_ids);

        return back()->with('success', 'Soal berhasil ditambahkan.');
    }

    /**
     * Remove question from Exam
     */
    public function removeQuestion(Exam $exam, \App\Models\Question $question)
    {
        $exam->questions()->detach($question->id);
        return back()->with('success', 'Soal berhasil dilepas dari ujian.');
    }

}