SELECT 'header' AS type,
'Location Information' AS label;

-- SET variables FIRST, with proper type casting
SET existing_site_id = (
    SELECT id
    FROM site
    WHERE id = CASE
        WHEN :site_name IS NOT NULL AND :site_name ~ '^[0-9]+$' THEN CAST(:site_name AS INT)
        ELSE NULL
    END
);

SET site_loc_name = (
    COALESCE((SELECT loc_name
    FROM site
    WHERE id = CAST($existing_site_id AS INTEGER))::TEXT,:site_name)  -- Cast to INTEGER for comparison
);

-- Site Name dropdown
SELECT
    'site_name' AS name,
    'Site Name' AS label,
    'select' AS type,
    TRUE as create_new,
    TRUE AS dropdown,
    TRUE AS required,
    'Type the Site Name' as empty_option,
    3 AS width,
    NOT ($action IN ('Edit', 'INSERT')) AS disabled,
    $site_loc_name AS value,
    (SELECT json_agg(json_build_object('label', loc_name, 'value', id) ORDER BY loc_name) FROM site) AS options;

-- Country dropdown
SELECT 'site_country' AS name,
       'Country' AS label,
       'select' AS type,
       3 AS width,
       TRUE AS required,
       TRUE AS dropdown,
       'Select a Country' AS empty_option,
       NOT ($action IN ('Edit', 'INSERT')) AS disabled,
       COALESCE(
           NULLIF(:site_country, ''),
           (SELECT s.country_code FROM plot p JOIN site s ON p.site_id = s.id WHERE p.id = CAST($id AS INTEGER))
       ) AS value,
       (
         SELECT json_agg(json_build_object(
           'label', ci.short_name_en || ' (' || ci.id || ')',
           'value', ci.id
         ) ORDER BY ci.short_name_en)
         FROM country_info ci
       ) AS options;

-- Display fields
SELECT
    'site_name_valeu' AS name,
    'Site Name' AS label,
    'text' AS type,
    3 AS width,
    $site_loc_name AS value;

SELECT
    'site_id_valeu' AS name,
    'Site ID' AS label,
    'text' AS type,
    3 AS width,
    $existing_site_id AS value;