<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

use App\Models\Tugas;
use App\Models\PengumpulanTugas;
use App\Models\Challenge;
use App\Models\PesertaChallenge;
use App\Models\Leaderboard;
use App\Models\Siswa;

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:siswa');
    }

    public function index()
    {
        /** @var \App\Models\Siswa $siswa */
        $siswa = Auth::guard('siswa')->user();

        // Tugas pending (belum dikumpulkan, belum lewat deadline)
        $sudahDikumpulkan = PengumpulanTugas::where('id_siswa', $siswa->id_siswa)
            ->pluck('id_tugas');

        $tugasRaw = Tugas::with(['mengajar.mapel'])
            ->whereNotIn('id_tugas', $sudahDikumpulkan)
            ->where('deadline', '>=', Carbon::now())
            ->whereHas('mengajar', function ($q) use ($siswa) {
                $q->where('id_kelas', $siswa->id_kelas);
            })
            ->orderBy('deadline', 'asc')
            ->take(5)
            ->get();

        $tugasList = [];
        foreach ($tugasRaw as $tugas) {
            $tgl = Carbon::parse($tugas->deadline)
                ->locale('id')
                ->isoFormat('dddd, D MMMM YYYY');

            $namaMapel = optional(optional($tugas->mengajar)->mapel)->nama_mapel ?? '-';

            $tugasList[$tgl][] = [
                'id_tugas' => $tugas->id_tugas,
                'jam'      => Carbon::parse($tugas->deadline)->format('H.i'),
                'nama'     => $tugas->judul_tugas,
                'mapel'    => 'Belum · ' . $namaMapel,
            ];
        }

        // Progress bar tugas (semua tugas dari guru untuk kelas ini)
        $tugasTotal = Tugas::whereHas('mengajar', function ($q) use ($siswa) {
                $q->where('id_kelas', $siswa->id_kelas);
            })
            ->where('deadline', '>=', Carbon::now())
            ->count();

        $tugasDikumpulkan = PengumpulanTugas::where('id_siswa', $siswa->id_siswa)
            ->whereIn('id_tugas', Tugas::whereHas('mengajar', function ($q) use ($siswa) {
                $q->where('id_kelas', $siswa->id_kelas);
            })->where('deadline', '>=', Carbon::now())->pluck('id_tugas'))
            ->count();

        // Mascot
        $startMinggu  = Carbon::now()->startOfWeek();
        $endMinggu    = Carbon::now()->endOfWeek();
        $tugasSelesai = PengumpulanTugas::where('id_siswa', $siswa->id_siswa)
            ->whereIn('status', ['dikumpulkan', 'terlambat'])
            ->whereBetween('tanggal_submit', [$startMinggu, $endMinggu])
            ->count();

        // Leaderboard
        $leaderboardRaw = Leaderboard::with('siswa')
            ->where('id_kelas', $siswa->id_kelas)
            ->orderBy('total_exp', 'desc')
            ->take(3)
            ->get();

        $leaderboard = $leaderboardRaw->map(function ($item, $index) {
            return [
                'rank' => $index + 1,
                'nama' => optional($item->siswa)->nama ?? '-',
                'exp'  => $item->total_exp,
            ];
        })->toArray();

        return view('siswa.dashboard', compact(
            'tugasList',
            'tugasTotal',
            'tugasDikumpulkan',
            'tugasSelesai',
            'leaderboard',
        ));
    }
}