<?php
header('Content-Type: application/json');
require_once 'aksi/koneksi.php';

$draw = isset($_GET['draw']) ? intval($_GET['draw']) : 1;
$start = isset($_GET['start']) ? intval($_GET['start']) : 0;
$length = isset($_GET['length']) ? intval($_GET['length']) : 10;

$data = [];
$totalRecords = 0;

if ($conn) {
    // 1. Hitung total data
    $countQuery = mysqli_query($conn, "SELECT COUNT(*) as total FROM barang");
    $countResult = mysqli_fetch_assoc($countQuery);
    $totalRecords = $countResult ? (int)$countResult['total'] : 0;

    // 2. Ambil data asli dengan limit dan offset
    $sql = "SELECT barang_nama FROM barang LIMIT $start, $length";
    $result = mysqli_query($conn, $sql);
    
    if ($result) {
        // HANYA ADA SATU LOOP WHILE DI SINI
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = [
                $row['barang_nama'],
                '<button type="button" class="btn btn-primary btn-sm btn-pilih">Pilih</button>'
            ];
        }
    }
}

echo json_encode([
    "draw" => $draw,
    "recordsTotal" => $totalRecords,
    "recordsFiltered" => $totalRecords,
    "data" => $data
]);
exit;
?>