<?php

namespace App\Http\Controllers\Guru;

use App\Http\Controllers\Controller;
use App\Models\Mengajar;
use App\Models\Siswa;
use App\Models\Tugas;
use App\Models\Leaderboard;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        $guru = Auth::guard('guru')->user();

        try {
            $totalKelas = Mengajar::where('id_guru', $guru->id_guru)
                ->distinct('id_kelas')->count('id_kelas');

            $totalMapel = Mengajar::where('id_guru', $guru->id_guru)
                ->distinct('id_mapel')->count('id_mapel');

            $kelasIds = Mengajar::where('id_guru', $guru->id_guru)
                ->pluck('id_kelas')->unique()->values()->toArray(); // fix: toArray()

            $totalSiswa = Siswa::whereIn('id_kelas', $kelasIds)->count();

            // ── Chart: Grouped Bar ──
            // Tampilkan semua kombinasi mapel-kelas meskipun belum ada pengumpulan
            $mengajars = Mengajar::with([
                'mapel',
                'kelas',
                'tugas.pengumpulanTugas' // relasi sudah ditambahkan di model
            ])->where('id_guru', $guru->id_guru)->get();

            $chartLabels    = [];
            $chartTepat     = [];
            $chartTerlambat = [];

            foreach ($mengajars as $m) {
                $namaMapel  = optional($m->mapel)->nama_mapel ?? 'Mapel';
                $namaKelas  = optional($m->kelas)->nama_kelas ?? 'Kelas';
                $labelPendek = (strlen($namaMapel) > 12
                    ? substr($namaMapel, 0, 12) . '…'
                    : $namaMapel) . ' · ' . $namaKelas;

                $tepat     = 0;
                $terlambat = 0;

                foreach ($m->tugas as $tugas) {
                    foreach ($tugas->pengumpulanTugas as $p) {
                        if ($p->status === 'dikumpulkan') $tepat++;
                        elseif ($p->status === 'terlambat') $terlambat++;
                    }
                }

                // Selalu push meskipun tepat=0 dan terlambat=0
                $chartLabels[]    = $labelPendek;
                $chartTepat[]     = $tepat;
                $chartTerlambat[] = $terlambat;
            }

            // ── Leaderboard ──
            $leaderboard = Leaderboard::with(['siswa', 'kelas'])
                ->whereIn('id_kelas', $kelasIds) // fix: sudah jadi array
                ->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::whereIn('id_kelas', $kelasIds)
                ->orderBy('total_exp', 'desc')->first();
            $semester    = $firstLb->semester    ?? '-';
            $tahunAjaran = $firstLb->tahun_ajaran ?? '-';

        } catch (\Exception $e) {
            $totalKelas     = 0;
            $totalMapel     = 0;
            $totalSiswa     = 0;
            $chartLabels    = [];
            $chartTepat     = [];
            $chartTerlambat = [];
            $leaderboard    = collect();
            $semester       = '-';
            $tahunAjaran    = '-';
        }

        return view('guru.dashboard', compact(
            'totalKelas', 'totalMapel', 'totalSiswa',
            'chartLabels', 'chartTepat', 'chartTerlambat',
            'leaderboard', 'semester', 'tahunAjaran'
        ));
    }
}