<?php
/**
 * Controller Pencarian
 */
class PencarianController {

    public function index() {
        $query   = sanitize($_GET['q'] ?? '');
        $type    = sanitize($_GET['type'] ?? 'siswa');
        $kelasId = (int)($_GET['kelas_id'] ?? 0);

        $results = [];
        $total   = 0;

        if ($query || $kelasId) {
            $db = getDB();

            if ($type === 'siswa') {
                $where = ['1=1'];
                $params = [];
                $types = '';

                if ($query) {
                    $where[] = '(s.nama LIKE ? OR s.nis LIKE ? OR s.nisn LIKE ? OR s.nik LIKE ?)';
                    $like = '%' . $query . '%';
                    $params = array_merge($params, [$like, $like, $like, $like]);
                    $types .= 'ssss';
                }
                if ($kelasId) {
                    $where[] = 's.kelas_id = ?';
                    $params[] = $kelasId;
                    $types .= 'i';
                }

                $whereStr = implode(' AND ', $where);
                $sql = "SELECT s.*, k.nama_kelas FROM siswa s
                        LEFT JOIN kelas k ON s.kelas_id = k.id
                        WHERE $whereStr ORDER BY s.nama LIMIT 50";

                $stmt = $db->prepare($sql);
                if ($params) $stmt->bind_param($types, ...$params);
                $stmt->execute();
                $results = stmt_get_result($stmt)->fetch_all(MYSQLI_ASSOC);
                $total = count($results);

            } elseif ($type === 'guru') {
                $like = '%' . $query . '%';
                $stmt = $db->prepare(
                    "SELECT * FROM guru WHERE nama LIKE ? OR nip LIKE ? OR mata_pelajaran LIKE ?
                     ORDER BY nama LIMIT 50"
                );
                $stmt->bind_param('sss', $like, $like, $like);
                $stmt->execute();
                $results = stmt_get_result($stmt)->fetch_all(MYSQLI_ASSOC);
                $total = count($results);
            }
        }

        // Kelas list for filter
        $db = getDB();
        $kelasList = query_fetch_all($db,
            "SELECT id, nama_kelas FROM kelas ORDER BY tingkat, nama_kelas"
        );

        $pageTitle = 'Pencarian';
        include __DIR__ . '/../views/pencarian/index.php';
    }
}
