<?php

namespace App\Http\Controllers\Guru;

use App\Http\Controllers\Controller;
use App\Models\Leaderboard;
use App\Models\Kelas;
use App\Models\Mengajar;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LeaderboardController extends Controller
{
    public function index(Request $request)
    {
        /** @var \App\Models\Guru $guru */
        $guru = Auth::guard('guru')->user();

        $now         = Carbon::now();
        $semester    = $request->input('semester', $now->month >= 7 ? '1' : '2');
        $tahunAjaran = $request->input('tahun_ajaran', $now->month >= 7
            ? $now->year . '/' . ($now->year + 1)
            : ($now->year - 1) . '/' . $now->year);

        // Kelas yang diajar guru ini
        $idKelasList = Mengajar::where('id_guru', $guru->id_guru)
            ->pluck('id_kelas')
            ->unique()
            ->toArray();

        $idKelas = $request->input('id_kelas', $idKelasList[0] ?? null);

        $kelasList = Kelas::whereIn('id_kelas', $idKelasList)
            ->orderBy('tingkat')->orderBy('nama_kelas')
            ->get();

        $leaderboard = collect();

        if ($idKelas) {
            $leaderboard = Leaderboard::with(['siswa', 'kelas'])
                ->where('id_kelas', $idKelas)
                ->where('semester', $semester)
                ->where('tahun_ajaran', $tahunAjaran)
                ->orderBy('total_exp', 'desc')
                ->get()
                ->map(function ($item, $i) {
                    return [
                        'ranking'    => $i + 1,
                        'nama'       => optional($item->siswa)->nama ?? '-',
                        'nisn'       => optional($item->siswa)->nisn ?? '-',
                        'nama_kelas' => optional($item->kelas)->nama_kelas ?? '-',
                        'exp'        => $item->total_exp,
                    ];
                });
        }

        $tahunList = [];
        for ($y = $now->year; $y >= $now->year - 4; $y--) {
            $tahunList[] = $y . '/' . ($y + 1);
        }

        return view('guru.leaderboard.index', compact(
            'leaderboard', 'kelasList', 'semester', 'tahunAjaran', 'idKelas', 'tahunList'
        ));
    }
}