<?php

namespace App\Http\Controllers\ParentPortal;

use App\Http\Controllers\Admin\PageController;
use App\Http\Controllers\ParentPortal\Concerns\ResolvesParentScope;
use App\Models\Quiz;
use App\Models\QuizAttempt;
use Illuminate\View\View;

class QuizController extends PageController
{
    use ResolvesParentScope;

    public function index(): View
    {
        $activeChild = $this->activeStudent();
        abort_unless($activeChild, 403);

        $classIds = $activeChild->classes()->pluck('classes.id');

        $quizzes = Quiz::query()
            ->with(['subject', 'schoolClass'])
            ->whereIn('class_id', $classIds)
            ->where('status', 'published')
            ->latest('starts_at')
            ->paginate(20);

        $attempts = QuizAttempt::query()
            ->where('student_id', $activeChild->id)
            ->where('status', 'submitted')
            ->get()
            ->keyBy('quiz_id');

        return $this->page('parent.quizzes.index', [
            'crumbTitle' => 'Quizzes',
            'crumbSub' => $activeChild->full_name,
            'quizzes' => $quizzes,
            'attempts' => $attempts,
            'students' => $this->guardianStudents(),
            'activeChild' => $activeChild,
        ]);
    }
}
