<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\RiwayatRekomendasi;
use Illuminate\Http\Request;
use Exception;

class RiwayatController extends Controller
{
    /**
     * Mengambil semua data riwayat prediksi
     */
    public function index(Request $request)
    {
        try {
            $riwayat = RiwayatRekomendasi::with('user:id,name')
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($item) {
                    return [
                        'id' => $item->id,
                        'tanggal' => $item->created_at->format('d M Y'), 
                        'nama_siswa' => $item->user ? $item->user->name : 'Siswa Tidak Diketahui',
                        'hasil' => $item->hasil_rekomendasi_jurusan ?? 'Belum ada hasil'
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => $riwayat
            ], 200);

        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Mengambil data detail riwayat prediksi berdasarkan ID
     */
    public function show($id)
    {
        try {
            $detail = RiwayatRekomendasi::with('user:id,name,email')->findOrFail($id);

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $detail->id,
                    'tanggal' => $detail->created_at->format('d M Y H:i:s'),
                    'nama_siswa' => $detail->user ? $detail->user->name : 'Siswa Tidak Diketahui',
                    'email_siswa' => $detail->user ? $detail->user->email : '-',
                    'hasil_rekomendasi' => $detail->hasil_rekomendasi_jurusan ?? 'Belum ada hasil',
                    'detail_lengkap' => $detail
                ]
            ], 200);

        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Data detail tidak ditemukan: ' . $e->getMessage()
            ], 404);
        }
    }
}