<?php

namespace App\Http\Controllers\Guru;

use App\Http\Controllers\Controller;
use App\Models\Nilai;
use App\Models\Kelas;
use App\Models\MataPelajaran;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Validation\Rule;

class NilaiController extends Controller
{
    public function index(Request $request): View
    {
        $selectedKelas = $request->query('kelas_id');
        $selectedMapel = $request->query('mata_pelajaran_id');

        $kelas = Kelas::orderBy('nama_kelas')->get();
        $mataPelajaran = MataPelajaran::orderBy('nama_mapel')->get();

        $siswaList = collect();
        $existingNilais = collect();
        $totalSiswa = 0;
        $averageNilai = 0;
        $maxNilai = 0;
        $minNilai = 0;

        if ($selectedKelas && $selectedMapel) {
            $kelasModel = Kelas::find($selectedKelas);
            $mapelModel = MataPelajaran::find($selectedMapel);

            if ($kelasModel && $mapelModel) {
                $namaKelas = $kelasModel->nama_kelas;

                // Get all students in this class
                $siswaList = User::where('role', 'siswa')
                    ->whereHas('siswaProfile', function ($query) use ($namaKelas) {
                        $query->where('kelas', $namaKelas);
                    })
                    ->with('siswaProfile')
                    ->orderBy('name')
                    ->get();

                // Get existing grades for this class and subject
                $existingNilais = Nilai::where('kelas_id', $selectedKelas)
                    ->where('mata_pelajaran_id', $selectedMapel)
                    ->get()
                    ->keyBy('siswa_id');

                // Statistics for this specific filtered selection
                $statsQuery = Nilai::where('kelas_id', $selectedKelas)
                    ->where('mata_pelajaran_id', $selectedMapel);

                $totalSiswa = (clone $statsQuery)->count();
                $averageNilai = (clone $statsQuery)->avg('nilai_akhir') ?? 0;
                $maxNilai = (clone $statsQuery)->max('nilai_akhir') ?? 0;
                $minNilai = (clone $statsQuery)->min('nilai_akhir') ?? 0;
            }
        }

        return view('guru.nilai', [
            'kelas' => $kelas,
            'mataPelajaran' => $mataPelajaran,
            'siswaList' => $siswaList,
            'existingNilais' => $existingNilais,
            'totalSiswa' => $totalSiswa,
            'averageNilai' => round($averageNilai, 2),
            'maxNilai' => round($maxNilai, 2),
            'minNilai' => round($minNilai, 2),
            'selectedKelas' => $selectedKelas,
            'selectedMapel' => $selectedMapel,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'siswa_id' => [
                'required',
                Rule::exists('users', 'id')->where('role', 'siswa'),
            ],
            'mata_pelajaran_id' => ['required', 'exists:mata_pelajaran,id'],
            'kelas_id' => ['required', 'exists:kelas,id'],
            'tugas' => ['required', 'integer', 'min:0', 'max:100'],
            'uts' => ['required', 'integer', 'min:0', 'max:100'],
            'uas' => ['required', 'integer', 'min:0', 'max:100'],
            'catatan' => ['nullable', 'string'],
        ]);

        $validated['guru_id'] = auth()->id();

        // Calculate Nilai Akhir
        $nilaiAkhir = ($validated['tugas'] + $validated['uts'] + $validated['uas']) / 3;
        $validated['nilai_akhir'] = $nilaiAkhir;

        // Calculate Grade
        $validated['grade'] = $this->calculateGrade($nilaiAkhir);

        Nilai::create($validated);

        return redirect()
            ->route('guru.nilai.index', [
                'kelas_id' => $request->input('kelas_id'),
                'mata_pelajaran_id' => $request->input('mata_pelajaran_id')
            ])
            ->with('success', 'Nilai siswa berhasil ditambahkan.');
    }

    public function update(Request $request, Nilai $nilai): RedirectResponse
    {
        $validated = $request->validate([
            'siswa_id' => [
                'required',
                Rule::exists('users', 'id')->where('role', 'siswa'),
            ],
            'mata_pelajaran_id' => ['required', 'exists:mata_pelajaran,id'],
            'kelas_id' => ['required', 'exists:kelas,id'],
            'tugas' => ['required', 'integer', 'min:0', 'max:100'],
            'uts' => ['required', 'integer', 'min:0', 'max:100'],
            'uas' => ['required', 'integer', 'min:0', 'max:100'],
            'catatan' => ['nullable', 'string'],
        ]);

        // Calculate Nilai Akhir
        $nilaiAkhir = ($validated['tugas'] + $validated['uts'] + $validated['uas']) / 3;
        $validated['nilai_akhir'] = $nilaiAkhir;

        // Calculate Grade
        $validated['grade'] = $this->calculateGrade($nilaiAkhir);

        $nilai->update($validated);

        return redirect()
            ->route('guru.nilai.index', [
                'kelas_id' => $request->input('kelas_id'),
                'mata_pelajaran_id' => $request->input('mata_pelajaran_id')
            ])
            ->with('success', 'Nilai siswa berhasil diperbarui.');
    }

    public function destroy(Nilai $nilai): RedirectResponse
    {
        $kelasId = $nilai->kelas_id;
        $mapelId = $nilai->mata_pelajaran_id;
        
        $nilai->delete();

        return redirect()
            ->route('guru.nilai.index', [
                'kelas_id' => $kelasId,
                'mata_pelajaran_id' => $mapelId
            ])
            ->with('success', 'Nilai siswa berhasil dihapus.');
    }

    private function calculateGrade(float $score): string
    {
        if ($score >= 90.0) {
            return 'A';
        } elseif ($score >= 80.0) {
            return 'B';
        } elseif ($score >= 70.0) {
            return 'C';
        } else {
            return 'D';
        }
    }
}
