<?php

namespace App\Http\Controllers\Syllabus;

use App\Models\Result\Exam;
use Illuminate\Http\Request;
use App\Models\Syllabus\Lesson;
use App\Models\Academic\Subject;
use App\Http\Controllers\Controller;
use App\Models\Academic\StudentClass;
use App\Http\Requests\StoreLessonRequest;

class LessonController extends Controller
{
    
    public function syllabusStatus(Request $request){
        $exam_id = '';
        $student_class_id = '';
        $subject_id = '';
        $lessons = '';
        $exams = Exam::pluck('exam_name','id');
        $studentClasses = StudentClass::pluck('class_name','id');
        $subject = Subject::pluck('subject_name','id');
        return view('pages.syllabus.syllabusStatus', compact('lessons','exams','studentClasses','subject','exam_id','student_class_id', 'subject_id'));
    }

    public function syllabusStatusSearch(Request $request){
        $request->validate([
            'exam_id' => 'required|integer',
            'student_class' => 'required|integer',
        ]);
        $exam_id = '';
        $student_class_id = '';

        $exam_id = $request->exam_id;
        $student_class_id = $request->student_class;
        $subject_id = $request->subject_id;
        $exams = Exam::pluck('exam_name','id');
        $studentClasses = StudentClass::pluck('class_name','id');
        $subject = Subject::pluck('subject_name','id');
        $exam_name = Exam::findOrFail($exam_id)->exam_name;
        $class_name = StudentClass::findOrFail($student_class_id)->class_name; 
        $lessons = Lesson::query();
        if($request->has('exam_id')){
            $lessons->where('exam_id', $exam_id);
        }
        if($request->has('student_class')){
            $lessons->where('student_class_id', $student_class_id);
        }
        if (!empty($subject_id)) {
            $lessons->where('subject_id', $subject_id);
        }
        $lessons = $lessons->with('lessonTopics')->get();
        return view('pages.syllabus.syllabusStatus', compact('lessons', 'exams','exam_name','class_name','studentClasses','subject','exam_id','student_class_id', 'subject_id'));
    }

    
    public function index(){
        $exam_id = '';
        $student_class_id = '';
        $subject_id = '';
        $exams = Exam::pluck('exam_name','id');
        $studentClasses = StudentClass::pluck('class_name','id');
        $subject = Subject::pluck('subject_name','id');
        $lessons = Lesson::groupBy('exam_id','student_class_id','subject_id')->get();
        return view('pages.syllabus.lesson.index', compact('lessons','exams','studentClasses','subject','exam_id','student_class_id', 'subject_id'));
    }

    public function store(StoreLessonRequest $request){
        $validatedData = $request->validated();
        foreach ($validatedData['name'] as $key => $name) {
            $lesson = new Lesson();
            $lesson->exam_id = $validatedData['exam_id'];
            $lesson->student_class_id = $validatedData['student_class_id'];
            $lesson->subject_id = $validatedData['subject_id'];
            $lesson->name = $name;
            $lesson->save();
        }
        return redirect()->back()->with('success', 'Lesson created successfully.');
    }

    public function edit($id){
        $edit = Lesson::findOrFail($id);
        $student_class_id = $edit->student_class_id;
        $exam_id = $edit->exam_id;
        $subject_id = $edit->subject_id;
        $studentClasses = StudentClass::pluck('class_name','id');
        $exams = Exam::pluck('exam_name','id');
        $subject = Subject::pluck('subject_name','id');
        $lessons = Lesson::groupBy('student_class_id','subject_id','exam_id')->get();
        return view('pages.syllabus.lesson.edit', compact('edit','lessons','studentClasses','exams', 'subject','student_class_id', 'exam_id', 'subject_id'));
    }

    public function update(Request $request, $id){
        $request->validate([
            'exam_id' => 'required|integer',
            'student_class_id' => 'required|integer',
            'subject_id' => 'required|integer',
        ]);

        $oldData = Lesson::findOrFail($id);
        $oldAllData =  group_lessons($oldData->exam_id,$oldData->student_class_id,$oldData->subject_id);

        $old_lesson_ids = [];
        foreach($request->request as $key => $value){
            if(preg_match('/^name_(\d+)$/', $key, $matches)){
                $old_lesson_ids[] = $matches[1];
                Lesson::where('id',$matches[1])->update(['name' => $value]);
            }
        }

        $mainIds = [];
        foreach($oldAllData as $allitem){
            $mainIds[] = $allitem->id;
        }

        $deletedIds = array_diff($mainIds,$old_lesson_ids);
        foreach($deletedIds as $deletedId){
            $deletedLesson = Lesson::findOrFail($deletedId);
            $relatedTopics = $deletedLesson->lessonTopics;
            foreach($relatedTopics as $relatedTopic){
                $relatedTopic->delete();
            }
            $deletedLesson->delete();
        }
        if(!empty($request->name)){
            foreach($request->name as $key => $name) {
                $lesson = new Lesson();
                $lesson->exam_id = $request->exam_id;
                $lesson->student_class_id = $request->student_class_id;
                $lesson->subject_id =  $request->subject_id;
                $lesson->name = $name;
                $lesson->save();
            }
        }

        return redirect()->route('lesson.index')->with('success', 'Lesson updated successfully.');
    }

    public function destroy($id){
        $oldData = Lesson::findOrFail($id);
        $oldAllData =  group_lessons($oldData->exam_id,$oldData->student_class_id,$oldData->subject_id);
        foreach($oldAllData as $oldItem){
            $oldItem->delete();
        }
        return redirect()->route('lesson.index')->with('success', 'Lesson deleted successfully.');
    }

    public function lessonList(Request $request){
        $lessons = Lesson::where([['student_class_id',$request->student_class_id],['subject_id',$request->subject_id]])->select('id','name')->get();
        return response()->json($lessons, 200);
    }
}
