<?php
// kasir/api_cari_barang.php — cari barang via AJAX
require_once '../includes/config.php';
require_once '../includes/auth.php';

header('Content-Type: application/json');
if (!isLoggedIn()) { echo json_encode([]); exit; }

$q   = trim($_GET['q']   ?? '');
$kat = (int)($_GET['kat'] ?? 0);

if (strlen($q) < 1 && !$kat) {
    echo json_encode([]); exit;
}

$sql    = "SELECT b.id, b.kode, b.nama, b.harga_jual, b.stok, b.kategori_id,
                  COALESCE(k.nama,'Lainnya') AS kat_nama
           FROM barang b
           LEFT JOIN kategori k ON b.kategori_id = k.id
           WHERE b.aktif=1 AND b.stok > 0";
$params = [];

if ($q) {
    $sql    .= " AND (b.nama LIKE ? OR b.kode LIKE ?)";
    $params[] = "%$q%";
    $params[] = "%$q%";
}
if ($kat) {
    $sql    .= " AND b.kategori_id = ?";
    $params[] = $kat;
}

$sql .= " ORDER BY b.nama ASC LIMIT 100";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
echo json_encode($stmt->fetchAll());
