-- Ensure Case Invoice form stores reference_id from modal prefill
UPDATE form_elements
SET label = 'reference_id',
    type_id = (SELECT id FROM element_types WHERE name='hidden' LIMIT 1),
    options_table = NULL,
    options_label_column = NULL,
    options_value_column = NULL,
    order_index = 1
WHERE form_id IN (SELECT id FROM forms WHERE name='Case Invoice')
  AND field_name = 'reference_id';

INSERT INTO form_elements (form_id,label,field_name,data_column,type_id,order_index)
SELECT id, 'reference_id', 'reference_id', 'reference_id',
       (SELECT id FROM element_types WHERE name='hidden' LIMIT 1), 1
FROM forms f
WHERE f.name = 'Case Invoice'
  AND NOT EXISTS (
    SELECT 1 FROM form_elements fe
    WHERE fe.form_id = f.id AND fe.field_name = 'reference_id'
  );
