<?php
/**
 * Model Guru
 */
class GuruModel {
    private $db;

    public function __construct() {
        $this->db = getDB();
    }

    // ----------------------------------------------------------------
    // Ambil semua guru + kode mapel dari tabel mata_pelajaran
    // ----------------------------------------------------------------
    public function getAll($search = '', $status = '', $limit = 15, $offset = 0) {
        $where  = ['1=1'];
        $params = [];
        $types  = '';

        if ($search) {
            $where[] = '(g.nama LIKE ? OR g.nip LIKE ? OR mp.kode LIKE ? OR mp.nama LIKE ?)';
            $like    = '%' . $search . '%';
            $params  = array_merge($params, [$like, $like, $like, $like]);
            $types  .= 'ssss';
        }
        if ($status) {
            $where[]  = 'g.status = ?';
            $params[] = $status;
            $types   .= 's';
        }

        $whereStr = implode(' AND ', $where);
        $sql = "SELECT g.*,
                       mp.id   AS mapel_id,
                       mp.kode AS kode_mapel,
                       mp.nama AS nama_mapel,
                       mp.kkm  AS kkm_mapel
                FROM guru g
                LEFT JOIN mata_pelajaran mp ON mp.guru_id = g.id
                WHERE $whereStr
                ORDER BY g.nama ASC
                LIMIT ? OFFSET ?";

        $params[] = $limit;
        $params[] = $offset;
        $types   .= 'ii';

        $stmt = $this->db->prepare($sql);
        if ($params) $stmt->bind_param($types, ...$params);
        $stmt->execute();
        return stmt_get_result($stmt)->fetch_all(MYSQLI_ASSOC);
    }

    // ----------------------------------------------------------------
    // Hitung total guru
    // ----------------------------------------------------------------
    public function countAll($search = '', $status = '') {
        $where  = ['1=1'];
        $params = [];
        $types  = '';

        if ($search) {
            $where[] = '(g.nama LIKE ? OR g.nip LIKE ? OR mp.kode LIKE ? OR mp.nama LIKE ?)';
            $like    = '%' . $search . '%';
            $params  = array_merge($params, [$like, $like, $like, $like]);
            $types  .= 'ssss';
        }
        if ($status) {
            $where[]  = 'g.status = ?';
            $params[] = $status;
            $types   .= 's';
        }

        $whereStr = implode(' AND ', $where);
        $sql = "SELECT COUNT(*) as total
                FROM guru g
                LEFT JOIN mata_pelajaran mp ON mp.guru_id = g.id
                WHERE $whereStr";

        $stmt = $this->db->prepare($sql);
        if ($params) $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $row = stmt_get_result($stmt)->fetch_assoc();
        return (int)($row['total'] ?? 0);
    }

    // ----------------------------------------------------------------
    // Ambil satu guru by ID + mapel
    // ----------------------------------------------------------------
    public function getById($id) {
        $stmt = $this->db->prepare(
            "SELECT g.*,
                    mp.id   AS mapel_id,
                    mp.kode AS kode_mapel,
                    mp.nama AS nama_mapel
             FROM guru g
             LEFT JOIN mata_pelajaran mp ON mp.guru_id = g.id
             WHERE g.id = ?
             LIMIT 1"
        );
        $stmt->bind_param('i', $id);
        $stmt->execute();
        return stmt_get_result($stmt)->fetch_assoc();
    }

    // ----------------------------------------------------------------
    // Semua guru aktif (untuk dropdown wali kelas)
    // ----------------------------------------------------------------
    public function getAllActive() {
        return query_fetch_all($this->db,
            "SELECT g.id, g.nama, g.nip, mp.kode AS kode_mapel
             FROM guru g
             LEFT JOIN mata_pelajaran mp ON mp.guru_id = g.id
             WHERE g.status = 'Aktif'
             ORDER BY g.nama"
        );
    }

    // ----------------------------------------------------------------
    // Insert guru baru
    // ----------------------------------------------------------------
    public function insert($data) {
        $stmt = $this->db->prepare(
            "INSERT INTO guru
             (nip, nama, jenis_kelamin, tempat_lahir, tanggal_lahir,
              agama, pendidikan, jurusan_pendidikan, mata_pelajaran,
              status_kepegawaian, no_hp, email, alamat, tahun_masuk, status)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );
        $stmt->bind_param('sssssssssssssss',
            $data['nip'],
            $data['nama'],
            $data['jenis_kelamin'],
            $data['tempat_lahir'],
            $data['tanggal_lahir'],
            $data['agama'],
            $data['pendidikan'],
            $data['jurusan_pendidikan'],
            $data['mata_pelajaran'],   // kode mapel (teks)
            $data['status_kepegawaian'],
            $data['no_hp'],
            $data['email'],
            $data['alamat'],
            $data['tahun_masuk'],
            $data['status']
        );
        $stmt->execute();
        return $this->db->insert_id;
    }

    // ----------------------------------------------------------------
    // Update guru
    // ----------------------------------------------------------------
    public function update($id, $data) {
        $stmt = $this->db->prepare(
            "UPDATE guru
             SET nip=?, nama=?, jenis_kelamin=?, tempat_lahir=?, tanggal_lahir=?,
                 agama=?, pendidikan=?, jurusan_pendidikan=?, mata_pelajaran=?,
                 status_kepegawaian=?, no_hp=?, email=?, alamat=?, tahun_masuk=?, status=?
             WHERE id=?"
        );
        $stmt->bind_param('ssssssssssssssi',
            $data['nip'],
            $data['nama'],
            $data['jenis_kelamin'],
            $data['tempat_lahir'],
            $data['tanggal_lahir'],
            $data['agama'],
            $data['pendidikan'],
            $data['jurusan_pendidikan'],
            $data['mata_pelajaran'],
            $data['status_kepegawaian'],
            $data['no_hp'],
            $data['email'],
            $data['alamat'],
            $data['tahun_masuk'],
            $data['status'],
            $id
        );
        return $stmt->execute();
    }

    public function updateFoto($id, $foto) {
        $stmt = $this->db->prepare("UPDATE guru SET foto=? WHERE id=?");
        $stmt->bind_param('si', $foto, $id);
        return $stmt->execute();
    }

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

    public function countByStatus() {
        $rows = query_fetch_all($this->db,
            "SELECT status, COUNT(*) as total FROM guru GROUP BY status"
        );
        $data = [];
        foreach ($rows as $row) {
            $data[$row['status']] = $row['total'];
        }
        return $data;
    }
}
