<?php
namespace App\Models;

use Core\Database;

class UjianKompre {

    // Cek apakah mahasiswa sudah punya token kompre di tb_token_kompre berdasar nim
    public function cekTokenMahasiswa($nim) {
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT * FROM tb_token_kompre WHERE nim = :nim");
        $stmt->execute(['nim' => $nim]);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    // Cek token valid di tb_token dengan kegiatan Kompre
    public function cekTokenDiTbToken($token) {
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT * FROM tb_token WHERE token = :token AND kegiatan = 'Kompre'");
        $stmt->execute(['token' => $token]);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    // Insert token ke tb_token_kompre dengan status 'unused' dan tahun akademik aktif
    public function insertTokenKompre($nim, $token) {
        $db = Database::getConnection();
        $stmt = $db->prepare("
            INSERT INTO tb_token_kompre (token, nim, status, tahun_akademik) 
            VALUES (:token, :nim, 'unused', (SELECT tahun_akademik FROM tb_akademik WHERE status = 'Aktif' LIMIT 1))
        ");
        return $stmt->execute([
            'token' => $token,
            'nim' => $nim
        ]);
    }

    // Hapus token di tb_token setelah dipakai
    public function hapusToken($token) {
        $db = Database::getConnection();
        $stmt = $db->prepare("DELETE FROM tb_token WHERE token = :token");
        return $stmt->execute(['token' => $token]);
    }

    // Ambil id_token_k dari tb_token_kompre berdasarkan nim dan token
    public function getIdTokenKompre($nim, $token) {
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT id_token_k FROM tb_token_kompre WHERE nim = :nim AND token = :token");
        $stmt->execute([
            'nim' => $nim,
            'token' => $token
        ]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        return $row ? $row['id_token_k'] : null;
    }

    // Buat ujian baru di tb_ujiankompre dengan nim dan id_tokenkompre
    public function buatUjian($nim) {
        $db = Database::getConnection();
    
        // pastikan nim bukan array
        if (is_array($nim)) {
            $nim = $nim[0];
        }
    
        $stmt = $db->prepare("
            INSERT INTO tb_ujiankompre (nim, waktu_mulai) 
            VALUES (:nim, NOW())
        ");
        $stmt->execute([
            'nim' => $nim
        ]);
    
        return $db->lastInsertId();
    }

    // Ambil ujian terakhir berdasar nim
    public function getUjianByNim($nim) {
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT * FROM tb_ujiankompre WHERE nim = :nim ORDER BY waktu_mulai DESC LIMIT 1");
        $stmt->execute(['nim' => $nim]);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    // Ambil soal ujian  
	public function getSoal($nim) {
		$db = Database::getConnection();

		// Ambil id_prodi dari tb_mahasiswa
		$stmtProdi = $db->prepare("SELECT id_prodi FROM tb_mahasiswa WHERE nim = ?");
		$stmtProdi->execute([$nim]);
		$result = $stmtProdi->fetch();

		if (!$result) {
			return []; // Nim tidak ditemukan
		}

		$id_prodi = $result['id_prodi'];

		// Ambil semua soal aktif berdasarkan id_prodi
		$stmtSoal = $db->prepare("
			SELECT id_kompre, pertanyaan, pilihan_a, pilihan_b, pilihan_c, pilihan_d, pilihan_e 
			FROM tb_soal_kompre 
			WHERE status = 'aktif' AND id_prodi = ?
		");
		$stmtSoal->execute([$id_prodi]);

		return $stmtSoal->fetchAll();
	}

    // Simpan jawaban mahasiswa
    public function simpanJawaban($id_ujian, $id_soal, $jawaban) {
        $db = Database::getConnection();
    
        $stmt = $db->prepare("
            INSERT INTO tb_jawabankompre (id_ujiankompre, id_kompre, jawaban) 
            VALUES (:id_ujian, :id_soal, :jawaban)
            ON DUPLICATE KEY UPDATE jawaban = :jawaban
        ");
        return $stmt->execute([
            'id_ujian' => $id_ujian,
            'id_soal'  => $id_soal,
            'jawaban'  => $jawaban
        ]);
    }


    // Selesaikan ujian: update status dan waktu selesai
    public function selesaikanUjian($id_ujian, $skor = null) {
        $db = Database::getConnection();
    
        if ($skor !== null) {
            $stmt = $db->prepare("
                UPDATE tb_ujiankompre 
                SET waktu_selesai = NOW(), skor = :skor 
                WHERE id_ujiankompre = :id
            ");
            return $stmt->execute([
                'id' => $id_ujian,
                'skor' => $skor
            ]);
        } else {
            $stmt = $db->prepare("
                UPDATE tb_ujiankompre 
                SET waktu_selesai = NOW() 
                WHERE id_ujiankompre = :id
            ");
            return $stmt->execute(['id' => $id_ujian]);
        }
    }


    // Ambil hasil ujian: total soal dan jawaban benar
    public function getHasil($id_ujian) {
        $db = Database::getConnection();
    
        // Ambil hasil (total & benar)
        $stmt = $db->prepare("
            SELECT 
                COUNT(*) AS total,
                SUM(jk.jawaban = sk.jawaban) AS benar
            FROM 
                tb_jawabankompre jk
            JOIN 
                tb_soal_kompre sk ON jk.id_kompre = sk.id_kompre
            WHERE 
                jk.id_ujiankompre = :id
        ");
        $stmt->execute(['id' => $id_ujian]);
        $hasil = $stmt->fetch();
    
        // Hitung skor
        $total = (int) $hasil['total'];
        $benar = (int) $hasil['benar'];
        $skor  = ($total > 0) ? intval(round(($benar / $total) * 100)) : 0;
    
        // ✅ Update skor ke tb_ujiankompre
        $update = $db->prepare("
            UPDATE tb_ujiankompre
            SET skor = :skor
            WHERE id_ujiankompre = :id
        ");
        $update->execute([
            'skor' => $skor,
            'id'   => $id_ujian
        ]);
    
        // Kembalikan hasil + skor
        $hasil['skor'] = $skor;
        return $hasil;
    }
	
	public function getMahasiswaByNim($nim) 
	{
		$db = Database::getConnection();
		$stmt = $db->prepare("SELECT * FROM tb_mahasiswa WHERE nim = :nim");
		$stmt->execute(['nim' => $nim]);
		return $stmt->fetch();
	}

    // Cek status kompre (Aktif / Tutup)
    public function cekStatusKompre()
    {
        $db = Database::getConnection();
    
        $stmt = $db->prepare("SELECT status FROM tb_kompre_active LIMIT 1");
        $stmt->execute();
    
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

}
