<?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;
use App\Models\User;


class DashboardController extends Controller
{
	public function index()
	{
		$user = Auth::user();

		// 1) Enrolled courses (with subject & level)
		$enrolled = $user->courses()
			->with(['subject', 'level'])
			->get();

		// 2) Courses not yet enrolled
		$availableCourses = Course::with(['subject', 'level'])
			->whereNotIn('id', $enrolled->pluck('id'))
			->get();

		// 3) Find which courses this user has started (based on LessonProgress)
		$progressEntries = LessonProgress::where('user_id', $user->id)
			->with('lesson.chapter.lessonSection.module.course')
			->orderByDesc('last_viewed_at')
			->get();

		$startedCourseIds = $progressEntries
			->pluck('lesson.chapter.lessonSection.module.course.id')
			->unique();

		// Split enrolled courses into inProgress and notStarted
		[$inProgressCourses, $notStartedCourses] = $enrolled->partition(
			fn($course) => $startedCourseIds->contains($course->id)
		);

		// 4) Build map of the *latest viewed lesson per course*
		$lastLessonsByCourse = collect();

		foreach ($progressEntries as $entry) {
			$course = $entry->lesson->chapter->lessonSection->module->course;
			$courseId = $course->id;

			// Store the first (i.e. most recent, since entries are sorted DESC) occurrence
			if (!$lastLessonsByCourse->has($courseId)) {
				$lastLessonsByCourse->put($courseId, $entry->lesson);
			}
		}

		return view('student.dashboard', [
			'inProgressCourses'   => $inProgressCourses,
			'notStartedCourses'   => $notStartedCourses,
			'availableCourses'    => $availableCourses,
			'lastLessonsByCourse' => $lastLessonsByCourse,
		]);
	}

}