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

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

$type    = trim($_GET['type'] ?? '');
$query   = trim($_GET['query'] ?? '');
$item_id = (int)($_GET['item_id'] ?? 0);

// Get all serials for selected item
if ($type === 'serials_by_item' && $item_id > 0) {
    $stmt = $conn->prepare("
        SELECT serial_number 
        FROM inventory_serials 
        WHERE inventory_id = ? 
          AND (status = 'In Stock' OR status IS NULL)
        ORDER BY serial_number ASC
    ");
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $serials = [];
    while ($row = $result->fetch_assoc()) {
        $serials[] = $row['serial_number'];
    }
    
    echo json_encode(['success' => true, 'serials' => $serials]);
    exit;
}

// Model or Serial Search
if (strlen($query) < 2 || !in_array($type, ['model', 'serial'])) {
    echo json_encode(['success' => false, 'items' => []]);
    exit;
}

if ($type === 'model') {
    $stmt = $conn->prepare("
        SELECT id, name, model_no, uom, hsn_sac, description, current_stock 
        FROM inventory_master 
        WHERE model_no LIKE ? 
        ORDER BY model_no ASC LIMIT 12
    ");
} else {
    $stmt = $conn->prepare("
        SELECT im.id, im.name, im.model_no, im.uom, im.hsn_sac, 
               im.description, im.current_stock, ins.serial_number
        FROM inventory_serials ins
        JOIN inventory_master im ON im.id = ins.inventory_id
        WHERE ins.serial_number LIKE ? 
          AND (ins.status = 'In Stock' OR ins.status IS NULL)
        ORDER BY ins.serial_number ASC LIMIT 12
    ");
}

$search = "%" . $query . "%";
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();

$items = [];
while ($row = $result->fetch_assoc()) {
    $items[] = $row;
}

echo json_encode([
    'success' => !empty($items),
    'type'    => $type,
    'items'   => $items
]);

$stmt->close();
$conn->close();
?>