<?php
require_once("../config/config.php");

$name = trim($_GET['name'] ?? '');

if (strlen($name) < 2) {
    echo json_encode([]);
    exit;
}

header('Content-Type: application/json');

// Search in name OR model_no (better matching)
$stmt = $conn->prepare("
    SELECT 
        id,
        sku,
        name,
        description,
        hsn_sac,
        category,
        uom,
        model_no,
        supplier_vendor,
        current_stock,
        reorder_level
    FROM inventory_master 
    WHERE (name LIKE ? OR model_no LIKE ?) 
    ORDER BY name ASC 
    LIMIT 15
");

$like = "%$name%";
$stmt->bind_param("ss", $like, $like);
$stmt->execute();
$result = $stmt->get_result();

$items = [];

while ($row = $result->fetch_assoc()) {
    $inventory_id = $row['id'];

    // Fetch ONLY In-Stock Serial Numbers
    $serial_stmt = $conn->prepare("
        SELECT serial_number 
        FROM inventory_serials 
        WHERE inventory_id = ? 
          AND (status = 'In Stock' OR status IS NULL OR status = '')
        ORDER BY serial_number ASC
    ");
    $serial_stmt->bind_param("i", $inventory_id);
    $serial_stmt->execute();
    $serial_result = $serial_stmt->get_result();

    $serials = [];
    while ($s = $serial_result->fetch_assoc()) {
        $serials[] = $s['serial_number'];
    }

    $row['serials']      = $serials;
    $row['serial_count'] = count($serials);
    $row['in_stock']     = $row['current_stock'] > 0 ? 'Yes' : 'No';

    $items[] = $row;
}

echo json_encode($items, JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR);

$conn->close();
?>