<?php
class exam_types_model {
    private $db;
    public function __construct() {
        $this->db = database::connect();
    }

    public function getAll() {
        return $this->db->query("SELECT * FROM exam_types WHERE status = 'enabled'")->fetchAll(PDO::FETCH_ASSOC);
    }

    public function validate($name, $id=null) {

        if(empty($id)) {

          $stmt = $this->db->prepare("SELECT * FROM exam_types WHERE name = ?");

          $stmt->execute([$name]);

          return $stmt->fetch(PDO::FETCH_ASSOC);

        }else{

          $stmt = $this->db->prepare("SELECT * FROM exam_types WHERE name = ? AND id != ?");

          $stmt->execute([$name, $id]);

          return $stmt->fetch(PDO::FETCH_ASSOC);
        }
    }

    public function get($id) {
        $stmt = $this->db->prepare("SELECT * FROM exam_types WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function insert($data) {
        $keys = implode(',', array_keys($data));
        $placeholders = implode(',', array_fill(0, count($data), '?'));
        $stmt = $this->db->prepare("INSERT INTO exam_types ($keys) VALUES ($placeholders)");
        return $stmt->execute(array_values($data));
    }

    public function update($id, $data) {
        $fields = implode(',', array_map(fn($k) => "$k = ?", array_keys($data)));
        $stmt = $this->db->prepare("UPDATE exam_types SET $fields WHERE id = ?");
        return $stmt->execute([...array_values($data), $id]);
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM exam_types WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
?>
