<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use App\Models\Kelas;
use App\Models\Materi;
use App\Models\Tugas;
use App\Models\PengumpulanTugas;
use App\Models\Nilai;
use App\Models\JadwalPelajaran;
use App\Models\Ujian;
use App\Models\Absensi;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index(): View
    {
        $siswa = auth()->user();
        $siswaProfile = $siswa->siswaProfile;
        
        if (!$siswaProfile) {
            abort(403, 'Profil siswa Anda tidak ditemukan. Silakan hubungi admin.');
        }

        $siswaKelas = $siswaProfile->kelas;
        $kelasModel = Kelas::where('nama_kelas', $siswaKelas)->first();

        // Fallbacks
        $materiCount = 0;
        $tugasTertunda = 0;
        $averageScore = 0;
        $tugasSelesai = 0;
        $schedules = collect();
        $recentTugas = collect();
        $submissions = collect();

        if ($kelasModel) {
            // 1. Jumlah materi aktif untuk kelas siswa
            $materiCount = Materi::where('kelas_id', $kelasModel->id)
                ->where('status', 'aktif')
                ->count();

            // 2. Jumlah tugas aktif & tertunda untuk kelas siswa
            $totalTugas = Tugas::where('kelas_id', $kelasModel->id)
                ->where('status', '!=', 'Draft')
                ->count();

            $submittedTugas = PengumpulanTugas::where('siswa_id', $siswa->id)
                ->where('status', '!=', 'Belum Mengumpulkan')
                ->count();

            $tugasTertunda = max(0, $totalTugas - $submittedTugas);

            // 3. Rata-rata Nilai
            $averageScore = round(Nilai::where('siswa_id', $siswa->id)->avg('nilai_akhir') ?? 0);

            // 4. Tugas Selesai
            $tugasSelesai = $submittedTugas;

            // 5. Jadwal pelajaran hari ini
            $daysMap = [
                'Sunday' => 'Minggu',
                'Monday' => 'Senin',
                'Tuesday' => 'Selasa',
                'Wednesday' => 'Rabu',
                'Thursday' => 'Kamis',
                'Friday' => 'Jumat',
                'Saturday' => 'Sabtu',
            ];
            $todayDay = $daysMap[Carbon::now('Asia/Jakarta')->format('l')] ?? 'Senin';

            $schedules = JadwalPelajaran::where('kelas', $siswaKelas)
                ->where('hari', $todayDay)
                ->with(['mataPelajaran', 'guru'])
                ->orderBy('jam_mulai')
                ->get();

            // 6. Tugas & Kuis Terbaru
            $recentTugas = Tugas::where('kelas_id', $kelasModel->id)
                ->where('status', '!=', 'Draft')
                ->with('mataPelajaran')
                ->latest()
                ->take(5)
                ->get();

            // Fetch submissions map for recent tugas
            $submissions = PengumpulanTugas::where('siswa_id', $siswa->id)
                ->whereIn('tugas_id', $recentTugas->pluck('id'))
                ->get()
                ->keyBy('tugas_id');
        }

        return view('siswa.dashboard', [
            'siswaProfile' => $siswaProfile,
            'materiCount' => $materiCount,
            'tugasTertunda' => $tugasTertunda,
            'averageScore' => $averageScore,
            'tugasSelesai' => $tugasSelesai,
            'schedules' => $schedules,
            'recentTugas' => $recentTugas,
            'submissions' => $submissions,
            'siswaKelas' => $siswaKelas,
        ]);
    }
}
