<?php
namespace App\Models;

use Core\Database;
use PDO;

class Yudisium
{
    private $pdo;

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

    public function getByNim($nim)
    {
        $stmt = $this->pdo->prepare("SELECT * FROM tb_yudisium 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_mahasiswa WHERE nim = :nim");
        $stmt->execute([':nim' => $nim]);
        return $stmt->fetch();
    }

    // Insert data awal saat token valid dan dipakai
    public function insertInitial($data)
    {
        // pastikan tanggal_lahir tidak null
        if (empty($data[':tanggal_lahir'])) {
            $data[':tanggal_lahir'] = '0000-00-00'; // atau bisa pakai date('Y-m-d')
        }
    
        $stmt = $this->pdo->prepare("INSERT INTO tb_yudisium 
            (nama, nim, id_prodi, tempat_lahir, tanggal_lahir, gender, alamat, tahun_masuk, tahun_yudisium, tgl_sidang, token)
            VALUES (:nama, :nim, :id_prodi, :tempat_lahir, :tanggal_lahir, :gender, :alamat, :tahun_masuk, :tahun_yudisium, :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_yudisium SET
            nik = :nik,
            nisn = :nisn,
            tempat_lahir = :tempat_lahir,
            tanggal_lahir = :tanggal_lahir,
            gender = :gender,
            alamat = :alamat,
            tahun_masuk = :tahun_masuk,
            judul_skripsi = :judul_skripsi,
            dospem1 = :dospem1,
            dospem2 = :dospem2,
            link_skripsi = :link_skripsi,
            tgl_sidang = :tgl_sidang,
            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);
    }
}
