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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id']) || (int)$_SESSION['user_id'] === 0) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Phiên làm việc đã hết hạn. Vui lòng đăng nhập lại.']);
    exit();
}

$response = ['status' => 'error', 'message' => 'Có lỗi xảy ra', 'data' => []];

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

$sql = "SELECT 
            p.id, 
            p.prd_name as name, 
            p.prd_sls as stock, 
            IF(p.prd_average_cost > 0, p.prd_average_cost, p.prd_origin_price) as cost_price, 
            p.prd_sell_price as sell_price 
        FROM cms_products p 
        WHERE (p.prd_name LIKE ? OR p.prd_code LIKE ?) 
        AND p.deleted = 0 
        AND p.prd_status = 1 
        ORDER BY p.prd_name ASC 
        LIMIT 100";

$stmt = $conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("ss", $searchTermWildcard, $searchTermWildcard);
    $stmt->execute();
    $result = $stmt->get_result();
    $products = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    $response['status'] = 'success';
    $response['message'] = 'Lấy dữ liệu thành công';
    $response['data'] = $products;
} else {
    $response['message'] = 'Lỗi truy vấn CSDL.';
}

echo json_encode($response);
?>