-- Risk Matrix form and modal

-- Create form for risk matrix entries
INSERT INTO forms (id, name, description, mapped_table, tenant_id, branch_id)
SELECT 58, 'Risk Matrix Entry', 'Risk matrix values', 'ohs_risk_matrices', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 58);

-- Form fields
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 58, 'severity', 'severity', 'severity', (SELECT id FROM element_types WHERE name='number' LIMIT 1), 1
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 58 AND field_name = 'severity');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 58, 'probability', 'probability', 'probability', (SELECT id FROM element_types WHERE name='number' LIMIT 1), 2
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 58 AND field_name = 'probability');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 58, 'risk_value', 'risk_value', 'risk_value', (SELECT id FROM element_types WHERE name='number' LIMIT 1), 3
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 58 AND field_name = 'risk_value');

-- Default table view
INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 58, 'Default', '["severity","probability","risk_value"]', 'severity', 'ASC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 58 AND name = 'Default');

-- Risk Matrix Manager modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description)
SELECT 'Risk Matrix Manager',
       '{"title":"Risk Matrix Manager","header":[{"type":"button","label":"Add Entry","formName":"Risk Matrix Entry"}],"body":[{"type":"table","options":{"tableName":"ohs_risk_matrices","showGlobalSearch":false,"rowClick":"selectRecord","editFormId":58}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
       NULL, NULL, 'fa-table-cells', 'Risk Matrix Manager', 'Risk Matrix Manager'
WHERE NOT EXISTS (SELECT 1 FROM ui_modals WHERE name = 'Risk Matrix Manager');
