<?php
namespace App\Models;

use Core\Database;
use PDO;

class Wisuda
{
    private $pdo;

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

    public function getByNim($nim)
    {
        $stmt = $this->pdo->prepare("SELECT * FROM tb_wisuda WHERE nim = :nim");
        $stmt->execute([':nim' => $nim]);
        return $stmt->fetch();
    }

    public function getTokenDataByTokenAndKegiatan($token, $kegiatan)
    {
        $stmt = $this->pdo->prepare("SELECT * FROM tb_token WHERE token = :token AND kegiatan = :kegiatan");
        $stmt->execute([':token' => $token, ':kegiatan' => $kegiatan]);
        return $stmt->fetch();
    }

    public function getMahasiswa($nim)
    {
        $stmt = $this->pdo->prepare("SELECT * FROM tb_yudisium WHERE nim = :nim");
        $stmt->execute([':nim' => $nim]);
        return $stmt->fetch();
    }

    // Insert data awal saat token valid dan dipakai
    public function insertInitial($data)
    {
        $stmt = $this->pdo->prepare("INSERT INTO tb_wisuda (nim, nama, id_prodi, nik, nisn, tempat_lahir, tanggal_lahir, gender, alamat, tahun_masuk, judul_skripsi, dospem1, dospem2, no_wa, tahun_wisuda, tgl_lulus, tgl_sidang, token)
														VALUES (:nim, :nama, :id_prodi, :nik, :nisn, :tempat_lahir, :tanggal_lahir, :gender, :alamat, :tahun_masuk, :judul_skripsi, :dospem1, :dospem2, :no_wa, :tahun_wisuda, :tgl_lulus, :tgl_sidang,  :token)");
        return $stmt->execute($data);
    }

    // Hapus token setelah dipakai (sekali pakai)
    public function deleteToken($token)
    {
        $stmt = $this->pdo->prepare("DELETE FROM tb_token WHERE token = :token");
        return $stmt->execute([':token' => $token]);
    }

    public function update($data)
    {
        $stmt = $this->pdo->prepare("UPDATE tb_wisuda SET
            nik = :nik,
            nisn = :nisn,
            tempat_lahir = :tempat_lahir,
            tanggal_lahir = :tanggal_lahir,
            gender = :gender,
            alamat_leng = :alamat_leng,
            judul_skripsi = :judul_skripsi,
            ipk = :ipk,
            nama_ayah = :nama_ayah,
            nama_ibu = :nama_ibu,
            email = :email,
            tgl_lulus = :tgl_lulus,
            no_wa = :no_wa
            WHERE nim = :nim");
        
        return $stmt->execute($data);
    }
	
    public function searchDosenByName($keyword)
    {
        $keyword = "%$keyword%";
        $sql = "SELECT nama FROM tb_dosen WHERE nama LIKE ? LIMIT 10";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$keyword]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
}
