<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\NilaiSantri;
use Illuminate\Http\Request;
use App\Notifications\NilaiBaruNotification;

class NilaiSantriController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $santri = $user->santri;

        if (!$santri) {
            return response()->json([
                'success' => false,
                'message' => 'Data santri tidak ditemukan',
                'data' => []
            ]);
        }

        $nilai = NilaiSantri::with(['mapel', 'semester']) // eager load relasi
            ->where('santri_id', $santri->id)
            ->orderBy('mapel_id')
            ->orderByDesc('tanggal')
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'santri_id' => $item->santri_id,
                    'kelas_id' => $item->kelas_id,
                    'mapel_id' => $item->mapel_id,
                    'mapel' => $item->mapel->nama_mapel ?? '-',
                    'semester_id' => $item->semester_id,
                    'semester' => $item->semester->semester . ' - ' . $item->semester->tahun_ajaran,
                    'tanggal' => $item->tanggal,
                    'jenis_nilai' => $item->jenis_nilai,
                    'nilai' => $item->nilai,
                    'keterangan' => $item->keterangan,
                    'created_at' => $item->created_at,
                    'updated_at' => $item->updated_at,
                ];
            });

        return response()->json([
            'success' => true,
            'message' => 'Data nilai berhasil diambil',
            'data' => $nilai
        ]);
    }
}