<?php

namespace App\Http\Controllers;

use App\Models\Grado;
use Illuminate\Http\Request;

class GradeController extends Controller
{
    public function index()
    {
        return response()->json(
            Grado::with('estudiante')->paginate(10),
            200
        );
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'estudiante_id' => 'required|exists:estudiantes,id',
            'subject'       => 'required|string|max:100',
            'score'         => 'required|numeric|min:0|max:100',
            'date_recorded' => 'required|date',
            'comments'      => 'nullable|string',
        ]);

        $grade = Grado::create($validated);

        return response()->json([
            'message' => 'Nota registrada exitosamente.',
            'grade'   => $grade
        ], 201);
    }

    public function show(Grado $grade)
    {
        $grade->load('estudiante');
        return response()->json($grade, 200);
    }

    public function update(Request $request, Grado $grade)
    {
        $validated = $request->validate([
            'subject'       => 'string|max:100',
            'score'         => 'numeric|min:0|max:100',
            'date_recorded' => 'date',
            'comments'      => 'nullable|string',
        ]);

        $grade->update($validated);

        return response()->json([
            'message' => 'Nota actualizada correctamente.',
            'grade'   => $grade
        ], 200);
    }

    public function destroy(Grado $grade)
    {
        $grade->delete();

        return response()->json([
            'message' => 'Nota eliminada correctamente.'
        ], 200);
    }
}
