<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\Lesson;
use App\Models\Quiz;
use App\Models\TimetableEntry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $user     = Auth::user()->load('studentProfile.grade', 'enrolledSubjects');
        $subjects = $user->enrolledSubjects;

        $recentLessons = Lesson::whereIn('subject_id', $subjects->pluck('id'))
            ->with('subject', 'teacher')
            ->latest('lesson_date')
            ->take(6)
            ->get();

        $upcomingQuizzes = Quiz::whereIn('subject_id', $subjects->pluck('id'))
            ->where('quiz_date', '>=', now())
            ->with('subject')
            ->orderBy('quiz_date')
            ->take(3)
            ->get();

        $announcements = Announcement::latest('published_at')->take(5)->get();

        $timetable = TimetableEntry::with('subject')
            ->get()
            ->groupBy('day_of_week');

        $marks = \App\Models\Mark::where('student_id', $user->id)
            ->with('quiz.subject')
            ->latest()
            ->get();

        return view('student.dashboard', compact(
            'user', 'subjects', 'recentLessons',
            'upcomingQuizzes', 'announcements', 'timetable', 'marks'
        ));
    }

    public function lesson(Lesson $lesson)
    {
        $lesson->load('subject', 'teacher');
        return view('student.lesson', compact('lesson'));
    }
}
