<?php

namespace App\Http\Controllers;

use App\Models\Lesson;
use App\Http\Requests\StoreLessonRequest;
use App\Http\Requests\UpdateLessonRequest;
use App\Models\Attendance;
use App\Models\ClassRoom;
use App\Models\Course;
use App\Models\StudentSubscribe;
use Illuminate\Http\Request;

class LessonController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($courseId)
    {
        $course = Course::find($courseId);
        $lessons = Lesson::where('course_id', $courseId)->get();
        return view('lessons.list')->with([
            'lessons' => $lessons,
            'course' => $course,
        ]);
    }

    public function attendancesList($roomId)
    {
         $room = ClassRoom::find($roomId);

        $subscribeIds = StudentSubscribe::with('student')
            ->where('room_id', $roomId)
            ->get()->map(function ($item) {
                return $item->id;
            });

        $attendances = Attendance::with('lesson')
            ->whereIn('subscribe_id', $subscribeIds)
            ->get()
            ->map(function ($item) {
                return $item->lesson->id;
            })->toArray();


        $waitLessons = Lesson::where('course_id', $room->course->id)
            ->get()
            ->except($attendances);

        $attenuatedLessons = Lesson::where('course_id', $room->course->id)
            ->get()
            ->except($waitLessons->map(function ($item) {
                return $item->id;
            })->toArray());

        $presents = Attendance::selectRaw('lesson_id,count(*) As count')
            ->whereIn('lesson_id', $attenuatedLessons->map(function ($item) {
                return $item->id;
            }))
            ->where('is_present', 1)
            ->whereIn('subscribe_id', $subscribeIds)
            ->groupBy('lesson_id')
            ->get();

        $absents = Attendance::selectRaw('lesson_id,count(*) As count')
            ->whereIn('lesson_id', $attenuatedLessons->map(function ($item) {
                return $item->id;
            }))
            ->where('is_present', -1)
            ->whereIn('subscribe_id', $subscribeIds)
            ->groupBy('lesson_id')
            ->get();

        return view('lessons.attendance-list')->with([
            'attenuatedLessons' => $attenuatedLessons,
            'waitLessons' => $waitLessons,
            'room' => $room,
            'presents' => $presents,
            'absents' => $absents,
        ]);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreLessonRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreLessonRequest $request)
    {
        $request->validate([
            'title' => 'required',
            // 'description' => 'required',
        ], [
            'title.required' => 'يرجى اضافة عنوان الدرس .',
            // 'description.required' => 'يرجى اضافة وصف للدرس .',
        ]);
        try {
            $newLesson = new Lesson();
            $newLesson->course_id = $request->courseId;
            $newLesson->title = $request->title;

            // $newLesson->description = $request->description;
            $newLesson->save();
            
            return back()->with(['success' => 'تم إضافة بيانات الدرس بنجاح']);
        } catch (\Throwable $th) {
            return back()->with(['error' => 'لم يتم إضافة بيانات الدرس  ']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Lesson  $lesson
     * @return \Illuminate\Http\Response
     */
    public function show(Lesson $lesson)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateLessonRequest  $request
     * @param  \App\Models\Lesson  $lesson
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateLessonRequest $request, Lesson $lesson)
    {
        $request->validate([
            'title' => 'required',
            // 'description' => 'required',
        ], [
            'title.required' => 'يرجى اضافة عنوان الدرس .',
            // 'description.required' => 'يرجى اضافة وصف للدرس .',
        ]);
        try {

            $newLesson = Lesson::find($request->id);
            $newLesson->title = $request->title;
            // $newLesson->description = $request->description;
            $newLesson->update();

            return back()->with(['success' => 'تم تعديل بيانات الدرس بنجاح']);
        } catch (\Throwable $th) {
            return back()->with(['error' => 'لم يتم تعديل بيانات الدرس  ']);
        }
    }

    /**
     * [Description for delete]
     *
     * @param Request $request
     *
     * @return [type]
     *
     */
    public function delete(Request $request)
    {
        try {
            Lesson::find($request->id)->delete();
            return back()->with(['success' => 'تم حذف الدرس بنجاح']);
        } catch (\Throwable $th) {
            return back()->with(['error' => 'لم يتم حذف الدرس ']);
        }
    }

    /**
     * active and not active course
     *
     * @param Request $request
     *
     * @return [type]
     *
     */
    public function toggle(Request $request)
    {
        try {
            $student = Lesson::find($request->id);
            $student->is_active *= -1;
            $student->save();
            return back()->with(['success' => 'تمت تحديث البيانات بنجاح']);
        } catch (\Throwable $th) {
            return back()->with(['error' => 'لم يتم تحديث البيانات']);
        }
    }
}
