<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use App\Models\Standard;
use App\Models\Subject;
use Illuminate\View\View;

class SubjectController extends Controller
{
    public function index(): View
    {
        $user = auth()->user();
        $standard = $this->resolveStandard($user->standard);

        return view('student.subjects.index', [
            'user' => $user,
            'standard' => $standard,
            'subjects' => $standard
                ? $standard->activeSubjects()->withCount(['chapters' => fn ($q) => $q->where('is_active', true)])->get()
                : collect(),
        ]);
    }

    public function show(Subject $subject): View
    {
        $user = auth()->user();
        $standard = $this->resolveStandard($user->standard);

        abort_unless(
            $standard && $subject->standard_id === $standard->id && $subject->is_active,
            404
        );

        return view('student.subjects.show', [
            'user' => $user,
            'standard' => $standard,
            'subject' => $subject,
            'chapters' => $subject->chapters()
                ->where('is_active', true)
                ->with([
                    'topics' => fn ($q) => $q->where('is_active', true)->orderBy('sort_order'),
                    'content:id,chapter_id,title',
                ])
                ->orderBy('sort_order')
                ->get(),
        ]);
    }

    private function resolveStandard(?string $slug): ?Standard
    {
        if (! $slug) {
            return null;
        }

        return Standard::where('slug', $slug)->where('is_active', true)->first();
    }
}
