<?php 

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Guru;
use App\Models\Siswa;
use App\Models\Kelas;
use App\Models\Mapel;
use App\Models\Challenge;
use App\Models\Leaderboard;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller {
    public function dashboard(){
        $totalGuru  = Guru::count();
        $totalSiswa = Siswa::count();
        $totalKelas = Kelas::count();
        $totalMapel = Mapel::count();
        $chartData  = Kelas::withCount('siswa')->get();
        $latestChallenges = Challenge::latest()->take(3)->get();

        // Leaderboard top 10
        $leaderboard = Leaderboard::with(['siswa', 'kelas'])
            ->orderBy('total_exp', 'desc')
            ->take(10)
            ->get()
            ->map(function ($lb, $i) {
                return [
                    'ranking'   => $i + 1,
                    'nama'      => optional($lb->siswa)->nama ?? '-',
                    'kelas'     => optional($lb->kelas)->nama_kelas ?? '-',
                    'total_exp' => $lb->total_exp,
                    'foto'      => optional($lb->siswa)->foto_profil,
                    'semester'  => $lb->semester,
                    'tahun'     => $lb->tahun_ajaran,
                ];
            });

        $firstLb     = Leaderboard::orderBy('total_exp', 'desc')->first();
        $semester    = $firstLb->semester     ?? '-';
        $tahunAjaran = $firstLb->tahun_ajaran ?? '-';

        return view('admin.dashboard', compact(
            'totalGuru','totalSiswa','totalKelas','totalMapel',
            'chartData','latestChallenges',
            'leaderboard','semester','tahunAjaran'
        ));
    }
}