CREATE OR REPLACE FUNCTION public.search_inventory (search text)
	RETURNS SETOF inventory
	LANGUAGE plpgsql
	STABLE
	AS $function$
BEGIN
	IF search = '' THEN
		RETURN query
		SELECT
			*
		FROM
			inventory;
	ELSE
		RETURN query
		SELECT
			*
		FROM
			inventory  inner JOIN billlines ON inventory.billlineid = billlines.id
			inner JOIN bills ON billlines.billid = bills.id
			inner JOIN vendors ON bills.vendorid = vendors.id
	
		WHERE
			 inventory.line_desc ILIKE '%' || search || '%'
			OR bills.invoice_number ILIKE '%' || search || '%'
			OR vendors.name ILIKE '%' || search || '%'
		ORDER BY
			inventory.line_desc ILIKE '%' || search || '%'
			OR NULL,
			bills.invoice_number ILIKE '%' || search || '%'
			OR NULL,
			vendors.name ILIKE '%' || search || '%'
			OR NULL;
	END IF;
END
$function$;
