SELECT 'tab' AS component, TRUE AS center;

SELECT title
, lower(title) AS id
, $title = title AS active
, lower(title)||'.sql' AS link
FROM (
  SELECT name FROM sqlpage_pages
) AS tabs(title)

SELECT 'form' AS component
, 'filter' AS id
, 'get' AS method
, '' AS title
, '' AS validate
;

SELECT 'hidden' AS type
, 'title' AS name
, $title AS value
;

SELECT j.name
--, fo.j#>>'{options}' AS label
, j.label
, COALESCE(c.type, j.type) AS type
, j.dropdown AS dropdown
, j.multiple
, COALESCE(c.width, j.width) AS width
, o.j#>'{options}' AS options
, COALESCE(j.value, v.value) AS value
, CASE j.type
    WHEN 'checkbox' THEN v.value::bool
    ELSE NULL
  END AS checked
, j.formaction
FROM json_populate_recordset(null::sqlpage_filter_type, sqlpage.read_file_as_text('sqlpage/json/filters.json')::json) j
LEFT JOIN json_populate_recordset(null::sqlpage_filter_type, $filter_config::json) c
USING (name)
LEFT JOIN json_array_elements($filter_options::json) o(j)
ON (o.j#>>'{name}') = j.name
LEFT JOIN json_each_text(sqlpage.variables()::json) v(key, value)
ON v.key = j.name
;
