<?php
session_start();
require_once '../config/database.php';
require_once '../config/function.php';

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

// Cek koneksi database
if (!$conn) {
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

// Ambil parameter
$search = isset($_GET['q']) ? mysqli_real_escape_string($conn, $_GET['q']) : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : $search;
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;

// Jika ada ID spesifik (untuk menampilkan data yang sudah dipilih)
if ($id > 0) {
    $query = "SELECT 
                id_siswa as id, 
                CONCAT(nama, ' (NIS: ', nis, ')') as text,
                nis,
                nama,
                '-' as kelas
              FROM bkcare_siswa 
              WHERE id_siswa = $id AND status = 'aktif'";
    
    $result = mysqli_query($conn, $query);
    
    if (!$result) {
        echo json_encode(['results' => []]);
        exit;
    }
    
    $items = [];
    if ($row = mysqli_fetch_assoc($result)) {
        $items[] = [
            'id' => $row['id'],
            'text' => $row['text'],
            'nis' => $row['nis'],
            'nama' => $row['nama'],
            'kelas' => $row['kelas']
        ];
    }
    
    echo json_encode(['results' => $items]);
    exit;
}

// Query untuk pencarian dengan format yang benar untuk Select2
$offset = ($page - 1) * $limit;

// Build WHERE clause
$where = "status = 'aktif'";
if (!empty($search)) {
    $where .= " AND (nama LIKE '%$search%' OR nis LIKE '%$search%')";
}

// Hitung total data
$count_query = "SELECT COUNT(*) as total FROM bkcare_siswa WHERE $where";
$count_result = mysqli_query($conn, $count_query);
$total = 0;
if ($count_result) {
    $total_row = mysqli_fetch_assoc($count_result);
    $total = $total_row['total'];
}

// Ambil data
$query = "SELECT 
            id_siswa as id, 
            CONCAT(nama, ' (NIS: ', nis, ')') as text,
            nis,
            nama,
            '-' as kelas
          FROM bkcare_siswa 
          WHERE $where
          ORDER BY nama ASC
          LIMIT $limit OFFSET $offset";

$result = mysqli_query($conn, $query);

if (!$result) {
    echo json_encode(['results' => [], 'pagination' => ['more' => false]]);
    exit;
}

// Format hasil untuk Select2
$results = [];
while ($row = mysqli_fetch_assoc($result)) {
    $results[] = [
        'id' => $row['id'],
        'text' => $row['text'],
        'nis' => $row['nis'],
        'nama' => $row['nama'],
        'kelas' => $row['kelas']
    ];
}

// Response untuk Select2
$response = [
    'results' => $results,
    'pagination' => [
        'more' => ($page * $limit) < $total
    ]
];

echo json_encode($response);
?>