<?php
class MapelModel {
    private $db;
    public function __construct() { $this->db = getDB(); }

    public function getAll($search = '') {
        if ($search) {
            $stmt = $this->db->prepare(
                "SELECT mp.*, g.nama AS nama_guru FROM mata_pelajaran mp
                 LEFT JOIN guru g ON mp.guru_id = g.id
                 WHERE mp.kode LIKE ? OR mp.nama LIKE ?
                 ORDER BY mp.kode"
            );
            $like = '%'.$search.'%';
            $stmt->bind_param('ss', $like, $like);
        } else {
            $stmt = $this->db->prepare(
                "SELECT mp.*, g.nama AS nama_guru FROM mata_pelajaran mp
                 LEFT JOIN guru g ON mp.guru_id = g.id
                 ORDER BY mp.kode"
            );
        }
        $stmt->execute();
        return stmt_get_result($stmt)->fetch_all(MYSQLI_ASSOC);
    }

    public function getById($id) {
        $stmt = $this->db->prepare("SELECT * FROM mata_pelajaran WHERE id=?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        return stmt_get_result($stmt)->fetch_assoc();
    }

    public function getAllSimple() {
        return query_fetch_all($this->db,
            "SELECT id, kode, nama, kkm FROM mata_pelajaran ORDER BY kode"
        );
    }

    public function insert($data) {
        $stmt = $this->db->prepare("INSERT INTO mata_pelajaran (kode, nama, kkm) VALUES (?, ?, ?)");
        $stmt->bind_param('ssi', $data['kode'], $data['nama'], $data['kkm']);
        $stmt->execute();
        return $this->db->insert_id;
    }

    public function update($id, $data) {
        $stmt = $this->db->prepare("UPDATE mata_pelajaran SET kode=?, nama=?, kkm=? WHERE id=?");
        $stmt->bind_param('ssii', $data['kode'], $data['nama'], $data['kkm'], $id);
        return $stmt->execute();
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM mata_pelajaran WHERE id=?");
        $stmt->bind_param('i', $id);
        return $stmt->execute();
    }

    public function isKodeExists($kode, $excludeId = 0) {
        $stmt = $this->db->prepare("SELECT id FROM mata_pelajaran WHERE kode=? AND id!=?");
        $stmt->bind_param('si', $kode, $excludeId);
        $stmt->execute();
        return stmt_get_result($stmt)->num_rows > 0;
    }

    public function count() {
        $row = query_fetch_assoc($this->db, "SELECT COUNT(*) as c FROM mata_pelajaran");
        return (int)($row['c'] ?? 0);
    }
}
