-- Admins form and modal

-- Create Admin form if it doesn't exist
INSERT INTO forms (id, name, description, mapped_table, tenant_id, branch_id)
SELECT 40, 'Admin', 'Admin user', 'users', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 40);

-- Form fields
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 40, 'full_name', 'full_name', 'full_name', (SELECT id FROM element_types WHERE name='text' LIMIT 1), 1
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 40 AND field_name='full_name');

INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 40, 'email', 'emails', 'emails', (SELECT id FROM element_types WHERE name='text-multiple' LIMIT 1), 2
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 40 AND field_name='email');

INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 40, 'phones', 'phones', 'phones', (SELECT id FROM element_types WHERE name='text-multiple' LIMIT 1), 3
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 40 AND field_name='phones');

INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 40, 'password', 'password', 'password', (SELECT id FROM element_types WHERE name='text' LIMIT 1), 4
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 40 AND field_name='password');

INSERT INTO form_elements (
    form_id, label, field_name, data_column, type_id,
    options_table, options_label_column, options_value_column, order_index)
SELECT 40, 'tenant_id', 'tenant_id', 'tenant_id',
    (SELECT id FROM element_types WHERE name='dropdown' LIMIT 1),
    'tenants', 'name', 'id', 5
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 40 AND field_name='tenant_id');

INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 40, 'Default', '["full_name","email","tenant_id"]', 'full_name', 'ASC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 40 AND name='Default');

-- Admins modal definition
INSERT INTO ui_modals (name, config, tenant_id, branch_id)
SELECT 'Admins', '{"title":"Admins","header":[{"type":"button","label":"Add Admin","formName":"Admin"}],"body":[{"type":"table","options":{"tableName":"users","filters":{"is_admin":"1"},"showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' , NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM ui_modals WHERE name = 'Admins');
