<?php

namespace App\Http\Controllers;

use App\Models\P4TimPenguji;
use App\Models\Penilaian;
use App\Models\PenilaianDetail;
use App\Models\KriteriaPenilaian;
use App\Models\Mahasiswa;
use App\Models\Dosen;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class PenilaianController extends Controller
{
    public function index()
    {
        // Get all students who have a defense scheduled (P4)
        $p4_list = P4TimPenguji::all();
        
        $mahasiswa_ujian = [];
        foreach ($p4_list as $p4) {
            // Check average final score
            $penilaians = Penilaian::where('nim_mahasiswa', $p4->nim_mahasiswa)->get();
            $jumlah_penguji = 0;
            for ($i = 1; $i <= 5; $i++) {
                $nipField = "nip_penguji$i";
                if (!empty($p4->$nipField)) {
                    $jumlah_penguji++;
                }
            }
            
            $total_nilai = $penilaians->sum('nilai_total');
            $rata_rata = $jumlah_penguji > 0 && $penilaians->count() > 0 ? $total_nilai / $jumlah_penguji : 0;
            
            $mahasiswa_ujian[] = (object)[
                'nim_mahasiswa' => $p4->nim_mahasiswa,
                'nama_mahasiswa' => $p4->nama_mahasiswa,
                'judul_skripsi' => $p4->judul_skripsi,
                'jumlah_penguji' => $jumlah_penguji,
                'jumlah_dinilai' => $penilaians->count(),
                'rata_rata' => $rata_rata,
                'p4' => $p4
            ];
        }

        return view('penilaian.index', compact('mahasiswa_ujian'));
    }

    public function detail($nim)
    {
        $p4 = P4TimPenguji::where('nim_mahasiswa', $nim)->firstOrFail();
        
        $pengujis = [];
        for ($i = 1; $i <= 5; $i++) {
            $nipField = "nip_penguji$i";
            $namaField = "nama_penguji$i";
            
            if (!empty($p4->$nipField)) {
                $penilaian = Penilaian::where('nim_mahasiswa', $nim)
                                      ->where('nip_penguji', $p4->$nipField)
                                      ->where('penguji_ke', $i)
                                      ->first();
                $pengujis[] = (object)[
                    'penguji_ke' => $i,
                    'nip' => $p4->$nipField,
                    'nama' => $p4->$namaField,
                    'penilaian' => $penilaian
                ];
            }
        }

        return view('penilaian.detail', compact('p4', 'pengujis'));
    }

    public function input($nim, $penguji_ke)
    {
        $p4 = P4TimPenguji::where('nim_mahasiswa', $nim)->firstOrFail();
        $nipField = "nip_penguji$penguji_ke";
        $namaField = "nama_penguji$penguji_ke";
        
        $penguji = (object)[
            'nip' => $p4->$nipField,
            'nama' => $p4->$namaField,
            'penguji_ke' => $penguji_ke
        ];

        $kriteria = KriteriaPenilaian::all();
        $penilaian = Penilaian::with('detail')->where('nim_mahasiswa', $nim)
                              ->where('nip_penguji', $penguji->nip)
                              ->where('penguji_ke', $penguji_ke)
                              ->first();

        return view('penilaian.input', compact('p4', 'penguji', 'kriteria', 'penilaian'));
    }

    public function store(Request $request, $nim, $penguji_ke)
    {
        $p4 = P4TimPenguji::where('nim_mahasiswa', $nim)->firstOrFail();
        $nipField = "nip_penguji$penguji_ke";
        
        $request->validate([
            'nilai.*' => 'required|numeric|min:0|max:100',
            'catatan' => 'nullable|string'
        ]);

        $kriterias = KriteriaPenilaian::all();
        $total_bobot = $kriterias->sum('bobot');
        
        if ($total_bobot == 0) {
            return back()->with('error', 'Total bobot kriteria adalah 0. Silakan atur Bobot Kriteria terlebih dahulu.');
        }

        $sum_bobot_nilai = 0;
        
        $penilaian = Penilaian::updateOrCreate(
            ['nim_mahasiswa' => $nim, 'nip_penguji' => $p4->$nipField, 'penguji_ke' => $penguji_ke],
            ['catatan' => $request->catatan, 'nilai_total' => 0] // We will update nilai_total later
        );

        foreach ($request->nilai as $kriteria_id => $nilai_angka) {
            $kr = $kriterias->where('id', $kriteria_id)->first();
            $hasil_bobot = $kr ? ($kr->bobot * $nilai_angka) : 0;
            $sum_bobot_nilai += $hasil_bobot;

            PenilaianDetail::updateOrCreate(
                ['penilaian_id' => $penilaian->id, 'kriteria_id' => $kriteria_id],
                ['nilai_angka' => $nilai_angka, 'hasil_bobot' => $hasil_bobot]
            );
        }

        $nilai_akhir = $sum_bobot_nilai / $total_bobot;
        $penilaian->update(['nilai_total' => $nilai_akhir]);

        return redirect()->route('penilaian.detail', $nim)->with('success', 'Nilai berhasil disimpan.');
    }

    public function cetak_form($nim, $penguji_ke)
    {
        $p4 = P4TimPenguji::where('nim_mahasiswa', $nim)->firstOrFail();
        $nipField = "nip_penguji$penguji_ke";
        $namaField = "nama_penguji$penguji_ke";
        
        $penguji = (object)[
            'nip' => $p4->$nipField,
            'nama' => $p4->$namaField,
            'penguji_ke' => $penguji_ke
        ];

        $kriteria = KriteriaPenilaian::all();
        $penilaian = Penilaian::with('detail')->where('nim_mahasiswa', $nim)
                              ->where('nip_penguji', $penguji->nip)
                              ->where('penguji_ke', $penguji_ke)
                              ->first();

        // Convert Nilai Huruf
        $huruf = '-';
        if($penilaian) {
            $total = $penilaian->nilai_total;
            if($total >= 80) $huruf = 'A';
            elseif($total >= 70) $huruf = 'B';
            elseif($total >= 60) $huruf = 'C';
            elseif($total >= 50) $huruf = 'D';
            else $huruf = 'E';
        }

        $pdf = Pdf::loadView('penilaian.pdf_form', compact('p4', 'penguji', 'kriteria', 'penilaian', 'huruf'));
        return $pdf->stream('Form_Penilaian_' . $nim . '_Penguji' . $penguji_ke . '.pdf');
    }

    public function cetak_rekap($nim)
    {
        $p4 = P4TimPenguji::where('nim_mahasiswa', $nim)->firstOrFail();
        
        $pengujis = [];
        $total_nilai = 0;
        $jumlah_penguji = 0;
        
        for ($i = 1; $i <= 5; $i++) {
            $nipField = "nip_penguji$i";
            $namaField = "nama_penguji$i";
            
            if (!empty($p4->$nipField)) {
                $penilaian = Penilaian::where('nim_mahasiswa', $nim)
                                      ->where('nip_penguji', $p4->$nipField)
                                      ->where('penguji_ke', $i)
                                      ->first();
                $pengujis[] = (object)[
                    'penguji_ke' => $i,
                    'nip' => $p4->$nipField,
                    'nama' => $p4->$namaField,
                    'penilaian' => $penilaian
                ];
                
                if ($penilaian) {
                    $total_nilai += $penilaian->nilai_total;
                }
                $jumlah_penguji++;
            }
        }
        
        $rata_rata = $jumlah_penguji > 0 ? $total_nilai / $jumlah_penguji : 0;
        
        $huruf = 'E';
        if($rata_rata >= 80) $huruf = 'A';
        elseif($rata_rata >= 70) $huruf = 'B';
        elseif($rata_rata >= 60) $huruf = 'C';
        elseif($rata_rata >= 50) $huruf = 'D';

        $pdf = Pdf::loadView('penilaian.pdf_rekap', compact('p4', 'pengujis', 'jumlah_penguji', 'total_nilai', 'rata_rata', 'huruf'));
        return $pdf->stream('Rekap_Nilai_' . $nim . '.pdf');
    }
}
