<?php

namespace App\Http\Controllers\Guru;

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

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();

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

            // Chart: pengumpulan tugas per tugas (6 tugas terbaru)
            $idMengajars = Mengajar::where('id_guru', $guru->id_guru)->pluck('id_mengajar');

            $tugasList = Tugas::with(['mengajar.mapel', 'pengumpulanTugas'])
                ->whereIn('id_mengajar', $idMengajars)
                ->latest()->take(6)->get();

            $chartLabels = [];
            $chartSudah  = [];
            $chartBelum  = [];

            foreach ($tugasList as $tugas) {
                $namaMapel      = optional($tugas->mengajar->mapel)->nama_mapel ?? 'Mapel';
                $chartLabels[]  = strlen($namaMapel) > 14 ? substr($namaMapel, 0, 14) . '…' : $namaMapel;
                $sudah          = $tugas->pengumpulanTugas->count();
                $chartSudah[]   = $sudah;
                $chartBelum[]   = max(0, $totalSiswa - $sudah);
            }

        } catch (\Exception $e) {
            $totalKelas  = 0;
            $totalMapel  = 0;
            $totalSiswa  = 0;
            $chartLabels = [];
            $chartSudah  = [];
            $chartBelum  = [];
        }

        return view('guru.dashboard', compact(
            'totalKelas', 'totalMapel', 'totalSiswa',
            'chartLabels', 'chartSudah', 'chartBelum'
        ));
    }
}