<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PengerjaanUjian;
use App\Models\Ujian;
use App\Models\User;
use App\Models\Siswa;
use App\Models\TahunAjaran;
use Illuminate\Http\Request;

class MonitoringController extends Controller
{
    public function dashboard(Request $request)
    {
        $tahunAktif = TahunAjaran::where('is_aktif', true)->first();

        $stats = [
            'total_guru'       => User::where('role', 'guru')->count(),
            'total_siswa'      => User::where('role', 'siswa')->count(),
            'total_kelas'      => \App\Models\Kelas::when($tahunAktif, fn($q) => $q->where('tahun_ajaran_id', $tahunAktif->id))->count(),
            'ujian_aktif'      => Ujian::where('status', 'aktif')->count(),
            'ujian_selesai'    => Ujian::where('status', 'selesai')->count(),
            'sedang_ujian'     => PengerjaanUjian::where('status', 'sedang')->count(),
            'tahun_ajaran'     => $tahunAktif,
        ];

        // Ujian per jenis (chart)
        $ujianPerJenis = Ujian::when($tahunAktif, fn($q) => $q->where('tahun_ajaran_id', $tahunAktif->id))
            ->selectRaw('jenis, COUNT(*) as total')
            ->groupBy('jenis')
            ->get();

        // Aktivitas ujian 7 hari terakhir
        $aktivitas = PengerjaanUjian::selectRaw('DATE(updated_at) as tanggal, COUNT(*) as total')
            ->where('updated_at', '>=', now()->subDays(7))
            ->groupBy('tanggal')
            ->orderBy('tanggal')
            ->get();

        // Pengerjaan terbaru
        $pengerjaanTerbaru = PengerjaanUjian::with(['ujian.mataPelajaran', 'siswa.kelas'])
            ->orderByDesc('updated_at')
            ->limit(10)
            ->get();

        return response()->json([
            'success' => true,
            'data'    => [
                'stats'              => $stats,
                'ujian_per_jenis'    => $ujianPerJenis,
                'aktivitas'          => $aktivitas,
                'pengerjaan_terbaru' => $pengerjaanTerbaru,
            ],
        ]);
    }

    public function dashboardGuru(Request $request)
    {
        $guru = $request->user()->guru;

        if (!$guru) {
            return response()->json(['success' => false, 'message' => 'Profil guru tidak ditemukan.'], 404);
        }

        $guruMengajarIds = $guru->guruMengajar->pluck('id');

        $stats = [
            'total_mengajar' => $guru->guruMengajar->count(),
            'ujian_aktif'    => Ujian::whereIn('guru_mengajar_id', $guruMengajarIds)->where('status', 'aktif')->count(),
            'ujian_selesai'  => Ujian::whereIn('guru_mengajar_id', $guruMengajarIds)->where('status', 'selesai')->count(),
            'nilai_pending'  => \App\Models\NilaiUjian::whereHas('ujian', fn($q) => $q->whereIn('guru_mengajar_id', $guruMengajarIds))
                ->where('is_essay_filled', false)->count(),
        ];

        $ujianTerbaru = Ujian::whereIn('guru_mengajar_id', $guruMengajarIds)
            ->with(['mataPelajaran', 'kelas'])
            ->orderByDesc('tanggal_mulai')
            ->limit(5)
            ->get();

        return response()->json([
            'success' => true,
            'data'    => ['stats' => $stats, 'ujian_terbaru' => $ujianTerbaru],
        ]);
    }

    public function dashboardSiswa(Request $request)
    {
        $siswa = $request->user()->siswa;

        if (!$siswa) {
            return response()->json(['success' => false, 'message' => 'Profil siswa tidak ditemukan.'], 404);
        }

        $ujianAktif = Ujian::where('kelas_id', $siswa->kelas_id)
            ->where('status', 'aktif')
            ->with('mataPelajaran')
            ->get()
            ->map(function ($ujian) use ($siswa) {
                $ujian->pengerjaan = PengerjaanUjian::where('ujian_id', $ujian->id)
                    ->where('siswa_id', $siswa->id)
                    ->first();
                return $ujian;
            });

        $nilaiTerbaru = \App\Models\NilaiUjian::where('siswa_id', $siswa->id)
            ->with(['ujian.mataPelajaran'])
            ->whereNotNull('nilai_final')
            ->orderByDesc('updated_at')
            ->limit(5)
            ->get();

        $stats = [
            'ujian_diikuti' => PengerjaanUjian::where('siswa_id', $siswa->id)->count(),
            'ujian_selesai' => PengerjaanUjian::where('siswa_id', $siswa->id)->where('status', 'selesai')->count(),
            'nilai_keluar'  => \App\Models\NilaiUjian::where('siswa_id', $siswa->id)->whereNotNull('nilai_final')->count(),
        ];

        return response()->json([
            'success' => true,
            'data'    => [
                'stats'        => $stats,
                'ujian_aktif'  => $ujianAktif,
                'nilai_terbaru'=> $nilaiTerbaru,
                'siswa'        => $siswa->load('kelas'),
            ],
        ]);
    }
}
