<?php

namespace App\Http\Controllers\ParentPortal;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ParentPortal\Concerns\ResolvesFamily;
use App\Models\Exam;
use App\Models\Student;
use App\Services\ResultService;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ResultController extends Controller
{
    use ResolvesFamily;

    public function __construct(private ResultService $results)
    {
    }

    public function index(Request $request): View
    {
        $family = $this->family();
        $children = $family->students;

        $studentId = $request->integer('student_id') ?: $children->first()?->id;
        $student = $studentId ? Student::find($studentId) : null;
        if ($student) {
            $this->authorizeChild($student);
        }

        // Only published exams that have papers for the child's class.
        $exams = $student
            ? Exam::where('branch_id', $family->branch_id)->where('is_published', true)
                ->whereHas('papers', fn ($q) => $q->where('class_id', $student->class_id))
                ->latest()->get()
            : collect();

        $examId = $request->integer('exam_id') ?: $exams->first()?->id;
        $exam = $examId ? $exams->firstWhere('id', $examId) : null;

        $result = null;
        $position = null;
        if ($exam && $student) {
            $result = $this->results->studentResult($exam, $student);
            $position = $this->results->classResults($exam, $student->class_id)
                ->firstWhere(fn ($r) => $r['student']->id === $student->id)['position'] ?? null;
        }

        return view('parent.results', compact('children', 'student', 'exams', 'exam', 'result', 'position'));
    }
}
