<?php
namespace App\Controllers;

use Core\Database;
use PDO;

class DosenInputUTSUASKelasController
{
    private $db;

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

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

		$db = $this->db;

		// Ambil data tahun akademik aktif
		$stmtTA = $db->prepare("SELECT tahun_akademik FROM tb_akademik WHERE status = 'Aktif'");
		$stmtTA->execute();
		$rowTA = $stmtTA->fetch(PDO::FETCH_ASSOC);
		$tahun_akademik = $rowTA['tahun_akademik'] ?? null;

		// Ambil data matakuliah untuk dropdown
		$stmtMK = $db->prepare("SELECT dm.kode_mk, mk.singkatan, dm.kode_kelas, dm.id_dmk
			FROM tb_dosen_mk dm
			JOIN tb_mk mk ON dm.kode_mk = mk.kode_mk
			WHERE dm.niy = :niy AND dm.tahun_akademik = :ta");
		$stmtMK->execute([':niy' => $niy, ':ta' => $tahun_akademik]);
		$matakuliah = $stmtMK->fetchAll(PDO::FETCH_ASSOC);

		$daftar_mahasiswa = [];
		$info_kelas = [];
		$id_j_soal = $_POST['id_j_soal'] ?? $_GET['id_j_soal'] ?? null;

		if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id_dmk'])) {
			$id_dmk = $_POST['id_dmk'];

			// Ambil info kelas & mk
			$stmtInfo = $db->prepare("SELECT dm.kode_mk, dm.kode_kelas, mk.sks, dm.id_dmk
				FROM tb_dosen_mk dm
				JOIN tb_mk mk ON dm.kode_mk = mk.kode_mk
				WHERE dm.id_dmk = :id_dmk");
			$stmtInfo->execute([':id_dmk' => $id_dmk]);
			$info_kelas = $stmtInfo->fetch(PDO::FETCH_ASSOC);

			if ($info_kelas) {
				$kode_mk = $info_kelas['kode_mk'];
				$kode_kelas = $info_kelas['kode_kelas'];

				// Ambil daftar mahasiswa & nilai
				$stmtMhs = $db->prepare("SELECT DISTINCT m.nim, m.nama,
					(SELECT nilai FROM tb_mk_dijawab
					 WHERE nim = m.nim AND kode_mk = :kode_mk AND id_jenis_s = :id_j_soal AND tahun_akademik = :tahun_akademik) AS nilai
					FROM tb_mahasiswa m
					JOIN tb_kelas k ON m.nim = k.nim
					JOIN tb_krs r ON m.nim = r.nim
					WHERE r.kode_mk = :kode_mk
					  AND r.tahun_akademik = :tahun_akademik
					  AND k.kode_kelas = :kode_kelas
					  AND k.tahun_akademik = :tahun_akademik
					  AND k.Status = 'Aktif'
					ORDER BY m.nim ASC");

				$stmtMhs->execute([
					':kode_mk' => $kode_mk,
					':kode_kelas' => $kode_kelas,
					':tahun_akademik' => $tahun_akademik,
					':id_j_soal' => $id_j_soal,
				]);
				$daftar_mahasiswa = $stmtMhs->fetchAll(PDO::FETCH_ASSOC);
			}
		}

		// Proses simpan nilai UTS/UAS jika form dikirimkan
		if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['nim'], $_POST['nilai'], $_POST['kode_mk'], $_POST['kode_kelas'], $_POST['tahun_akademik'], $_POST['id_j_soal'])) {
			$nims = $_POST['nim'];
			$nilais = $_POST['nilai'];
			$kode_mk = $_POST['kode_mk'];
			$kode_kelas = $_POST['kode_kelas'];
			$tahun_akademik = $_POST['tahun_akademik'];
			$id_j_soal = $_POST['id_j_soal'];

			foreach ($nims as $index => $nim) {
				$nilai = (int) $nilais[$index];

				// Cek apakah data sudah ada
				$stmtCek = $db->prepare("SELECT COUNT(*) FROM tb_mk_dijawab WHERE nim = :nim AND kode_mk = :kode_mk AND id_jenis_s = :id_j_soal AND tahun_akademik = :tahun_akademik");
				$stmtCek->execute([
					':nim' => $nim,
					':kode_mk' => $kode_mk,
					':id_j_soal' => $id_j_soal,
					':tahun_akademik' => $tahun_akademik
				]);
				$ada = $stmtCek->fetchColumn();

				if ($ada) {
					// Update nilai
					$stmtUpdate = $db->prepare("UPDATE tb_mk_dijawab SET nilai = :nilai WHERE nim = :nim AND kode_mk = :kode_mk AND id_jenis_s = :id_j_soal AND tahun_akademik = :tahun_akademik");
					$stmtUpdate->execute([
						':nilai' => $nilai,
						':nim' => $nim,
						':kode_mk' => $kode_mk,
						':id_j_soal' => $id_j_soal,
						':tahun_akademik' => $tahun_akademik
					]);
				} else {
					// Insert nilai baru
					$stmtInsert = $db->prepare("INSERT INTO tb_mk_dijawab (nim, kode_mk, id_jenis_s, nilai, tahun_akademik) VALUES (:nim, :kode_mk, :id_j_soal, :nilai, :tahun_akademik)");
					$stmtInsert->execute([
						':nim' => $nim,
						':kode_mk' => $kode_mk,
						':id_j_soal' => $id_j_soal,
						':nilai' => $nilai,
						':tahun_akademik' => $tahun_akademik
					]);
				}
			}

			echo '<!DOCTYPE html>';
			echo '<html><head><meta charset="UTF-8"><title>Redirect</title></head><body>';
			echo '<form id="redirectForm" method="POST" action="/dashboard/dosen-input-uasuts">';
			echo '<input type="hidden" name="id_j_soal" value="' . htmlspecialchars($_POST['id_j_soal'] ?? '') . '">';
			echo '<input type="hidden" name="kode_mk" value="' . htmlspecialchars($_POST['kode_mk'] ?? '') . '">';
			echo '<input type="hidden" name="kode_kelas" value="' . htmlspecialchars($_POST['kode_kelas'] ?? '') . '">';
			echo '<input type="hidden" name="id_dmk" value="' . htmlspecialchars($_POST['id_dmk'] ?? '') . '">';
			echo '<input type="hidden" name="tahun_akademik" value="' . htmlspecialchars($_POST['tahun_akademik'] ?? '') . '">';
			echo '<input type="hidden" name="flash_success" value="Nilai berhasil disimpan.">';
			echo '</form>';
			echo '<script>document.getElementById("redirectForm").submit();</script>';
			echo '</body></html>';
			exit;

		}		

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

}
