<?php

namespace App\Http\Controllers\Student;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Models\Lesson;
use App\Models\LessonProgress;

class LessonController extends Controller
{
    public function show(Course $course, Lesson $lesson)
    {
        if (
            $lesson->chapter &&
            $lesson->chapter->lessonSection &&
            $lesson->chapter->lessonSection->module &&
            $lesson->chapter->lessonSection->module->course &&
            $lesson->chapter->lessonSection->module->course->id !== $course->id
        ) {
            abort(404);
        }

        $lesson->load([
            'chapter.lessonSection.module.course.subject',
            'chapter.lessonSection.module.course.level',
			'questions' => fn($q) => $q->where('published', 1)->with('student'),
        ]);

        LessonProgress::updateOrCreate(
            ['user_id' => Auth::id(), 'lesson_id' => $lesson->id],
            ['last_viewed_at' => now()]
        );

        $course = $lesson->chapter->lessonSection->module->course;

        // Collect all chapters across all lesson sections for this course
        $chapters = $course->lessonSections()
            ->with(['chapters.lessons'])
            ->get()
            ->pluck('chapters')
            ->flatten();

        return view('student.lessons.show', compact('lesson', 'chapters'));
    }
	
	
    // Pretty route: /student/{course}/{lesson}
    public function showByCourse(Course $course, Lesson $lesson)
    {
		
		\Log::info('Entered showByCourse route');
		dd('Reached controller');
		dd($course, $lesson);
        // Ensure the lesson actually belongs to the course
        $belongs = $lesson->chapter
            && $lesson->chapter->lessonSection
            && $lesson->chapter->lessonSection->module
            && $lesson->chapter->lessonSection->module->course
            && $lesson->chapter->lessonSection->module->course->id === $course->id;

        if (!$belongs) {
            abort(404);
        }

        return $this->show($lesson); // reuse the existing rendering logic
    }
}