<?php
require_once __DIR__ . '/../core/init.php';
header('Content-Type: application/json; charset=utf-8');

$term = $_GET['term'] ?? '';
$searchTermWildcard = "%" . $term . "%";

// Sử dụng logic IF để đảm bảo luôn có giá vốn để hiển thị
$sql = "SELECT 
            p.ID as id, 
            p.prd_code as code, 
            p.prd_name as name, 
            p.prd_sell_price as sell_price, 
            p.prd_sls as stock,
            IF(p.prd_average_cost > 0, p.prd_average_cost, p.prd_origin_price) as cost_price
        FROM cms_products p
        WHERE (p.prd_name LIKE ? OR p.prd_code LIKE ?) AND p.deleted = 0 
        ORDER BY p.prd_name ASC 
        LIMIT 50";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $searchTermWildcard, $searchTermWildcard);
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

echo json_encode(['status' => 'success', 'data' => $data]);
?>