<?php
namespace App\Controllers;

use Core\Database;
use PDO;

class SoalController 
{
    public function mulai()
    {

		if (!isset($_SESSION['user'])) {
			header('Location: /login');
			exit;
		}

		$level = strtolower($_SESSION['user']['level'] ?? '');
		if ($level !== 'mahasiswa') {
			header('Location: /dashboard');
			exit;
		}

        $nim = $_SESSION['user']['nim'] ?? null;
        $db = Database::getConnection();

        // Ambil data dari GET
        $kode_mk = $_GET['kode_mk'] ?? '';
        $id_jadwal_u = $_GET['id_jadwal_u'] ?? '';
        $tipe_soal = $_GET['tipe_soal'] ?? '';
        $tgl_berakhir = $_GET['tgl_berakhir'] ?? '';

        // Tahun akademik aktif
        $tahunAktif = $db->query("SELECT tahun_akademik FROM tb_akademik WHERE status = 'aktif' LIMIT 1")->fetchColumn();

        // Jenis soal aktif
        $idJenisSoal = $db->query("SELECT id_jenis_s FROM tb_jenis_soal WHERE status = 'aktif' LIMIT 1")->fetchColumn();

        // Kode kelas mahasiswa
        $stmt = $db->prepare("SELECT kode_kelas FROM tb_kelas WHERE nim = ? AND tahun_akademik = ? AND status = 'aktif' LIMIT 1");
        $stmt->execute([$nim, $tahunAktif]);
        $kode_kelas = $stmt->fetchColumn();

        // Ambil ID dosen pengampu (niy) dari jadwal ujian
        $stmt = $db->prepare("SELECT dmk.niy FROM tb_jadwal_ujian ju JOIN tb_dosen_mk dmk ON ju.id_dmk = dmk.id_dmk WHERE ju.id_jadwal_u = ? LIMIT 1");
        $stmt->execute([$id_jadwal_u]);
        $niy = $stmt->fetchColumn();

        // Ambil nama mata kuliah
        $stmt = $db->prepare("SELECT nama_mk FROM tb_mk WHERE kode_mk = ? LIMIT 1");
        $stmt->execute([$kode_mk]);
        $nama_mk = $stmt->fetchColumn();

        // Ambil soal
        $stmt = $db->prepare("SELECT * FROM tb_soal WHERE kode_mk = ? AND tipe_soal = ? AND kode_kelas = ? AND niy = ? AND tahun_akademik = ?");
        $stmt->execute([$kode_mk, $tipe_soal, $kode_kelas, $niy, $tahunAktif]);
        $soalList = $stmt->fetchAll();

        // Ambil jawaban jika sudah ada
        $jawabanSebelumnya = [];
        foreach ($soalList as $soal) {
            $stmt = $db->prepare("SELECT jawaban FROM tb_jawaban WHERE id_soal = ? AND nim = ? AND tahun_akademik = ? LIMIT 1");
            $stmt->execute([$soal['id_soal'], $nim, $tahunAktif]);
            $jawabanSebelumnya[$soal['id_soal']] = $stmt->fetchColumn();
        }

        // Tampilkan view pengerjaan soal
        include_once __DIR__ . '/../Views/ujian/kerjakan_soal.php';
    }

	public function simpanJawaban()
	{
		if (!isset($_SESSION['user'])) {
			header('Location: /login');
			exit;
		}

		$nim = $_SESSION['user']['nim'] ?? null;

		if (!$nim) {
			echo "NIM tidak ditemukan di sesi.";
			exit;
		}

		$jawabanList = $_POST['jawaban'] ?? [];
		$id_jadwal_u = $_POST['id_jadwal_u'] ?? '';
		$tipe_soal = $_POST['tipe_soal'] ?? '';
		$kode_mk = $_POST['kode_mk'] ?? '';

		$db = \Core\Database::getConnection();

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

		$berhasilSimpan = true;

		foreach ($jawabanList as $id_soal => $teksJawaban) {
			$stmt = $db->prepare("SELECT id_jawaban FROM tb_jawaban WHERE id_soal = ? AND nim = ? AND tahun_akademik = ?");
			$stmt->execute([$id_soal, $nim, $tahunAktif]);
			$existing = $stmt->fetch();

			if ($existing) {
				$stmtUpdate = $db->prepare("UPDATE tb_jawaban SET jawaban = ?, tanggal_jawab = NOW() WHERE id_soal = ? AND nim = ? AND tahun_akademik = ?");
				if (!$stmtUpdate->execute([$teksJawaban, $id_soal, $nim, $tahunAktif])) {
					$berhasilSimpan = false;
				}
			} else {
				$stmtInsert = $db->prepare("INSERT INTO tb_jawaban (id_soal, nim, jawaban, tanggal_jawab, tahun_akademik) VALUES (?, ?, ?, NOW(), ?)");
				if (!$stmtInsert->execute([$id_soal, $nim, $teksJawaban, $tahunAktif])) {
					$berhasilSimpan = false;
				}
			}
		}

		if ($berhasilSimpan) {
			$_SESSION['info'] = 'Jawaban berhasil disimpan';
			$_SESSION['info_type'] = 'success';
		} else {
			$_SESSION['info'] = 'Jawaban gagal disimpan';
			$_SESSION['info_type'] = 'error';
		}

		// Redirect kembali ke halaman soal
		header("Location: /dashboard/mahasiswa-soal");
		exit;
	}



} 