<?php
namespace App\Controllers;

use Core\Database;
use PDO;

class DosenKoreksiJawabanController
{
    private $db;

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

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

        $kodeMkDipilih = $_GET['kode_mk'] ?? null;
        $kodeKelasDipilih = $_GET['kode_kelas'] ?? null;
        $nimYangDikoreksi = $_GET['nim'] ?? null;

        // Ambil daftar mata kuliah dosen aktif
        $stmt = $this->db->prepare("
            SELECT DISTINCT dm.kode_mk, mk.nama_mk, dm.kode_kelas 
            FROM tb_dosen_mk dm
            INNER JOIN tb_mk mk ON dm.kode_mk = mk.kode_mk
            INNER JOIN tb_akademik ak ON dm.tahun_akademik = ak.tahun_akademik
            WHERE dm.niy = :niy AND ak.status = 'Aktif'
        ");
        $stmt->execute(['niy' => $niy]);
        $mata_kuliah = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Ambil id_jenis_s aktif
        $stmt = $this->db->query("SELECT id_jenis_s FROM tb_jenis_soal WHERE status = 'Aktif' LIMIT 1");
        $id_jenis_s = $stmt->fetchColumn();

        // Proses simpan nilai POST
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $nilaiTotal = $_POST['nilai_total'] ?? null;
            $pkodeMkDipilih = $_POST['kode_mk'] ?? null;
            $pkodeKelasDipilih = $_POST['kode_kelas'] ?? null;
            $nimPost = $_GET['nim'] ?? null; // Pastikan nim dari query

            if (is_numeric($nilaiTotal) && $nimPost) {
                $stmt = $this->db->prepare("
                    UPDATE tb_mk_dijawab
                    SET nilai = :nilai
                    WHERE nim = :nim AND kode_mk = :kode_mk AND id_jenis_s = :id_jenis_s
                    AND tahun_akademik = (SELECT tahun_akademik FROM tb_akademik WHERE status = 'Aktif')
                ");
                $stmt->execute([
                    'nilai' => $nilaiTotal,
                    'nim' => $nimPost,
                    'kode_mk' => $pkodeMkDipilih,
                    'id_jenis_s' => $id_jenis_s
                ]);

                $_SESSION['success_message'] = "Nilai berhasil diperbarui.";
                header("Location: /dashboard/dosen-koreksi-jawaban?kode_mk=" . urlencode($pkodeMkDipilih) . "&kode_kelas=" . urlencode($pkodeKelasDipilih));
                exit();
            } else {
                $_SESSION['error_message'] = "Nilai total harus berupa angka dan NIM harus dipilih.";
            }
        }

        // Ambil daftar mahasiswa dan status jawaban jika ada kode MK dan kelas
        $mahasiswa = [];
		// Ambil jenis soal aktif (UTS/UAS)
		$stmtJenis = $this->db->prepare("SELECT jenis_soal FROM tb_jenis_soal WHERE status = 'Aktif' LIMIT 1");
		$stmtJenis->execute();
		$jenisAktif = $stmtJenis->fetch(PDO::FETCH_ASSOC);

		if (!$jenisAktif) {
			die("Jenis soal aktif tidak ditemukan.");
		}

		$jenis_soal = $jenisAktif['jenis_soal']; // contoh: "UTS" atau "UAS"

		if ($kodeMkDipilih && $kodeKelasDipilih) {
			$stmt = $this->db->prepare("
				SELECT k.nim, m.nama,
					CASE 
						WHEN EXISTS (
							SELECT 1 
							FROM tb_jawaban j
							JOIN tb_soal s ON j.id_soal = s.id_soal
							WHERE j.nim = k.nim 
							AND s.kode_mk = dm.kode_mk
							AND s.tipe_soal = :jenis_soal
							AND j.tahun_akademik = k.tahun_akademik
						) THEN 'Sudah Dikerjakan'
						ELSE 'Belum Mengerjakan'
					END AS status_jawaban,
					COALESCE(md.nilai, 0) AS nilai,
					:jenis_soal AS jenis_soal
				FROM tb_kelas k
				INNER JOIN tb_mahasiswa m ON k.nim = m.nim
				INNER JOIN tb_dosen_mk dm ON k.kode_kelas = dm.kode_kelas
				INNER JOIN tb_krs kr ON k.nim = kr.nim 
					AND dm.kode_mk = kr.kode_mk 
					AND kr.tahun_akademik = k.tahun_akademik
				LEFT JOIN tb_mk_dijawab md ON k.nim = md.nim 
					AND md.kode_mk = dm.kode_mk 
					AND md.tahun_akademik = k.tahun_akademik 
					AND md.id_jenis_s IN (
						SELECT id_jenis_s FROM tb_jenis_soal WHERE status = 'Aktif' AND jenis_soal = :jenis_soal
					)
				WHERE dm.niy = :niy 
					AND dm.kode_mk = :kode_mk 
					AND dm.kode_kelas = :kode_kelas
					AND k.tahun_akademik = (SELECT tahun_akademik FROM tb_akademik WHERE status = 'Aktif')
				GROUP BY k.nim, m.nama, md.nilai
			");

			$stmt->execute([
				'niy' => $niy,
				'kode_mk' => $kodeMkDipilih,
				'kode_kelas' => $kodeKelasDipilih,
				'jenis_soal' => $jenis_soal
			]);

			$mahasiswa = $stmt->fetchAll(PDO::FETCH_ASSOC);
		}

        // Ambil jawaban dan nilai mahasiswa yang dikoreksi
        $jawaban = [];
        $nilaiMahasiswa = null;
        if ($nimYangDikoreksi && $kodeMkDipilih) {
        $stmt = $this->db->prepare("
            SELECT j.jawaban, s.soal, s.tipe_soal
            FROM tb_jawaban j
            INNER JOIN tb_soal s ON j.id_soal = s.id_soal
            INNER JOIN tb_jenis_soal js ON s.tipe_soal = js.jenis_soal
            WHERE j.nim = :nim 
              AND s.kode_mk = :kode_mk 
              AND js.status = 'Aktif'
            ORDER BY s.id_soal ASC
        ");
        $stmt->execute([
            'nim' => $nimYangDikoreksi,
            'kode_mk' => $kodeMkDipilih
        ]);
        $jawaban = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $stmt = $this->db->prepare("
                SELECT nilai FROM tb_mk_dijawab 
                WHERE nim = :nim AND kode_mk = :kode_mk AND id_jenis_s = :id_jenis_s
            ");
            $stmt->execute([
                'nim' => $nimYangDikoreksi,
                'kode_mk' => $kodeMkDipilih,
                'id_jenis_s' => $id_jenis_s
            ]);
            $nilaiMahasiswa = $stmt->fetchColumn();
        }

        // Ambil nama mahasiswa yang dikoreksi
        $namaMahasiswa = null;
        if ($nimYangDikoreksi) {
            $stmt = $this->db->prepare("SELECT nama FROM tb_mahasiswa WHERE nim = :nim");
            $stmt->execute(['nim' => $nimYangDikoreksi]);
            $namaMahasiswa = $stmt->fetchColumn();
        }

        // Kirim variabel ke view
        $viewData = [
            'mata_kuliah' => $mata_kuliah,
            'kodeMkDipilih' => $kodeMkDipilih,
            'kodeKelasDipilih' => $kodeKelasDipilih,
            'nimYangDikoreksi' => $nimYangDikoreksi,
            'namaMahasiswa' => $namaMahasiswa,
            'mahasiswa' => $mahasiswa,
            'jawaban' => $jawaban,
            'nilaiMahasiswa' => $nilaiMahasiswa,
            'success_message' => $_SESSION['success_message'] ?? null,
            'error_message' => $_SESSION['error_message'] ?? null,
        ];

        // Hapus pesan session setelah dibaca supaya tidak muncul terus
        unset($_SESSION['success_message'], $_SESSION['error_message']);

        extract($viewData);
        require __DIR__ . '/../Views/dosen/koreksi_jawaban.php';
    }

	public function simpanNilai()
	{
		if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
			header("Location: /dashboard/dosen-koreksi-jawaban");
			exit();
		}

		$nilaiTotal = $_POST['nilai_total'] ?? null;
		$kodeMk = $_POST['kode_mk'] ?? null;
		$kodeKelas = $_POST['kode_kelas'] ?? null;
		$nim = $_GET['nim'] ?? null;

		if (!is_numeric($nilaiTotal) || !$kodeMk || !$kodeKelas || !$nim) {
			$_SESSION['error_message'] = "Data tidak lengkap atau nilai tidak valid.";
			header("Location: /dashboard/dosen-koreksi-jawaban?kode_mk=" . urlencode($kodeMk) . "&kode_kelas=" . urlencode($kodeKelas) . "&nim=" . urlencode($nim));
			exit();
		}

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

		// Ambil id_jenis_s aktif
		$stmt = $this->db->query("SELECT id_jenis_s FROM tb_jenis_soal WHERE status = 'Aktif' LIMIT 1");
		$idJenisSoal = $stmt->fetchColumn();

		// Cek apakah data sudah ada
		$stmt = $this->db->prepare("
			SELECT COUNT(*) FROM tb_mk_dijawab 
			WHERE nim = :nim AND kode_mk = :kode_mk AND id_jenis_s = :id_jenis_s AND tahun_akademik = :tahun_akademik
		");
		$stmt->execute([
			'nim' => $nim,
			'kode_mk' => $kodeMk,
			'id_jenis_s' => $idJenisSoal,
			'tahun_akademik' => $tahunAkademik
		]);
		$exists = $stmt->fetchColumn() > 0;

		if ($exists) {
			// Update nilai
			$stmt = $this->db->prepare("
				UPDATE tb_mk_dijawab
				SET nilai = :nilai
				WHERE nim = :nim AND kode_mk = :kode_mk AND id_jenis_s = :id_jenis_s AND tahun_akademik = :tahun_akademik
			");
		} else {
			// Insert nilai baru
			$stmt = $this->db->prepare("
				INSERT INTO tb_mk_dijawab (nim, kode_mk, id_jenis_s, nilai, tahun_akademik)
				VALUES (:nim, :kode_mk, :id_jenis_s, :nilai, :tahun_akademik)
			");
		}

		$stmt->execute([
			'nim' => $nim,
			'kode_mk' => $kodeMk,
			'id_jenis_s' => $idJenisSoal,
			'nilai' => $nilaiTotal,
			'tahun_akademik' => $tahunAkademik
		]);

		$_SESSION['success_message'] = "Nilai berhasil disimpan.";
		header("Location: /dashboard/dosen-koreksi-jawaban?kode_mk=" . urlencode($kodeMk) . "&kode_kelas=" . urlencode($kodeKelas));
		exit();
	}
	
}
