<?php

namespace App\Http\Controllers\Api\Student;

use App\Http\Controllers\Controller;
use App\Models\RiwayatRekomendasi;
use Illuminate\Support\Facades\Auth;
use Exception;

class DashboardStudentController extends Controller
{
    public function index()
    {
        try {
            $user = Auth::user();
            
            if (!$user) {
                return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);
            }

            $totalAktivitas = RiwayatRekomendasi::where('user_id', $user->id)->count();

            $rekomendasiTerakhir = RiwayatRekomendasi::where('user_id', $user->id)
                ->latest()
                ->first();

            $aktivitasTerbaru = RiwayatRekomendasi::where('user_id', $user->id)
                ->latest()
                ->take(5)
                ->get()
                ->map(function ($item) {
                    return [
                        'id' => $item->id,
                        'jurusan' => $item->hasil_rekomendasi_jurusan,
                        'tanggal' => $item->created_at->diffForHumans(),
                    ];
                });

            $trenNilai = RiwayatRekomendasi::where('user_id', $user->id)
                ->orderBy('created_at', 'asc')
                ->get()
                ->map(function ($item, $index) {
                    $mapel = [
                        'agama', 'pkn', 'bahasa_indonesia', 'bahasa_inggris', 'matematika', 
                        'fisika', 'kimia', 'biologi', 'sejarah', 'geografi', 
                        'ekonomi_mapel', 'sosiologi', 'seni_budaya', 'pjok', 'informatika'
                    ];

                    $totalNilai = 0;
                    foreach ($mapel as $m) {
                        $totalNilai += (float) $item->$m;
                    }
                    
                    $rataRata = $totalNilai / count($mapel);

                    return [
                        'label' => 'Tes ' . ($index + 1),
                        'nilai' => round($rataRata, 2)
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => [
                    'total_aktivitas' => $totalAktivitas,
                    'rekomendasi_terakhir' => $rekomendasiTerakhir ? $rekomendasiTerakhir->hasil_rekomendasi_jurusan : 'Belum Ada Data',
                    'aktivitas_terbaru' => $aktivitasTerbaru,
                    'tren_nilai' => $trenNilai
                ]
            ]);

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