<?php

namespace App\Controllers;

use Core\Database;
use PDO;

class PegawaiViewNilaiKelasController
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }

    public function index()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id_dmk'], $_POST['tahun_akademik'])) {
            $id_dmk = $_POST['id_dmk'];
            $tahun_akademik = $_POST['tahun_akademik'];

            // 🟡 Ambil info Mata Kuliah & Kelas
            $stmt = $this->db->prepare("
                SELECT d.kode_mk, d.kode_kelas, m.nama_mk, m.sks
                FROM tb_dosen_mk d
                JOIN tb_mk m ON m.kode_mk = d.kode_mk
                WHERE d.id_dmk = :id_dmk
                LIMIT 1
            ");
            $stmt->execute(['id_dmk' => $id_dmk]);
            $dmkInfo = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$dmkInfo) {
                echo "<script>alert('Data mata kuliah tidak ditemukan');history.back();</script>";
                exit;
            }

            $kode_mk = $dmkInfo['kode_mk'];
            $kode_kelas = $dmkInfo['kode_kelas'];
            $nama_mk = $dmkInfo['nama_mk'];
            $sks = $dmkInfo['sks'];

            // 🟡 Ambil daftar mahasiswa berdasarkan kelas & tahun akademik
            $stmt = $this->db->prepare("
                SELECT k.nim, m.nama
                FROM tb_kelas k
                JOIN tb_mahasiswa m ON m.nim = k.nim
                WHERE k.kode_kelas = :kode_kelas
                  AND k.tahun_akademik = :tahun_akademik
                ORDER BY m.nama ASC
            ");
            $stmt->execute([
                'kode_kelas' => $kode_kelas,
                'tahun_akademik' => $tahun_akademik
            ]);
            $mahasiswaList = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // 🟡 Ambil nilai tiap komponen per mahasiswa
            $dataMahasiswa = [];
            foreach ($mahasiswaList as $mhs) {
                $nim = $mhs['nim'];

                $nilai_uts = $this->ambilNilaiUjian($nim, $kode_mk, $tahun_akademik, 1);
                $nilai_uas = $this->ambilNilaiUjian($nim, $kode_mk, $tahun_akademik, 2);
                $nilai_tugas = $this->ambilNilaiTugas($nim, $kode_mk, $tahun_akademik);
                $nilai_absensi = $this->ambilNilaiPresensi($nim, $kode_mk, $kode_kelas, $tahun_akademik);

                // Bobot: UTS 30% | UAS 30% | Tugas 20% | Absensi 20%
                $nilai_akhir = round(
                    ($nilai_uts * 0.30) +
                    ($nilai_uas * 0.30) +
                    ($nilai_tugas * 0.20) +
                    ($nilai_absensi * 0.20)
                );

                $dataMahasiswa[] = [
                    'nim' => $nim,
                    'nama' => $mhs['nama'],
                    'nilai_uts' => $nilai_uts,
                    'nilai_uas' => $nilai_uas,
                    'nilai_tugas' => $nilai_tugas,
                    'nilai_absensi' => $nilai_absensi,
                    'nilai_akhir' => $nilai_akhir
                ];
            }

            $infoMK = [
                'kode_mk' => $kode_mk,
                'kode_kelas' => $kode_kelas,
                'nama_mk' => $nama_mk,
                'sks' => $sks
            ];

            require __DIR__ . '/../Views/pegawai/view_nilai_kelas.php';

        } else {
            // 🟡 Tampilkan form jika belum submit
            $tahunAkademikList = $this->db->query("
                SELECT DISTINCT tahun_akademik FROM tb_dosen_mk ORDER BY tahun_akademik DESC
            ")->fetchAll(PDO::FETCH_COLUMN);

            require __DIR__ . '/../Views/pegawai/form_nilai.php';
        }
    }

    private function ambilNilaiUjian($nim, $kode_mk, $tahun_akademik, $jenis)
    {
        $stmt = $this->db->prepare("
            SELECT nilai FROM tb_mk_dijawab
            WHERE nim = :nim 
              AND kode_mk = :kode_mk 
              AND tahun_akademik = :tahun_akademik 
              AND id_jenis_s = :jenis
            LIMIT 1
        ");
        $stmt->execute([
            'nim' => $nim,
            'kode_mk' => $kode_mk,
            'tahun_akademik' => $tahun_akademik,
            'jenis' => $jenis
        ]);
        return (float) $stmt->fetchColumn() ?: 0;
    }

    private function ambilNilaiTugas($nim, $kode_mk, $tahun_akademik)
    {
        $stmt = $this->db->prepare("
            SELECT nilai FROM tb_nilai_tugas
            WHERE nim = :nim 
              AND kode_mk = :kode_mk 
              AND tahun_akademik = :tahun_akademik
            LIMIT 1
        ");
        $stmt->execute([
            'nim' => $nim,
            'kode_mk' => $kode_mk,
            'tahun_akademik' => $tahun_akademik
        ]);
        return (float) $stmt->fetchColumn() ?: 0;
    }

    private function ambilNilaiPresensi($nim, $kode_mk, $kode_kelas, $tahun_akademik)
    {
        // Cari id_krs berdasarkan nim, kode_mk, tahun akademik
        $stmt = $this->db->prepare("
            SELECT id_krs 
            FROM tb_krs 
            WHERE nim = :nim 
              AND kode_mk = :kode_mk 
              AND tahun_akademik = :tahun_akademik
            LIMIT 1
        ");
        $stmt->execute([
            'nim' => $nim,
            'kode_mk' => $kode_mk,
            'tahun_akademik' => $tahun_akademik
        ]);
        $id_krs = $stmt->fetchColumn();

        if (!$id_krs) {
            return 0;
        }

        // Hitung rata-rata nilai_absensi berdasarkan id_krs
        $stmt2 = $this->db->prepare("
            SELECT SUM(nilai_absensi) 
            FROM tb_absensi 
            WHERE id_krs = :id_krs 
              AND kode_mk = :kode_mk 
              AND kode_kelas = :kode_kelas 
              AND tahun_akademik = :tahun_akademik
        ");
        $stmt2->execute([
            'id_krs' => $id_krs,
            'kode_mk' => $kode_mk,
            'kode_kelas' => $kode_kelas,
            'tahun_akademik' => $tahun_akademik
        ]);

        return (float) $stmt2->fetchColumn() ?: 0;
    }

public function updateKHS()
{
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $jumMhs = $_POST['n'] ?? 0;
        $kode_mk = $_POST['kode_mk'] ?? '';
        $sks = (int)($_POST['sks'] ?? 0);
        $tahun_akademik = $_POST['tahun_akademik'] ?? '';

        $inputSuccessful = false;

        for ($i = 1; $i <= $jumMhs; $i++) {
            $nim = $_POST['nim' . $i] ?? null;
            if (!$nim) continue;

            $nilai_uts = $_POST['nilai_uts' . $i] ?? 0;
            $nilai_uas = $_POST['nilai_uas' . $i] ?? 0;
            $nilai_tugas = $_POST['nilai_tugas' . $i] ?? 0;
            $nilai_absensi = $_POST['nilai_absensi' . $i] ?? 0;

            // Hitung nilai akhir
            $nilai_akhir = round(($nilai_uts * 0.30) + ($nilai_uas * 0.30) + ($nilai_tugas * 0.20) + ($nilai_absensi * 0.20));

            // Konversi mutu
            if ($nilai_akhir > 84) {
                $mutu = "A"; $bobot = 4;
            } elseif ($nilai_akhir > 74) {
                $mutu = "B"; $bobot = 3;
            } elseif ($nilai_akhir > 64) {
                $mutu = "C"; $bobot = 2;
            } elseif ($nilai_akhir > 59) {
                $mutu = "D"; $bobot = 1;
            } else {
                $mutu = "E"; $bobot = 0;
            }

            $s_x_b = $sks * $bobot;

            // Cek apakah sudah ada record
            $stmt = $this->db->prepare("SELECT COUNT(*) AS jml FROM tb_khs WHERE nim = ? AND kode_mk = ?");
            $stmt->execute([$nim, $kode_mk]);
            $cek = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($cek && $cek['jml'] > 0) {
                // Update
                $stmt = $this->db->prepare("
                    UPDATE tb_khs 
                    SET nilai = ?, mutu = ?, bobot = ?, sks_x_bobot = ? 
                    WHERE nim = ? AND kode_mk = ?
                ");
                $stmt->execute([$nilai_akhir, $mutu, $bobot, $s_x_b, $nim, $kode_mk]);
            } else {
                // Insert
                $stmt = $this->db->prepare("
                    INSERT INTO tb_khs (nim, kode_mk, smt, nilai, mutu, bobot, sks_x_bobot, accept) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, 0)
                ");
                $stmt->execute([$nim, $kode_mk, $tahun_akademik, $nilai_akhir, $mutu, $bobot, $s_x_b]);
            }

            $inputSuccessful = true;
        }

        if ($inputSuccessful) {
            echo "<script>alert('Nilai KHS berhasil diperbarui'); window.location.href='/dashboard/pegawai-view-nilaikelas?id_dmk={$_POST['id_dmk']}&tahun_akademik={$tahun_akademik}';</script>";
        } else {
            echo "<script>alert('Tidak ada data yang diperbarui'); window.location.href='/dashboard/pegawai-view-nilaikelas?id_dmk={$_POST['id_dmk']}&tahun_akademik={$tahun_akademik}';</script>";
        }
        exit;
    }
}

    
}
