<?php

namespace App\Http\Controllers\StudentPortal;

use App\Http\Controllers\Controller;
use App\Http\Controllers\StudentPortal\Concerns\ResolvesStudent;
use App\Models\Exam;
use App\Services\ResultService;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ResultController extends Controller
{
    use ResolvesStudent;

    public function __construct(private ResultService $results)
    {
    }

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

        $exams = $student->class_id
            ? Exam::where('branch_id', $student->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) {
            $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('student.results', compact('student', 'exams', 'exam', 'result', 'position'));
    }
}
