<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class GradesController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);
        $userId = $request->user()?->id;
        $studentId = $userId && $schoolId
            ? DB::table('students')->where('school_id', $schoolId)->where('user_id', $userId)->value('id')
            : null;

        $grades = ($schoolId && $studentId)
            ? DB::table('grades')
                ->leftJoin('subjects', 'subjects.id', '=', 'grades.subject_id')
                ->leftJoin('exams', 'exams.id', '=', 'grades.exam_id')
                ->where('grades.school_id', $schoolId)
                ->where('grades.student_id', $studentId)
                ->where('grades.status', 'approved')
                ->select([
                    'grades.id',
                    'grades.score',
                    'grades.max_score',
                    'grades.description',
                    'grades.approved_at',
                    'subjects.name as subject_name',
                    'exams.title as exam_title',
                ])
                ->orderByDesc('grades.approved_at')
                ->limit(50)
                ->get()
                ->map(fn ($g): array => [
                    'id' => (int) $g->id,
                    'score' => (float) $g->score,
                    'maxScore' => (float) $g->max_score,
                    'subject' => $g->subject_name ?: '—',
                    'examTitle' => $g->exam_title,
                    'description' => $g->description,
                    'approvedAt' => $g->approved_at ? $this->jalaliDate($g->approved_at) : '—',
                ])
                ->values()
            : collect()->values();

        $average = $grades->isNotEmpty()
            ? round($grades->sum(fn ($g) => ($g['score'] / $g['maxScore']) * 20) / $grades->count(), 2)
            : null;

        return Inertia::render('Student/Grades', [
            'grades' => $grades,
            'average' => $average,
        ]);
    }
}
