<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Prestasi;
use Illuminate\Http\Request;

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

        $prestasis = Prestasi::with(['santri', 'kelas'])
            ->where('user_id', $user->id)
            ->latest()
            ->get();

        return response()->json([
            'status' => true,
            'message' => 'Data prestasi berhasil diambil',
            'authenticated_user_id' => $user->id,
            'user_prestasi_count' => $prestasis->count(),
            'data' => $prestasis->map(function ($item) {
                return [
                    'id' => $item->id,
                    'user_id' => $item->user_id,
                    'santri_id' => $item->santri_id,
                    'kelas_id' => $item->kelas_id,
                    'nama_prestasi' => $item->nama_prestasi,
                    'jenis_prestasi' => $item->jenis_prestasi,
                    'tingkat' => $item->tingkat,
                    'peringkat' => $item->peringkat,
                    'tanggal_prestasi' => $item->tanggal_prestasi,
                    'deskripsi' => $item->deskripsi,
                    'sertifikat_url' => $item->sertifikat ? asset('storage/' . $item->sertifikat) : null,
                    'created_at' => $item->created_at->toDateTimeString(),
                    'updated_at' => $item->updated_at->toDateTimeString(),
                    'santri' => $item->santri ? [
                        'id' => $item->santri->id,
                        'nama' => $item->santri->nama,
                    ] : null,
                    'kelas' => $item->kelas ? [
                        'id' => $item->kelas->id,
                        'nama_kelas' => $item->kelas->nama_kelas,
                    ] : null,
                ];
            }),
        ]);
    }
}
