<?php
namespace App\Controllers;

use Core\Database;
use PDO;

class DosenViewNilaiKelasController
{
    private $db;

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

public function index()
{
    $niy = $_SESSION['user']['niy'] ?? null;
    if (!$niy) {
        header("Location: /login");
        exit();
    }

    $dataMahasiswa = [];
    $infoMK = null;
    $tahun_akademik = null;

    // Ambil tahun akademik aktif
    $ta = $this->db->query("SELECT tahun_akademik FROM tb_akademik WHERE status = 'Aktif' LIMIT 1");
    $tahun_akademik = $ta->fetchColumn();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['simpan'])) {
            // === HANDLE SIMPAN DATA NILAI ===
            $jumMhs = $_POST['n'] ?? 0;
            $kode_mk = $_POST['kode_mk'] ?? '';
            $sks = $_POST['sks'] ?? 0;
            $inputSuccessful = false;

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

                $nilai_tugas = $_POST['nilai_tugas' . $i] ?? 0;
                $nilai_akhir = $_POST['nilai_akhir' . $i] ?? 0;

                // 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;

                // Simpan/update nilai_tugas
                $cekTugas = $this->db->prepare("SELECT COUNT(*) FROM tb_nilai_tugas WHERE nim = ? AND kode_mk = ? AND tahun_akademik = ?");
                $cekTugas->execute([$nim, $kode_mk, $tahun_akademik]);

                if ($cekTugas->fetchColumn() > 0) {
                    $stmtTugas = $this->db->prepare("UPDATE tb_nilai_tugas SET nilai = ? WHERE nim = ? AND kode_mk = ? AND tahun_akademik = ?");
                    $stmtTugas->execute([$nilai_tugas, $nim, $kode_mk, $tahun_akademik]);
                } else {
                    $stmtTugas = $this->db->prepare("INSERT INTO tb_nilai_tugas (id_nilai_tugas, nim, kode_mk, nilai, tahun_akademik) VALUES (NULL, ?, ?, ?, ?)");
                    $stmtTugas->execute([$nim, $kode_mk, $nilai_tugas, $tahun_akademik]);
                }

                // Update KHS
                $stmtKHS = $this->db->prepare("UPDATE tb_khs SET nilai = ?, mutu = ?, bobot = ?, sks_x_bobot = ? WHERE nim = ? AND kode_mk = ?");
                $stmtKHS->execute([$nilai_akhir, $mutu, $bobot, $s_x_b, $nim, $kode_mk]);

                $inputSuccessful = true;
            }

            if ($inputSuccessful) {
                echo "<script>alert('Data berhasil disimpan.'); window.location.href = '/dashboard/dosen-input-nilai';</script>";
            } else {
                echo "<script>alert('Tidak ada data yang berhasil disimpan.'); window.location.href = '/dashboard/dosen-input-nilai';</script>";
            }
            exit;
        }

        // === HANDLE VIEW DATA ===
        if (isset($_POST['id_dmk'])) {
            $id_dmk = $_POST['id_dmk'];

            $stmt = $this->db->prepare("
                SELECT dm.kode_mk, dm.kode_kelas, mk.sks 
                FROM tb_dosen_mk dm 
                INNER JOIN tb_mk mk ON dm.kode_mk = mk.kode_mk 
                WHERE dm.id_dmk = :id_dmk
            ");
            $stmt->execute([':id_dmk' => $id_dmk]);
            $infoMK = $stmt->fetch(PDO::FETCH_ASSOC);

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

            $kode_mk = $infoMK['kode_mk'];
            $kode_kelas = $infoMK['kode_kelas'];

            $sql = $this->db->prepare("
                SELECT DISTINCT mhs.nim, mhs.nama,
                    (SELECT nilai FROM tb_mk_dijawab WHERE nim = mhs.nim AND kode_mk = :kode_mk AND id_jenis_s = 1 AND tahun_akademik = :tahun_akademik) AS nilai_uts,
                    (SELECT nilai FROM tb_mk_dijawab WHERE nim = mhs.nim AND kode_mk = :kode_mk AND id_jenis_s = 2 AND tahun_akademik = :tahun_akademik) AS nilai_uas,
                    (SELECT nilai FROM tb_nilai_tugas WHERE nim = mhs.nim AND kode_mk = :kode_mk AND tahun_akademik = :tahun_akademik) AS nilai_tugas,
                    LEAST(100, (
                        SELECT SUM(nilai_absensi) 
                        FROM tb_absensi 
                        WHERE tahun_akademik = :tahun_akademik 
                          AND id_krs IN (
                              SELECT id_krs 
                              FROM tb_krs 
                              WHERE nim = mhs.nim 
                                AND kode_mk = :kode_mk 
                                AND tahun_akademik = :tahun_akademik
                          )
                    )) AS nilai_absensi
                FROM tb_mahasiswa mhs
                INNER JOIN tb_kelas kls ON mhs.nim = kls.nim 
                INNER JOIN tb_krs krs ON mhs.nim = krs.nim AND krs.kode_mk = :kode_mk AND krs.tahun_akademik = :tahun_akademik
                WHERE kls.kode_kelas = :kode_kelas AND kls.tahun_akademik = :tahun_akademik AND kls.status = 'Aktif'
                ORDER BY mhs.nim ASC
            ");
            $sql->execute([
                ':kode_mk' => $kode_mk,
                ':kode_kelas' => $kode_kelas,
                ':tahun_akademik' => $tahun_akademik
            ]);

            $dataMahasiswa = $sql->fetchAll(PDO::FETCH_ASSOC);
        }
    }

    require __DIR__ . '/../Views/dosen/view_nilai_kelas.php';
}

}
