<?php
// admin/api_cari_barang_admin.php — cari barang via AJAX untuk admin
require_once '../includes/config.php';
require_once '../includes/auth.php';

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

$q      = trim($_GET['q']   ?? '');
$kat    = (int)($_GET['kat'] ?? 0);
$sort   = $_GET['sort'] ?? 'nama';
$dir    = ($_GET['dir'] ?? 'asc') === 'desc' ? 'DESC' : 'ASC';

$sortAllow = [
    'kode'      => 'b.kode',
    'nama'      => 'b.nama',
    'kategori'  => 'k.nama',
    'stok'      => 'b.stok',
    'harga_jual'=> 'b.harga_jual',
];
$orderCol = $sortAllow[$sort] ?? 'b.nama';

$sql    = "SELECT b.id, b.kode, b.nama, b.harga_beli, b.harga_jual,
                  b.stok, b.satuan, b.kategori_id,
                  COALESCE(k.nama,'Tanpa Kategori') AS kat_nama
           FROM barang b
           LEFT JOIN kategori k ON b.kategori_id = k.id
           WHERE b.aktif = 1";
$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 $orderCol $dir LIMIT 100";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
echo json_encode($stmt->fetchAll());
