<?php
include 'koneksi.php';

header('Content-Type: application/json');

// ambil keyword
$q = $_GET['q'] ?? '';
$q = trim($q);

// kalau kosong, jangan query berat
if($q == ''){
    echo json_encode([]);
    exit;
}

// prepared statement (lebih aman)
$stmt = $koneksi->prepare("
    SELECT id, nama, tingkat, jurusan, rombel 
    FROM data_siswa 
    WHERE nama LIKE CONCAT('%', ?, '%')
    ORDER BY nama ASC
    LIMIT 15
");

$stmt->bind_param("s", $q);
$stmt->execute();

$result = $stmt->get_result();

$data = [];

while($row = $result->fetch_assoc()){

    // format kelas: 10 Perhotelan 2
    $kelas = $row['tingkat'] . " " . $row['jurusan'] . " " . $row['rombel'];

    $data[] = [
        "id" => $row['id'],
        "nama" => $row['nama'],
        "kelas" => $kelas,
        "jurusan" => $row['jurusan']
    ];
}

echo json_encode($data);