<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Course;
use Illuminate\View\View;

class CourseController extends Controller
{
    public function index(): View
    {
        $courses = Course::where('is_active', true)
            ->withCount([
                'materials',
                'pastQuestions',
                'questions',
                'exams',
            ])
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate(12);

        return view('user.courses.index', compact('courses'));
    }

    public function show(Course $course): View
    {
        abort_unless($course->is_active, 404);

        $course->load([
            'materials' => function ($query) {
                $query->where('is_active', true)
                    ->latest();
            },
            'pastQuestions' => function ($query) {
                $query->where('is_active', true)
                    ->withCount('questions')
                    ->orderByDesc('year')
                    ->orderBy('batch');
            },
            'exams' => function ($query) {
                $query->where('is_active', true)
                    ->latest();
            },
        ]);

        return view('user.courses.show', compact('course'));
    }
}