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

    public function getAll($id=null) {
        if (empty($id)) {
          return $this->db->query("SELECT * FROM courses WHERE status = 'enabled'")->fetchAll(PDO::FETCH_ASSOC);
        }else{
          return $this->db->query("SELECT * FROM courses WHERE programme_id = $id AND status = 'enabled'")->fetchAll(PDO::FETCH_ASSOC);
        }

    }

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

        if(empty($id)) {

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

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

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

        }else{

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

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

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

    public function get($id) {
        $stmt = $this->db->prepare("SELECT * FROM courses 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 courses ($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 courses SET $fields WHERE id = ?");
        return $stmt->execute([...array_values($data), $id]);
    }

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