<?php
namespace App\Models;

class NilaiModel
{
    protected $pdo;

    public function __construct(\PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function upsertNilai(array $data)
    {
        $sqlCheck = "SELECT id_khs FROM tb_khs WHERE nim = :nim AND kode_mk = :kode_mk AND smt = :smt LIMIT 1";
        $stmt = $this->pdo->prepare($sqlCheck);
        $stmt->execute([
            ':nim' => $data['nim'],
            ':kode_mk' => $data['kode_mk'],
            ':smt' => $data['smt']
        ]);
        $row = $stmt->fetch();

        if ($row) {
            $sqlUpdate = "UPDATE tb_khs SET nilai=:nilai, mutu=:mutu, bobot=:bobot, sks_x_bobot=:sks_x_bobot, accept=:accept WHERE id_khs=:id";
            $stmtUpdate = $this->pdo->prepare($sqlUpdate);
            $stmtUpdate->execute([
                ':nilai' => $data['nilai'],
                ':mutu' => $data['mutu'],
                ':bobot' => $data['bobot'],
                ':sks_x_bobot' => $data['sks_x_bobot'],
                ':accept' => $data['accept'],
                ':id' => $row['id_khs']
            ]);
        } else {
            $sqlInsert = "INSERT INTO tb_khs (nim, kode_mk, smt, nilai, mutu, bobot, sks_x_bobot, accept) 
                          VALUES (:nim,:kode_mk,:smt,:nilai,:mutu,:bobot,:sks_x_bobot,:accept)";
            $stmtInsert = $this->pdo->prepare($sqlInsert);
            $stmtInsert->execute([
                ':nim' => $data['nim'],
                ':kode_mk' => $data['kode_mk'],
                ':smt' => $data['smt'],
                ':nilai' => $data['nilai'],
                ':mutu' => $data['mutu'],
                ':bobot' => $data['bobot'],
                ':sks_x_bobot' => $data['sks_x_bobot'],
                ':accept' => $data['accept']
            ]);
        }
    }
}
