-- PAYE deduction settings for Fiji
-- Applies separately to residents and non-residents
-- Values not provided default to 0 or NULL as appropriate

INSERT INTO deduction_settings (
    name, start_salary, end_salary, base_amount, percent,
    company_contribution, start_date, end_date, applies_to,
    scope, country_id, tenant_id, branch_id
) VALUES
    ('PAYE', 0, 30000.0, 0, 0, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 30001, 50000.0, 0, 18, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 50001, 270000.0, 3600, 20, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 270001, 300000.0, 47600, 33, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 300001, 350000.0, 57500, 34, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 350001, 400000.0, 74500, 35, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 400001, 450000.0, 92000, 36, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 450001, 500000.0, 110000, 37, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 500001, 1000000.0, 128500, 38, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 1000001, NULL, 318500, 39, 0, NULL, NULL, 'resident', 'country', 1, NULL, NULL),
    ('PAYE', 0, 30000.0, 0, 20, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 30001, 50000.0, 6000, 20, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 50001, 270000.0, 10000, 20, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 270001, 300000.0, 54000, 33, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 300001, 350000.0, 63900, 34, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 350001, 400000.0, 80900, 35, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 400001, 450000.0, 98400, 36, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 450001, 500000.0, 116400, 37, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 500001, 1000000.0, 134900, 38, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('PAYE', 1000001, NULL, 324900, 39, 0, NULL, NULL, 'non_resident', 'country', 1, NULL, NULL),
    ('FNPF', 0, NULL, 0, 8, 10, NULL, NULL, 'resident', 'country', 1, NULL, NULL);


-- Default application settings
INSERT INTO settings (
    name, value, category, tenant_id, branch_id
) VALUES
    ('default_currency', 'FJD', 'finance', NULL, NULL),
    ('timezone', 'Pacific/Fiji', 'system', 1, 1),
    ('policy_publish_webhook', '', 'system', NULL, NULL),
    ('policy_update_webhook', '', 'system', NULL, NULL);


-- Default hazard types
INSERT INTO ohs_hazard_types (name, tenant_id, branch_id) VALUES
    ('Physical', NULL, NULL),
    ('Chemical', NULL, NULL),
    ('Biological', NULL, NULL),
    ('Psychosocial', NULL, NULL),
    ('Ergonomic', NULL, NULL);

-- Default incident types
INSERT INTO ohs_incident_types (name, form_id, tenant_id, branch_id) VALUES
    ('Injury', 20, NULL, NULL),
    ('Property Damage', 13, NULL, NULL),
    ('Environmental', 14, NULL, NULL),
    ('Near Miss', 15, NULL, NULL),
    ('First Aid', 16, NULL, NULL),
    ('Medical Treatment', 17, NULL, NULL),
    ('LTI', 18, NULL, NULL),
    ('Fatality', 19, NULL, NULL);


-- Default permit types
INSERT INTO permit_types (name)
VALUES
    ('Hot Work'),
    ('Confined Space Entry'),
    ('Electrical Work'),
    ('Working at Heights'),
    ('Excavation'),
    ('General Work'),
    ('Cold Work');


-- Default form element types
INSERT INTO element_types (tenant_id, branch_id, name, html_type, sql_type)
VALUES
    (NULL, NULL, 'text', 'text', 'VARCHAR(255)'),
    (NULL, NULL, 'number', 'number', 'INT'),
    (NULL, NULL, 'date', 'date', 'DATE'),
    (NULL, NULL, 'dropdown', 'select', 'VARCHAR(255)'),
    (NULL, NULL, 'checkbox', 'checkbox', 'BOOLEAN');


-- Additional types required by default forms
INSERT INTO element_types (tenant_id, branch_id, name, html_type, sql_type)
VALUES
    (NULL, NULL, 'textarea', 'textarea', 'TEXT'),
    (NULL, NULL, 'file', 'file', 'VARCHAR(255)'),
    (NULL, NULL, 'datetime', 'datetime-local', 'TIMESTAMP');



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (4, 'Default', '["status","date","classification","location"]', 'date', 'DESC');


-- Default table views for other OHS lists
INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES
    (5, 'Default', '["date","location","inspector_id"]', 'date', 'DESC'),
    (6, 'Default', '["title","description","doc_path","location","department_id","analysis_date","review_date"]', 'title', 'ASC');





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



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


INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (12, 'Default', '["project_id","course_id"]', 'project_id', 'ASC');


INSERT INTO table_views (form_id, tenant_id, branch_id, name, columns, sort_by, sort_dir) VALUES
    (20, 1, NULL, 'Default', '["status","date","classification","location","days_lost","rtw_date","restricted_duty_notes"]', 'date', 'DESC')
ON CONFLICT DO NOTHING;


INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 13, 'Default', '["user_id","clock_type","location_id","clocked_at"]', 'clocked_at', 'DESC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 13 AND name = 'Default');



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 14, 'Default', '["user_id","date","standard_hours","overtime_hours","break_hours","approved"]', 'date', 'DESC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 14 AND name = 'Default');



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 15, 'Default', '["permit_type_id","applicant_id","status","created_at"]', 'created_at', 'DESC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 15 AND name = 'Default');



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 55, 'Default', '["inspector_id","scheduled_for","result","notes","hours_logged"]', 'scheduled_for', 'DESC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 55 AND name = 'Default');


-- Default groups
INSERT INTO groups (name, description)
VALUES
  ('Drivers', 'Drivers allowed to operate fleet vehicles'),
  ('Mechanics', 'Vehicle maintenance team'),
  ('Fleet Managers', 'Fleet management supervisors'),
  ('Fleet Engineers', 'Fleet maintenance crew');


-- Initial Super Admin
INSERT INTO users (id, full_name, password, locations, tenant_id, branch_id)
VALUES (1, 'Super Admin', '$2y$10$PXEdpEbxI5c11/tC3UdC6OrZr7V2MsHAatf5C6LRzRV/goxQDPTl.', NULL, NULL, NULL);


INSERT INTO user_emails (user_id, email)
VALUES (1, 'admin@example.com');


INSERT INTO user_group_memberships (user_id, group_id, role)
VALUES (1, 1, 'Super Admin');


INSERT INTO roles_permissions (role, tenant_id, branch_id, inheritedFrom, permissions, updatedAt, createdBy)
VALUES ('Super Admin', NULL, NULL, NULL, '{"*": ["*"]}', NOW(), 1);


INSERT INTO roles_permissions (role, tenant_id, branch_id, inheritedFrom, permissions, updatedAt, createdBy)
VALUES (
    'Admin',
    NULL,
    NULL,
    NULL,
    '{"tenants": ["*"], "admins": ["*"], "theme": ["current"], "users": ["me"], "ui_modals": ["*"]}',
    NOW(),
    1
);


SELECT setval('users_id_seq', (SELECT MAX(id) FROM users));



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (29, 'Default', '["vehicle_number","make","model","year"]', 'vehicle_number', 'ASC');


INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (30, 'Default', '["vehicle_id","driver_id","trip_date","start_time","end_time","start_mileage","end_mileage","distance_km","status"]', 'start_time', 'DESC');




INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (31, 'Default', '["name","make","model","km_interval","month_interval"]', 'name', 'ASC');


-- Service Types modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Service Types',
  '{"title":"Service Types","header":[{"type":"button","label":"Add Service Type","formName":"Service Type"}],"body":[{"type":"table","options":{"tableName":"service_types","showGlobalSearch":false,"addButton":false,"editFormId":31}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-wrench',
  'Service Types',
  'Service Types'
);


-- Vehicles modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Vehicles',
  '{"title":"Vehicles","header":[{"type":"button","label":"Add Vehicle","formName":"Vehicle Registration"}],"body":[{"type":"table","options":{"tableName":"vehicles","showGlobalSearch":false,"addButton":false,"editFormId":29}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-car',
  'Vehicles',
  'Vehicles'
);


-- Attendance modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Attendance',
  '{"title":"Attendance","body":[{"type":"table","options":{"tableName":"attendance","searchInputTypes":{"employee":"text","date":"date","timeIn":"time","timeOut":"time","timeInLat":"number","timeInLng":"number","timeOutLat":"number","timeOutLng":"number"},"columnsToShow":["employee","date","timeIn","timeOut","hoursWorked","overtime"]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-user-check',
  'Attendance',
  'Attendance'
);


-- Attendance Dashboard modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Attendance Dashboard',
  '{"title":"Attendance Dashboard","body":[{"type":"html","id":"attendanceDash","html":"<div class=\"grid grid-cols-2 gap-4\"><div class=\"bg-base-100 rounded-lg shadow p-4 text-center\"><h3 class=\"text-sm font-medium\">Clocked In</h3><p id=\"adClockIn\" class=\"text-2xl font-bold\">0</p></div><div class=\"bg-base-100 rounded-lg shadow p-4 text-center\"><h3 class=\"text-sm font-medium\">Clocked Out</h3><p id=\"adClockOut\" class=\"text-2xl font-bold\">0</p></div></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-chart-pie',
  'Attendance Dashboard',
  'Attendance Dashboard'
);


-- Time Clocks modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Time Clocks',
  '{"title":"Time Clocks","mapLibraries":{"provider":"google"},"body":[{"type":"table","options":{"tableName":"time_clocks","searchInputTypes":{"user_id":"number","clock_type":{"type":"select","options":["in","out"]},"lat":"number","lng":"number","location_id":"number","supervisor_id":"number","supervisor_type":"text","work_id":"number","security_type":"text","clocked_at":"datetime-local"},"columnsToShow":["user_id","clock_type","location_id","stationApproved","supervisor_id","supervisor_type","work_id","security_type","clocked_at"]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-user',
  'Time Clocks',
  'Time Clocks'
);


-- Time Clock Locations modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Time Clock Locations',
  '{"title":"Time Clock Locations","mapLibraries":{"provider":"google","libraries":"drawing"},"body":[{"type":"table","options":{"tableName":"time_clock_locations","searchInputTypes":{"name":"text","shape":"text","radius_m":"number","assigned_to_type":"text"},"columnsToShow":["name","shape","radius_m","assigned_to_type"]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-map-location-dot',
  'Time Clock Locations',
  'Time Clock Locations'
);


-- Timesheet Approval modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Timesheet Approval',
  '{"title":"Timesheet Approval","body":[{"type":"table","options":{"tableName":"pending_timesheets","tableUrl":"../api/timesheets/pending","columnsToShow":["id","user_id","date","standard_hours","overtime_hours","break_hours"],"apiRowActions":[{"buttonText":"Approve","apiUrl":"../api/timesheets/approve/{id}"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-check',
  'Timesheet Approval',
  'Timesheet Approval'
);


-- Clock Adjustment modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Clock Adjustment',
  '{"title":"Clock Adjustment","body":[{"type":"table","options":{"tableName":"time_clocks","searchInputTypes":{"clocked_at":"datetime-local","approval_comment":"text"},"columnsToShow":["user_id","clock_type","clocked_at","approval_comment"],"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clock',
  'Clock Adjustment',
  'Clock Adjustment'
);


-- Timesheet Summary modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Timesheet Summary',
  '{"title":"Timesheet Summary","body":[{"type":"table","options":{"tableName":"timesheet_summary","tableUrl":"../api/timesheets/summary","columnsToShow":["user_id","approved_hours","rejected_hours","comments"],"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-list-check',
  'Timesheet Summary',
  'Timesheet Summary'
);



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (32, 'Default', '["name","description"]', 'name', 'ASC');


-- User Groups modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'User Groups',
  '{"title":"User Groups","header":[{"type":"button","label":"Add Group","formName":"User Group"}],"body":[{"type":"table","options":{"tableName":"groups","showGlobalSearch":true,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-users',
  'User Groups',
  'User Groups'
);



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (33, 'Default', '["user_id","group_id","role"]', 'user_id', 'ASC');


-- Group Members modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Group Members',
  '{"title":"Group Members","header":[{"type":"button","label":"Add Member","formName":"Group Member"}],"body":[{"type":"table","options":{"tableName":"user_group_memberships","showGlobalSearch":true,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-user-group',
  'Group Members',
  'Group Members'
);


-- Users modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Users',
  '{"title":"Users","header":[{"type":"button","label":"Add User","formName":"User"}],"body":[{"type":"table","options":{"tableName":"users","showGlobalSearch":true,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-users-gear',
  'Manage Users',
  'Manage Users'
);


-- Dashboard card permissions modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'dashboard_card_permissions',
  '{"title":"Dashboard Card Permissions","body":[{"type":"html","html":"<select id=\"dcpTenantSelect\"><option value=\"\">All</option></select><div class=\"tabs mb-2\" id=\"dcp-tabs\"><a class=\"tab tab-bordered tab-active\" data-tab=\"groups\">Groups</a><a class=\"tab tab-bordered\" data-tab=\"users\">Users</a></div>"},{"type":"table","id":"dcpGroups","options":{"tableName":"groups","addButton":false,"showGlobalSearch":false,"actionsHeader":"Allow"}},{"type":"table","id":"dcpUsers","options":{"tableName":"users","addButton":false,"showGlobalSearch":false,"actionsHeader":"Allow"}}],"footer":[{"type":"button","label":"Save","onClick":"saveDashboardCardPerms"},{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-id-badge',
  'Card Permissions',
  'Card Permissions'
);


-- Dashboard card permissions manager modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'dashboard_card_permissions_manager',
  '{"title":"Card Permissions Manager","body":[{"type":"html","html":"<select id=\"dcpTenantSelect\"></select><select id=\"dcpmGroupSelect\"></select><select id=\"dcpmUserSelect\"></select>"},{"type":"html","id":"dcpmCards","html":""},{"type":"html","html":"<div id=\"dcpm-detail\" class=\"hidden\"></div>"}],"footer":[{"type":"button","label":"Save","onClick":"saveCardPermissions"},{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-id-badge',
  'Card Permissions Manager',
  'Card Permissions Manager'
);


-- Workflow Builder modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'workflow_builder',
  '{"title":"Workflow Builder","body":[{"type":"html","id":"wfBuilderContainer","html":""}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-sitemap',
  'Workflow Builder',
  'Workflow Builder'
);


-- Trip Logs modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Trip Logs',
  '{"title":"Trip Logs","header":[{"type":"button","label":"Map View","onClick":"openTripMapView"}],"body":[{"type":"table","options":{"tableName":"vehicle_trips","addButton":false,"rowClick":"selectRecord","showGlobalSearch":true}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-road',
  'Trip Logs',
  'Trip Logs'
);




INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (34, 'Default', '["vehicle_id","report_type","status"]', 'created_at', 'DESC');



-- Vehicle Reports modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Vehicle Reports',
  '{"title":"Vehicle Reports","header":[{"type":"button","label":"Add Report","formName":"Vehicle Issue Report"},{"type":"button","label":"Detail View","onClick":"openSelectedDetail"}],"body":[{"type":"table","id":"vehicleReports","options":{"tableName":"vehicle_reports","showGlobalSearch":false,"addButton":false,"rowClick":"selectRecord","filters":{"status":"open"},"apiRowActions":[{"buttonText":"Accept","apiUrl":"../api/vehicle_reports/{id}/assign"},{"buttonText":"Confirm","apiUrl":"../api/vehicle_reports/{id}/confirm"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-list',
  'Vehicle Reports',
  'Vehicle Reports'
);


-- Fleet Calendar modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Fleet Calendar',
  '{"title":"Fleet Calendar","body":[{"type":"calendar","options":{"source":"fleet","showAddButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-calendar-days',
  'Fleet Calendar',
  'Fleet Calendar'
);


-- Fleet Analytics modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Fleet Analytics',
  '{"title":"Fleet Analytics","body":[{"type":"html","id":"fleetAnalyticsRoot","html":"<div id=\"fleetAnalytics\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-truck-fast',
  'Fleet Analytics',
  'Fleet Analytics'
);


INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 42, 'Default', '["vehicle_id","start_date","end_date","reason"]', 'start_date', 'DESC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 42 AND name = 'Default');

-- Vehicle Downtime modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Vehicle Downtime',
  '{"title":"Vehicle Downtime","header":[{"type":"button","label":"Add Downtime","formName":"Vehicle Downtime"}],"body":[{"type":"table","options":{"tableName":"vehicle_downtime","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clock',
  'Vehicle Downtime',
  'Vehicle Downtime'
);


-- Table views
INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 35, 'Default', '["name","email","phone"]', 'name', 'ASC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 35 AND name = 'Default');

INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 36, 'Default', '["client_id","title","status","opened_at","closed_at"]', 'opened_at', 'DESC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 36 AND name = 'Default');


-- Case Hour form
INSERT INTO forms (id, name, description, mapped_table, tenant_id, branch_id)
SELECT 38, 'Case Hour', 'Record hours worked on a case', 'case_hours', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 38);


INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 38, 'Default', '["case_id","user_id","hours","rate","billed_to_client","approved","work_type"]', 'updatedAt', 'DESC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 38 AND name = 'Default');



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


-- Clients modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description)
SELECT 'Clients', '{"title":"Clients","header":[{"type":"button","label":"Add Client","formName":"Client"},{"type":"button","label":"Detail View","onClick":"openSelectedDetail"}],"body":[{"type":"table","options":{"tableName":"clients","showGlobalSearch":false,"addButton":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' , NULL, NULL, 'fa-users', 'Clients', 'Clients'
WHERE NOT EXISTS (SELECT 1 FROM ui_modals WHERE name = 'Clients');


-- Cases modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description)
SELECT 'Cases', '{"title":"Cases","header":[{"type":"button","label":"Add Case","formName":"Case"},{"type":"button","label":"Detail View","onClick":"openSelectedDetail"}],"body":[{"type":"table","options":{"tableName":"cases","showGlobalSearch":false,"addButton":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' , NULL, NULL, 'fa-folder-open', 'Cases', 'Cases'
WHERE NOT EXISTS (SELECT 1 FROM ui_modals WHERE name = 'Cases');



-- Case Management modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description)
SELECT 'Case Management', '{"title": "Case Management", "header": [{"type": "filter-select", "options": {"source_table": "cases", "source_column": "id", "display_column": "title", "default_label": "Select Case", "data_column": "case_id", "scope": "admin_user", "userField": "lead_rep_id"}}], "body": [{"type": "tabs", "tabs": [{"label": "Details", "elements": [{"type": "detail-view", "viewId": 2, "filterField": "case_id", "tableName": "cases"}]}, {"label": "Instructions", "elements": [{"type": "button", "label": "Add Instruction", "formName": "Case Instruction", "prefillFilter": "case_id"}, {"type": "table", "options": {"tableName": "case_instructions", "showGlobalSearch": false, "addButton": false, "filterField": "case_id"}}]}, {"label": "Documents", "elements": [{"type": "documents", "options": {"filterField": "case_id"}}]}, {"label": "Hours", "elements": [{"type": "button", "label": "Add Hour", "formName": "Case Hour", "prefillFilter": "case_id"}, {"type": "table", "options": {"tableName": "case_hours", "tableUrl": "../api/case_hours", "showGlobalSearch": false, "addButton": false, "editFormId": 38, "filterField": "case_id", "multipleSelect": true}}]}, {"label": "Expenses", "elements": [{"type": "button", "label": "Add Expense", "formName": "Case Expense", "prefillFilter": "case_id"}, {"type": "table", "options": {"tableName": "expenses", "showGlobalSearch": false, "addButton": false, "editFormId": 48, "filterField": "case_id", "multipleSelect": true}}]}, {"label": "Invoices", "elements": [{"type": "button", "label": "Create Invoice", "formName": "Case Invoice", "prefillFilter": "reference_id"}, {"type": "table", "options": {"tableName": "invoices", "showGlobalSearch": false, "addButton": false, "filterField": "reference_id"}}]}, {"label": "Payments", "elements": [{"type": "button", "label": "Record Payment", "formName": "Case Payment", "prefillFilter": "case_id"}, {"type": "table", "options": {"tableName": "payments", "showGlobalSearch": false, "addButton": false, "filterField": "case_id"}}]}]}], "footer": [{"type": "button", "label": "Close", "onClick": "closeModal"}]}', NULL, NULL, 'fa-scale-balanced', 'Case Management', 'Case Management'
WHERE NOT EXISTS (SELECT 1 FROM ui_modals WHERE name = 'Case Management');



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


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, icon, aria_label, description)
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, 'fa-user-shield', 'Admins', 'Admins'
WHERE NOT EXISTS (SELECT 1 FROM ui_modals WHERE name = 'Admins');



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


-- Default dashboard card actions
INSERT INTO ui_actions (page, action_key, button_label, button_id, workflow_event) VALUES
('Dashboard','card_permissions','Permissions','Accounts','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ActionBuilder','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Admins','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','AnalyticsDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ApplicationFieldDefs','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Applications','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ApprovalQueue','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','AttendanceDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Calendar','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CareerPaths','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CareerReadiness','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Careers','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CaseManagement','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Companies','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CompetencyLibrary','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CompetencyManagement','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CompetencyMatrix','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ComplianceCalendar','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ComplianceDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ComplianceReports','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ContractApprovals','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ContractRepository','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CountryDeductions','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CountryHolidays','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CreateUser','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CustomModule','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CustomizeDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','DeductionSettings','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Deductions','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','DigitalWallet','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Disciplinary','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','DmsAdmin','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','EmergencyPreparedness','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','EmployeeLicenses','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','EmployeeTypes','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Employees','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ExecutiveDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ExitManagement','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ExpiringDocuments','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Feedback','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','FormBuilder','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','GoalAlignment','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','GoalDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','GoalProgress','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','GoalStrategyAlignment','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','GoalTemplates','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','GoodsReceipts','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','HRPerformanceDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','HazardManagement','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','HazardTypes','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','IncidentHeatmap','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','IncidentSummaryDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','IncidentTypes','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','InterviewFeedback','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Interviews','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ItemAssignments','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','JSATrainingStatus','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','JobOpeningTemplates','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','KanbanBoard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','LeaveRequests','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','LedgerEntries','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Locations','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Logout','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ManagePolicies','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','MyGoals','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','MyPolicies','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','MyRequest','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','MyReviews','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','NearMissDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','NewHire','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','OHSAssignmentRules','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','OHSIncidents','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','OHSInspections','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','OHSInvestigationDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','OHSJSA','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','OhsReports','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','OpenPosition','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','IssuesLog','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','OvertimeSettings','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PageConfigBuilder','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PageCustomizer','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PayCycles','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Payments','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PayrollProcess','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PayrollSubmissions','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PayrollVerification','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Payslips','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PerformanceDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PerformanceManagement','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Permits','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PolicyApprovals','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Properties','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PropertyRates','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PurchaseOrders','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','PurchaseRequest','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','RFQs','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Reconciliation','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Reporting','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ReviewCalibration','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ReviewCycles','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','RiskMatrixDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','RootCauseDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','SafetyDocuments','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','SafetyInductions','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ScheduleInterviews','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','SentimentDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','SystemSettings','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TeamGoalsDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TeamLearningTracker','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Tenants','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TimeClockLocations','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TimeClocks','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Training','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TrainingCalendar','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TrainingCompletion','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TrainingDashboard','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TrainingGamification','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TrainingProfile','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','TripLogs','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','UpcomingReviews','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','Users','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','VendorInvoices','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','ViewBuilder','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','WorkflowTasks','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','procurement','dashboard.card.permissions'),
('Dashboard','card_permissions','Permissions','CardPermissionsManager','dashboard.card.permissions');


-- Default workflow to launch the Dashboard Card Permissions modal
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES (
  'Dashboard Card Permissions',
  'dashboard.card.permissions',
  '{"conditions":[]}',
  TRUE
);


INSERT INTO workflow_steps (workflow_id, step_order, step_type, config)
VALUES (
  (SELECT id FROM workflows WHERE name='Dashboard Card Permissions' LIMIT 1),
  1,
  'open_modal',
  '{"modal":"dashboard_card_permissions"}'
);

-- Default dashboard card permissions
INSERT INTO dashboard_card_permissions (card_slug, group_id)
VALUES
  ('Vehicle_Reports', (SELECT id FROM groups WHERE name='Mechanics' LIMIT 1)),
  ('Vehicle_Reports', (SELECT id FROM groups WHERE name='Fleet Managers' LIMIT 1)),
  ('Fleet_Calendar', (SELECT id FROM groups WHERE name='Fleet Managers' LIMIT 1)),
  ('Risk_Assessments', (SELECT id FROM groups WHERE name='Admin' LIMIT 1)),
  ('Risk_Assessments', (SELECT id FROM groups WHERE name='Safety Officers' LIMIT 1)),
  ('IssuesLog', (SELECT id FROM groups WHERE name='Admin' LIMIT 1));

-- Default vehicle makes and models
INSERT INTO vehicle_makes (name, tenant_id, branch_id)
VALUES ('Toyota', NULL, NULL);


INSERT INTO vehicle_models (make_id, name, tenant_id, branch_id)
VALUES ((SELECT id FROM vehicle_makes WHERE name='Toyota' LIMIT 1), 'Corolla', NULL, NULL);


-- Default vehicle service workflow to schedule maintenance after registration
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES ('Vehicle Service Setup', 'vehicle.registered', '{"conditions": []}', TRUE);


INSERT INTO workflow_steps (workflow_id, step_order, step_type, config)
VALUES (
  (SELECT id FROM workflows WHERE name='Vehicle Service Setup' LIMIT 1),
  1,
  'schedule_services',
  '{}'
);


-- Table Builder modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Table Builder',
  '{"title":"Table Builder","body":[{"type":"html","html":"<div class=\"mb-2\"><label class=\"label\">Table Name</label><input id=\"tbTableName\" class=\"input input-bordered w-full\"/></div>"},{"type":"html","html":"<div class=\"mt-4\"><button id=\"addColumnBtn\" type=\"button\" class=\"btn btn-sm mb-2\">Add Column</button><table id=\"tbColumns\" class=\"table table-sm w-full\"><thead><tr><th>Name</th><th>Type</th><th>Default</th><th>Required</th><th></th></tr></thead><tbody></tbody></table></div>"},{"type":"html","html":"<div class=\"mt-4\"><button id=\"addRelationBtn\" type=\"button\" class=\"btn btn-sm mb-2\">Add Relationship</button><table id=\"tbRelations\" class=\"table table-sm w-full\"><thead><tr><th>Column</th><th>References Table</th><th>References Column</th><th></th></tr></thead><tbody></tbody></table></div>"}],"footer":[{"type":"button","label":"Save","onClick":"submitTableDefinition"},{"type":"button","label":"Close","onClick":"closeModal"}]}' ,
  NULL,
  NULL,
  'fa-table',
  'Table Builder',
  'Table Builder'
);


-- Tenant Table Manager modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'tenant_table_manager',
  '{"title":"Tenant Table Manager","body":[{"type":"table","options":{"tableName":"tenant_tables","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-table-list',
  'Tenant Table Manager',
  'Tenant Table Manager'
);


-- Module Manager modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'module_manager',
  '{"title":"Module Manager","body":[{"type":"html","id":"moduleManagerContainer","html":""}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-cubes',
  'Module Manager',
  'Module Manager'
);


-- Vendor Quotes modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Vendor Quotes',
  '{"title":"Vendor Quotes","header":[{"type":"button","label":"Add Quote","formName":"Vendor Quote"}],"body":[{"type":"table","options":{"tableName":"vendor_quotes","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-file-lines',
  'Vendor Quotes',
  'Vendor Quotes'
);

-- Case Hour Entry modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Case Hour Entry',
  '{"title":"Case Hour Entry","header":[{"type":"button","label":"Add Hour","formId":38}],"body":[{"type":"table","options":{"tableName":"case_hours","tableUrl":"../api/case_hours","showGlobalSearch":false,"addButton":false,"editFormId":38,"editFormId":38}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-user-clock',
  'Case Hour Entry',
  'Case Hour Entry'
);


-- Workflow step type definitions
INSERT INTO workflow_step_types (type, description, metadata) VALUES
  ('start', 'Workflow entry point', '{"trigger":""}'),
  ('save_record', 'Insert or update a record', '{"table":"","data":{},"match":{}}'),
  ('sms', 'Send an SMS notification', '{"to":"","message":""}'),
  ('http_request', 'HTTP request to external API', '{"url":"","method":"GET"}'),
  ('alert', 'Send a push notification', '{"title":"","body":""}'),
  ('create_task', 'Add a kanban board task', '{"column_id":0,"title":""}'),
  ('add_calendar_event', 'Create a calendar event', '{"title":"","start_time":"","end_time":""}'),
  ('open_form', 'Open a form for the user', '{"form_id":0}'),
  ('condition', 'Evaluate workflow conditions', '{"conditions":[]}'),
  ('query_budget', 'Load remaining budget for a category', '{"category":"","context_key":"budget_amount"}'),
  ('map_fields', 'Copy values between context fields', '{"map":{}}'),
  ('load_record', 'Load a record into context', '{"table":"","id_key":"id","context_key":"record"}'),
  ('query_records', 'Query records from a table', '{"table":"","where":{},"context_key":"records"}'),
  ('for_each_record', 'Execute steps for each record', '{"list_key":"records","steps":[]}'),
  ('queue_notification', 'Queue a notification payload', '{"entity":"","record_id":"","event_type":"insert","payload":null}');


-- User-based forms for personnel


INSERT INTO table_views (form_id,name,columns,sort_by,sort_dir) VALUES
  (45,'Default','["full_name","email","phone"]','full_name','ASC');

INSERT INTO ui_modals (name,config,tenant_id,branch_id,icon,aria_label,description) VALUES
  ('Drivers','{"title":"Drivers","header":[{"type":"button","label":"Add Driver","formName":"Driver"}],"body":[{"type":"table","options":{"tableName":"users","showGlobalSearch":false,"filterField":"groups.name","filterValue":"Drivers"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-id-card','Drivers','Drivers');



INSERT INTO table_views (form_id,name,columns,sort_by,sort_dir) VALUES
  (37,'Default','["full_name","emails","phones"]','full_name','ASC');

INSERT INTO ui_modals (name,config,tenant_id,branch_id,icon,aria_label,description) VALUES
  ('Lawyers','{"title":"Lawyers","header":[{"type":"button","label":"Add Lawyer","formName":"Lawyer"}],"body":[{"type":"table","options":{"tableName":"users","showGlobalSearch":false,"filterField":"groups.name","filterValue":"Lawyers"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-gavel','Lawyers','Lawyers');



INSERT INTO table_views (form_id,name,columns,sort_by,sort_dir) VALUES
  (46,'Default','["full_name","email","phone"]','full_name','ASC');

INSERT INTO ui_modals (name,config,tenant_id,branch_id,icon,aria_label,description) VALUES
  ('Fleet Engineers','{"title":"Fleet Engineers","header":[{"type":"button","label":"Add Fleet Engineer","formName":"Fleet Engineer"}],"body":[{"type":"table","options":{"tableName":"users","showGlobalSearch":false,"filterField":"groups.name","filterValue":"Fleet Engineers"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-screwdriver-wrench','Fleet Engineers','Fleet Engineers');


INSERT INTO table_views (form_id,name,columns,sort_by,sort_dir) VALUES
  (47,'Default','["case_id","instruction_date","instruction"]','instruction_date','DESC');


INSERT INTO table_views (form_id,name,columns,sort_by,sort_dir) VALUES
  (48,'Default','["case_id","expense_date","amount","employee_id"]','expense_date','DESC');


INSERT INTO table_views (form_id,name,columns,sort_by,sort_dir) VALUES
  (49,'Default','["reference_id","invoice_number","invoice_date","amount","status"]','invoice_date','DESC');


-- Case Invoice Preview modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id) VALUES (
  'Case Invoice Preview',
  '{"title":"Case Invoice","body":[{"type":"html","id":"ciPreview","html":""},{"type":"form","formName":"Case Invoice"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL
);

INSERT INTO table_views (form_id,name,columns,sort_by,sort_dir) VALUES
  (50,'Default','["invoice_id","payment_date","amount","payment_method"]','payment_date','DESC');


INSERT INTO table_views (form_id,name,columns,sort_by,sort_dir) VALUES
  (51,'Default','["case_id","comments"]','case_id','ASC');

INSERT INTO form_buttons (form_id,label,action_type,action_payload,order_index) VALUES
  (51,'Approve','workflow',(SELECT id FROM workflows WHERE trigger_event='case.approved' LIMIT 1),1),
  (51,'Reject','workflow',(SELECT id FROM workflows WHERE trigger_event='case.rejected' LIMIT 1),2);



INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES
  ('Driver Created', 'driver.created', '{"conditions":[]}', TRUE),
  ('Lawyer Created', 'lawyer.created', '{"conditions":[]}', TRUE),
  ('Fleet Engineer Created', 'fleet_engineer.created', '{"conditions":[]}', TRUE);


-- Driver workflow steps
INSERT INTO workflow_steps (workflow_id, step_order, step_type, config) VALUES
  ((SELECT id FROM workflows WHERE name='Driver Created'),1,'map_fields','{"map":{"user_id":"id"}}'),
  ((SELECT id FROM workflows WHERE name='Driver Created'),2,'ensure_group','{"name":"Drivers"}'),
  ((SELECT id FROM workflows WHERE name='Driver Created'),3,'save_record','{"table":"user_group_memberships","data":{"user_id":"{user_id}","group_id":"{group_id}","role":"Driver"}}'),
  ((SELECT id FROM workflows WHERE name='Driver Created'),4,'load_record','{"table":"users","id_key":"user_id","context_key":"user"}'),
  ((SELECT id FROM workflows WHERE name='Driver Created'),5,'queue_notification','{"entity":"users","record_id":"{user_id}","event_type":"insert","payload":"{user}"}');


-- Lawyer workflow steps
INSERT INTO workflow_steps (workflow_id, step_order, step_type, config) VALUES
  ((SELECT id FROM workflows WHERE name='Lawyer Created'),1,'map_fields','{"map":{"user_id":"id"}}'),
  ((SELECT id FROM workflows WHERE name='Lawyer Created'),2,'ensure_group','{"name":"Lawyers"}'),
  ((SELECT id FROM workflows WHERE name='Lawyer Created'),3,'save_record','{"table":"user_group_memberships","data":{"user_id":"{user_id}","group_id":"{group_id}","role":"Lawyer"}}'),
  ((SELECT id FROM workflows WHERE name='Lawyer Created'),4,'load_record','{"table":"users","id_key":"user_id","context_key":"user"}'),
  ((SELECT id FROM workflows WHERE name='Lawyer Created'),5,'queue_notification','{"entity":"users","record_id":"{user_id}","event_type":"insert","payload":"{user}"}');


-- Ensure Lawyer form references the correct workflow now that it exists
UPDATE forms
  SET on_submit_workflow_id = (
    SELECT id FROM workflows WHERE name='Lawyer Created'
  )
WHERE name='Lawyer';


-- Fleet Engineer workflow steps
INSERT INTO workflow_steps (workflow_id, step_order, step_type, config) VALUES
  ((SELECT id FROM workflows WHERE name='Fleet Engineer Created'),1,'map_fields','{"map":{"user_id":"id"}}'),
  ((SELECT id FROM workflows WHERE name='Fleet Engineer Created'),2,'ensure_group','{"name":"Fleet Engineers"}'),
  ((SELECT id FROM workflows WHERE name='Fleet Engineer Created'),3,'save_record','{"table":"user_group_memberships","data":{"user_id":"{user_id}","group_id":"{group_id}","role":"Fleet Engineer"}}'),
  ((SELECT id FROM workflows WHERE name='Fleet Engineer Created'),4,'load_record','{"table":"users","id_key":"user_id","context_key":"user"}'),
  ((SELECT id FROM workflows WHERE name='Fleet Engineer Created'),5,'queue_notification','{"entity":"users","record_id":"{user_id}","event_type":"insert","payload":"{user}"}');


-- Sample detail view
INSERT INTO detail_views (id, name, config, tenant_id, branch_id) VALUES (
  1,
  'Sample Detail',
  '{"name":"Sample Detail","items":[{"type":"heading","data_column":"name"},{"type":"paragraph","data_column":"description"}]}',
  NULL,
  NULL
);


-- Modal using sample detail view
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES (
  'Sample Detail Modal',
  '{"title":"Sample Detail","body":[{"type":"detail-view","viewId":1}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-address-card',
  'Sample Detail View',
  'Sample Detail View'
);


INSERT INTO detail_views (id, name, config, tenant_id, branch_id) VALUES (
  2,
  'Case Details',
  '{"name":"Case Details","items":[{"type":"heading","data_column":"title"},{"type":"paragraph","data_column":"client_id"},{"type":"paragraph","data_column":"status"},{"type":"paragraph","data_column":"opened_at"},{"type":"paragraph","data_column":"closed_at"},{"type":"paragraph","data_column":"lead_rep_id"},{"type":"paragraph","data_column":"description"},{"type":"paragraph","data_column":"initial_instructions"},{"type":"aggregate","table":"case_hours","column":"hours","function":"sum","filterField":"case_id"},{"type":"aggregate","table":"case_hours","column":"hours*rate","function":"sum","filterField":"case_id"},{"type":"aggregate","table":"expenses","column":"amount","function":"sum","filterField":"reference_id"}]}',
  NULL,
  NULL
);

-- Default invoice templates
INSERT INTO invoice_templates (name, file_path, tenant_id)
VALUES
  ('Basic', 'templates/invoices/basic.php', NULL),
  ('Detailed', 'templates/invoices/detailed.php', NULL),
  ('Modern', 'templates/invoices/modern.php', NULL);


-- Default invoice settings row
INSERT INTO invoice_settings (tenant_id)
VALUES (NULL);


-- Invoice Configuration modal and workflow
INSERT INTO ui_modals (name, config, tenant_id, branch_id) VALUES (
  'Invoice Configuration',
  '{"title":"Invoice Configuration","body":[{"type":"form","formId":44}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL
);


INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES (
  'Invoice Configuration',
  'invoice.configure',
  '{"conditions":[]}',
  TRUE
);


INSERT INTO workflow_steps (workflow_id, step_order, step_type, config)
VALUES (
  (SELECT id FROM workflows WHERE name='Invoice Configuration' LIMIT 1),
  1,
  'open_modal',
  '{"modal":"Invoice Configuration"}'
);


-- Workflows triggered when case hours are approved or rejected
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES ('Case Hours Approved', 'case_hours.approved', '{"conditions": []}', TRUE);


INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES ('Case Hours Rejected', 'case_hours.rejected', '{"conditions": []}', TRUE);


INSERT INTO workflow_steps (workflow_id, step_order, step_type, config) VALUES
  ((SELECT id FROM workflows WHERE name='Case Hours Approved' LIMIT 1),1,'map_fields','{"map":{"id":"case_id"}}'),
  ((SELECT id FROM workflows WHERE name='Case Hours Approved' LIMIT 1),2,'save_record','{"table":"case_hours","data":{"comments":"{comments}","status":"Approved"},"match":{"id":"{id}"}}'),
  ((SELECT id FROM workflows WHERE name='Case Hours Approved' LIMIT 1),3,'load_record','{"table":"case_hours","id_key":"id","context_key":"case_hour"}'),
  ((SELECT id FROM workflows WHERE name='Case Hours Approved' LIMIT 1),4,'queue_notification','{"entity":"case_hours","record_id":"{id}","payload":"{case_hour}"}');


INSERT INTO workflow_steps (workflow_id, step_order, step_type, config) VALUES
  ((SELECT id FROM workflows WHERE name='Case Hours Rejected' LIMIT 1),1,'map_fields','{"map":{"id":"case_id"}}'),
  ((SELECT id FROM workflows WHERE name='Case Hours Rejected' LIMIT 1),2,'save_record','{"table":"case_hours","data":{"comments":"{comments}","status":"Rejected"},"match":{"id":"{id}"}}'),
  ((SELECT id FROM workflows WHERE name='Case Hours Rejected' LIMIT 1),3,'load_record','{"table":"case_hours","id_key":"id","context_key":"case_hour"}'),
((SELECT id FROM workflows WHERE name='Case Hours Rejected' LIMIT 1),4,'queue_notification','{"entity":"case_hours","record_id":"{id}","payload":"{case_hour}"}');



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (52, 'Default', '["description","responsible_user_id","target_date","status","completed_at"]', 'target_date', 'ASC');




INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (53, 'Default', '["title","effective_date"]', 'title', 'ASC');



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (54, 'Default', '["regulation_id","title","due_date","assigned_to","status"]', 'due_date', 'ASC');


INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (58, 'Default', '["location","type","severity","investigator_id"]', 'location', 'ASC');


-- OHS module modals
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Compliance Calendar','{"title":"Compliance Calendar","body":[{"type":"calendar","options":{"tableName":"ohs_compliance_tasks","dateField":"due_date"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-calendar-check','Compliance Calendar','Compliance Calendar');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Compliance Dashboard','{"title":"Compliance Dashboard","body":[{"type":"html","id":"complianceDash","html":"<div id=\"complianceDashboard\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-gauge','Compliance Dashboard','Compliance Dashboard');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Drill Down Dashboard','{"title":"Drill Down Dashboard","body":[{"type":"table","options":{"tableName":"ohs_incidents"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-filter','Drill Down Dashboard','Drill Down Dashboard');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Emergency Preparedness','{"title":"Emergency Preparedness","body":[{"type":"table","options":{"tableName":"ohs_emergency_drills"}},{"type":"table","options":{"tableName":"ohs_emergency_contacts"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-phone','Emergency Preparedness','Emergency Preparedness');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Hazard Management','{"title":"Hazard Management","header":[{"type":"button","label":"Add Hazard","formName":"OHS Hazard"}],"body":[{"type":"table","options":{"tableName":"ohs_hazards","showGlobalSearch":false,"addButton":false,"editFormId":7}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-shield-halved','Hazard Management','Hazard Management');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Hazard Types','{"title":"Hazard Types","header":[{"type":"button","label":"Add Hazard Type","formName":"Hazard Type"}],"body":[{"type":"table","options":{"tableName":"ohs_hazard_types","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-layer-group','Hazard Types','Hazard Types');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Incident Heatmap','{"title":"Incident Heatmap","mapLibraries":{"provider":"google","libraries":"visualization"},"body":[{"type":"graph-map","options":{"endpoint":"../api/ohs_dashboard/heatmap","dataPath":"rows"}},{"type":"graph-chart","options":{"endpoint":"../api/ohs_dashboard/heatmap","dataPath":"chart","type":"bar"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-map','Incident Heatmap','Incident Heatmap');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Incident Summary Dashboard','{"title":"Incident Summary","body":[{"type":"graph-chart","options":{"endpoint":"../api/ohs_dashboard/summary","type":"pie"}},{"type":"graph-chart","options":{"endpoint":"../api/ohs_dashboard/monthly_trend","type":"line"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-chart-pie','Incident Summary Dashboard','Incident Summary Dashboard');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Inspection Audit','{"title":"Inspection Audit","body":[{"type":"table","options":{"tableName":"ohs_inspection_audits"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-list-check','Inspection Audit','Inspection Audit');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('JSA Training Status','{"title":"JSA Training Status","body":[{"type":"table","options":{"tableName":"ohs_jsas"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-user-graduate','JSA Training Status','JSA Training Status');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Near Miss Dashboard','{"title":"Near Miss Dashboard","body":[{"type":"html","id":"nearMissDash","html":"<canvas id=\"nearMissTrend\"></canvas><table class=\"near-miss-table\"></table>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-chart-line','Near Miss Dashboard','Near Miss Dashboard');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Assignment Rules','{"title":"OHS Assignment Rules","body":[{"type":"table","options":{"tableName":"ohs_assignment_rules"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-route','OHS Assignment Rules','OHS Assignment Rules');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Incident Types','{"title":"OHS Incident Types","header":[{"type":"button","label":"Add Incident Type","formName":"Incident Type"}],"body":[{"type":"table","options":{"tableName":"ohs_incident_types","showGlobalSearch":false,"addButton":false,"editFormId":57}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-clipboard-list','OHS Incident Types','OHS Incident Types');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Incident Wizard','{"title":"OHS Incident Wizard","body":[{"type":"html","id":"incidentWizard","html":"<div id=\"incidentWizard\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-wand-magic-sparkles','OHS Incident Wizard','OHS Incident Wizard');


-- Wizard configuration for incident forms
INSERT INTO form_wizards (id, name, description, tenant_id, branch_id)
VALUES (1, 'OHS Incident Wizard', 'Guided incident reporting', NULL, NULL)
ON CONFLICT DO NOTHING;


INSERT INTO form_wizard_steps (wizard_id, step_number, form_id, condition_field, condition_value)
VALUES
  (1, 1, 59, NULL, NULL),
  (1, 2, 13, 'classification', 'property_damage'),
  (1, 3, 14, 'classification', 'environmental'),
  (1, 4, 15, 'classification', 'near_miss'),
  (1, 5, 16, 'classification', 'first_aid'),
  (1, 6, 17, 'classification', 'medical_treatment'),
  (1, 7, 18, 'classification', 'lti'),
  (1, 8, 19, 'classification', 'fatality')
ON CONFLICT DO NOTHING;


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Incidents','{"title":"OHS Incidents","header":[{"type":"button","label":"Add Incident","wizardId":1}],"body":[{"type":"table","options":{"tableName":"ohs_incidents","showGlobalSearch":false,"addButton":false,"editFormId":4}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-exclamation-triangle','OHS Incidents','OHS Incidents');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Inspections','{"title":"OHS Inspections","header":[{"type":"button","label":"Add Inspection","formName":"OHS Inspection"}],"body":[{"type":"table","options":{"tableName":"ohs_inspections","showGlobalSearch":false,"addButton":false,"editFormId":5}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-clipboard-check','OHS Inspections','OHS Inspections');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Investigation Dashboard','{"title":"Investigation Dashboard","header":[{"type":"button","label":"Add Incident","wizardId":1}],"body":[{"type":"table","options":{"tableName":"ohs_incidents","editFormId":4,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-clipboard-question','OHS Investigation Dashboard','OHS Investigation Dashboard');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS JSA','{"title":"OHS JSA","header":[{"type":"button","label":"Create JSA","formName":"Job Safety Analysis"}],"body":[{"type":"table","options":{"tableName":"ohs_jsas","showGlobalSearch":false,"addButton":false,"editFormId":6}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-helmet-safety','OHS JSA','OHS JSA');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Safety Documents','{"title":"Safety Documents","body":[{"type":"table","options":{"tableName":"safety_documents"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-file-lines','Safety Documents','Safety Documents');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
('Ohs Reports','{"title": "OHS Reports", "header": [{"type": "html", "html": "<button class=\"btn btn-sm\" onclick=\"location.href=''../api/ohs_reports/export/excel''\">Export Excel</button><button class=\"btn btn-sm ml-2\" onclick=\"location.href=''../api/ohs_reports/export/pdf''\">Export PDF</button>"}], "body": [{"type": "graph-chart", "options": {"endpoint": "../api/ohs_reports/trendsByDepartment", "type": "line"}}, {"type": "graph-chart", "options": {"endpoint": "../api/ohs_reports/locationBenchmark", "type": "bar"}}], "footer": [{"type": "button", "label": "Close", "onClick": "closeModal"}]}',NULL,NULL,'fa-chart-bar','OHS Reports','OHS Reports');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Risk Matrix Dashboard','{"title":"Risk Matrix Dashboard","body":[{"type":"heatmap","id":"riskMatrixHeatmap","options":{"endpoint":"../api/ohs_risk_matrices"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-table-cells','Risk Matrix Dashboard','Risk Matrix Dashboard');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Root Cause Dashboard','{"title":"Root Cause Dashboard","body":[{"type":"html","id":"rootCauseDash","html":"<div id=\"rootCauseDashboard\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-magnifying-glass-chart','Root Cause Dashboard','Root Cause Dashboard');

INSERT INTO ui_modals (name, config, tenant_id, branch_id) VALUES ('Fishbone Example','{"title":"Fishbone Example","body":[{"type":"fishbone-diagram","options":{"diagramId":1}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL);

INSERT INTO ui_modals (name, config, tenant_id, branch_id) VALUES ('Fishbone Diagram Manager','{"title":"Fishbone Diagram Manager","header":[{"type":"button","label":"Add Diagram","onClick":"addFishboneDiagram"}],"body":[{"type":"table","id":"fishboneList","options":{"tableName":"fishbone_diagrams","showGlobalSearch":false,"addButton":false,"rowActions":[{"label":"Edit","onClick":"editFishboneDiagram"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL);
INSERT INTO ui_modals (name, config, tenant_id, branch_id) VALUES ('Fault Tree Manager','{"title":"Fault Tree Manager","header":[{"type":"button","label":"Add Diagram","onClick":"addFaultTreeDiagram"}],"body":[{"type":"table","id":"ftList","options":{"tableName":"ohs_fault_trees","showGlobalSearch":false,"addButton":false,"rowActions":[{"label":"Edit","onClick":"editFaultTreeDiagram"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL);


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Severity Dashboard','{"title":"Severity Dashboard","body":[{"type":"html","id":"severityDash","html":"<canvas id=\"sevChart\"></canvas><table class=\"treat-outcomes\"></table>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-notes-medical','Severity Dashboard','Severity Dashboard');

INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Actions','{"title":"OHS Actions","header":[{"type":"button","label":"Add Action","formName":"OHS Action"}],"body":[{"type":"table","options":{"tableName":"ohs_actions","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-list-check','OHS Actions','OHS Actions');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Regulations','{"title":"OHS Regulations","header":[{"type":"button","label":"Add Regulation","formName":"OHS Regulation"}],"body":[{"type":"table","options":{"tableName":"ohs_regulations","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-book','OHS Regulations','OHS Regulations');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Compliance Tasks','{"title":"OHS Compliance Tasks","header":[{"type":"button","label":"Add Task","formName":"OHS Compliance Task"}],"body":[{"type":"table","options":{"tableName":"ohs_compliance_tasks","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-list-check','OHS Compliance Tasks','OHS Compliance Tasks');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Safety Inductions','{"title":"Safety Inductions","header":[{"type":"button","label":"Add Induction","formName":"Safety Induction"}],"body":[{"type":"table","options":{"tableName":"safety_inductions","showGlobalSearch":false,"rowClick":"selectRecord","editFormId":10}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-helmet-safety','Safety Inductions','Safety Inductions');




INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (66, 'Default', '["description","type","category","owner","review_date"]', 'review_date', 'DESC');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Issues Log','{"title":"Issues Log","header":[{"type":"button","label":"Add Issue","formName":"Issues Log"}],"body":[{"type":"table","options":{"tableName":"ohs_issues","showGlobalSearch":false,"addButton":false,"editFormId":66}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-bug','Issues Log','Issues Log');



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (58, 'Default', '["title","assessment_date","department_id"]', 'assessment_date', 'DESC');


-- Risk Assessments modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Risk Assessments','{"title":"Risk Assessments","header":[{"type":"button","label":"Add Assessment","wizardId":2}],"body":[{"type":"table","options":{"tableName":"risk_assessments","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-triangle-exclamation','Risk Assessments','Risk Assessments');


INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Risk Assessment Wizard','{"title":"Risk Assessment Wizard","body":[{"type":"html","id":"riskAssessmentWizard","html":"<div id=\"riskAssessmentWizard\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-wand-magic-sparkles','Risk Assessment Wizard','Risk Assessment Wizard');


-- Wizard configuration for risk assessment forms
INSERT INTO form_wizards (id, name, description, tenant_id, branch_id)
VALUES (2, 'Risk Assessment Wizard', 'Guided risk assessment', NULL, NULL)
ON CONFLICT DO NOTHING;


INSERT INTO form_wizard_steps (wizard_id, step_number, form_id, condition_field, condition_value) VALUES
  (2, 1, 60, NULL, NULL),
  (2, 2, 61, NULL, NULL),
  (2, 3, 62, NULL, NULL),
  (2, 4, 63, NULL, NULL),
  (2, 5, 64, NULL, NULL),
  (2, 6, 65, NULL, NULL)
ON CONFLICT DO NOTHING;

-- Employee Licenses modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Employee Licenses','{"title":"Employee Licenses","header":[{"type":"button","label":"Add License","formId":11}],"body":[{"type":"table","options":{"tableName":"employee_licenses","showGlobalSearch":false,"editFormId":11}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-id-card','Employee Licenses','Employee Licenses');


-- Permits modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description) VALUES
  ('Permits','{"title":"Permits","header":[{"type":"button","label":"Add Application","formId":15}],"body":[{"type":"table","options":{"tableName":"permit_applications","showGlobalSearch":false,"addButton":false,"editFormId":15,"nestedTableConfig":{"childTableName":"permit_inspections","linkField":"permit_application_id","columnsToShow":["inspector_id","scheduled_for","result","notes","hours_logged"],"editFormId":55}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-passport','Permits','Permits');



INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
VALUES (66, 'Default', '["interested_party","status","review_date"]', 'interested_party', 'ASC');


-- Needs & Expectations modal
INSERT INTO ui_modals (name, config, tenant_id, branch_id, icon, aria_label, description)
VALUES ('Needs & Expectations','{"title":"Needs & Expectations","header":[{"type":"button","label":"Add Assessment","formName":"Needs & Expectations Assessment"}],"body":[{"type":"table","options":{"tableName":"ohs_needs_expectations","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-hands-helping','Needs & Expectations','Needs & Expectations');

-- Link OHS modals to their forms and disable search/add buttons
UPDATE ui_modals SET config='{"title":"OHS Incidents","header":[{"type":"button","label":"Add Incident","wizardId":1}],"body":[{"type":"table","options":{"tableName":"ohs_incidents","showGlobalSearch":false,"addButton":false,"editFormId":4}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='OHS Incidents';

UPDATE ui_modals SET config='{"title":"OHS Inspections","header":[{"type":"button","label":"Add Inspection","formName":"OHS Inspection"}],"body":[{"type":"table","options":{"tableName":"ohs_inspections","showGlobalSearch":false,"addButton":false,"editFormId":5}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='OHS Inspections';

UPDATE ui_modals SET config='{"title":"Hazard Management","header":[{"type":"button","label":"Add Hazard","formName":"OHS Hazard"}],"body":[{"type":"table","options":{"tableName":"ohs_hazards","showGlobalSearch":false,"addButton":false,"editFormId":7}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='Hazard Management';

UPDATE ui_modals SET config='{"title":"Hazard Types","header":[{"type":"button","label":"Add Hazard Type","formName":"Hazard Type"}],"body":[{"type":"table","options":{"tableName":"ohs_hazard_types","showGlobalSearch":false,"addButton":false,"editFormId":56}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='Hazard Types';

UPDATE ui_modals SET config='{"title":"OHS JSA","header":[{"type":"button","label":"Create JSA","formName":"Job Safety Analysis"}],"body":[{"type":"table","options":{"tableName":"ohs_jsas","showGlobalSearch":false,"addButton":false,"editFormId":6}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='OHS JSA';

UPDATE ui_modals SET config='{"title":"OHS Assignment Rules","header":[{"type":"button","label":"Add Rule","formId":58}],"body":[{"type":"table","options":{"tableName":"ohs_assignment_rules","addButton":false,"editFormId":58}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='OHS Assignment Rules';

UPDATE ui_modals SET config='{"title":"Risk Assessments","header":[{"type":"button","label":"Add Assessment","wizardId":2}],"body":[{"type":"table","options":{"tableName":"risk_assessments","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='Risk Assessments';


-- Converted on 2025-07-11T16:28:17+12:00

INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 4, 'OHS Incident', 'Default incident report form', 'ohs_incidents', '[{"label":"date","field_name":"date","data_column":"date","type_id":3,"order_index":1},{"label":"time","field_name":"time","data_column":"time","type_id":1,"order_index":2},{"label":"classification","field_name":"classification","data_column":"classification","type_id":4,"order_index":3},{"label":"nature","field_name":"nature","data_column":"nature","type_id":1,"order_index":4},{"label":"location","field_name":"location","data_column":"location","type_id":1,"order_index":5},{"label":"status","field_name":"status","data_column":"status","type_id":4,"order_index":6}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 4);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 5, 'OHS Inspection', 'Record safety inspections', 'ohs_inspections', '[]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 5);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 6, 'Job Safety Analysis', 'Record JSA details', 'ohs_jsas', '[{"label":"title","field_name":"title","data_column":"title","type_id":1,"order_index":1},{"label":"description","field_name":"description","data_column":"description","type_id":1,"order_index":2},{"label":"doc_path","field_name":"doc_path","data_column":"doc_path","type_id":7,"order_index":3},{"label":"location","field_name":"location","data_column":"location","type_id":1,"order_index":4},{"label":"department_id","field_name":"department_id","data_column":"department_id","type_id":2,"order_index":5},{"label":"analysis_date","field_name":"analysis_date","data_column":"analysis_date","type_id":3,"order_index":6},{"label":"prepared_by","field_name":"prepared_by","data_column":"prepared_by","type_id":2,"order_index":7},{"label":"team_member_ids","field_name":"team_member_ids","data_column":"team_member_ids","type_id":6,"order_index":8},{"label":"ppe_required","field_name":"ppe_required","data_column":"ppe_required","type_id":6,"order_index":9},{"label":"permit_requirements","field_name":"permit_requirements","data_column":"permit_requirements","type_id":6,"order_index":10},{"label":"review_date","field_name":"review_date","data_column":"review_date","type_id":3,"order_index":11}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 6);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 7, 'OHS Hazard', 'Default hazard report form', 'ohs_hazards', '[{"label":"description","field_name":"description","data_column":"description","type_id":1,"order_index":1},{"label":"location","field_name":"location","data_column":"location","type_id":1,"order_index":2},{"label":"probability","field_name":"probability","data_column":"probability","type_id":4,"order_index":4,"options":[{"display_text":"1","value":"1"},{"display_text":"2","value":"2"},{"display_text":"3","value":"3"},{"display_text":"4","value":"4"},{"display_text":"5","value":"5"}]},{"label":"severity","field_name":"severity","data_column":"severity","type_id":4,"order_index":5,"options":[{"display_text":"1","value":"1"},{"display_text":"2","value":"2"},{"display_text":"3","value":"3"},{"display_text":"4","value":"4"},{"display_text":"5","value":"5"}]},{"label":"risk_level","field_name":"risk_level","data_column":"risk_level","type_id":2,"order_index":6},{"label":"latitude","field_name":"latitude","data_column":"latitude","type_id":2,"order_index":7},{"label":"longitude","field_name":"longitude","data_column":"longitude","type_id":2,"order_index":8},{"label":"Hazard Type","field_name":"hazard_type_id","data_column":"hazard_type_id","type_id":4,"order_index":3,"options_table":"ohs_hazard_types","options_label_column":"name","options_value_column":"id"}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 7);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 8, 'SCORM Package', 'Upload SCORM content', ' NULL', '[{"label":"course_id","field_name":"course_id","data_column":"course_id","type_id":2,"order_index":1},{"label":"title","field_name":"title","data_column":"title","type_id":1,"order_index":2},{"label":"scorm_zip","field_name":"scorm_zip","data_column":"scorm_zip","type_id":7,"order_index":3},{"label":"is_scorm","field_name":"is_scorm","data_column":"is_scorm","type_id":5,"order_index":4},{"label":"caption","field_name":"caption","data_column":"caption","type_id":7,"order_index":5},{"label":"language_code","field_name":"language_code","data_column":"language_code","type_id":1,"order_index":6}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 8);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 9, 'Training Path', 'Create a learning path', ' NULL', '[{"label":"name","field_name":"name","data_column":"name","type_id":1,"order_index":1},{"label":"description","field_name":"description","data_column":"description","type_id":1,"order_index":2},{"label":"department_id","field_name":"department_id","data_column":"department_id","type_id":2,"order_index":3},{"label":"role_id","field_name":"role_id","data_column":"role_id","type_id":2,"order_index":4}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 9);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 10, 'Safety Induction', 'Record employee safety inductions', ' NULL', '[{"label":"employee_id","field_name":"employee_id","data_column":"employee_id","type_id":2,"order_index":1},{"label":"induction_date","field_name":"induction_date","data_column":"induction_date","type_id":3,"order_index":2},{"label":"document_id","field_name":"document_id","data_column":"document_id","type_id":7,"order_index":3}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 10);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 11, 'Employee License', 'Track employee licenses', ' NULL', '[{"label":"employee_id","field_name":"employee_id","data_column":"employee_id","type_id":2,"order_index":1},{"label":"license_type","field_name":"license_type","data_column":"license_type","type_id":1,"order_index":2},{"label":"license_number","field_name":"license_number","data_column":"license_number","type_id":1,"order_index":3},{"label":"expiry_date","field_name":"expiry_date","data_column":"expiry_date","type_id":3,"order_index":4},{"label":"document_id","field_name":"document_id","data_column":"document_id","type_id":7,"order_index":5}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 11);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 12, 'Training Requirement', 'Assign mandatory courses per project', ' NULL', '[{"label":"project_id","field_name":"project_id","data_column":"project_id","type_id":2,"order_index":1},{"label":"role_id","field_name":"role_id","data_column":"role_id","type_id":2,"order_index":2},{"label":"location_id","field_name":"location_id","data_column":"location_id","type_id":2,"order_index":3},{"label":"course_id","field_name":"course_id","data_column":"course_id","type_id":2,"order_index":4}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 12);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 13, 'Time Clock', 'Record time clock entries', 'time_clocks', '[{"label":"Date of Damage","field_name":"incident_date","data_column":"incident_date","type_id":3,"order_index":1},{"label":"Time of Damage","field_name":"incident_time","data_column":"incident_time","type_id":1,"order_index":2},{"label":"Location","field_name":"location","data_column":"location","type_id":1,"order_index":3},{"label":"Asset Affected","field_name":"asset_affected","data_column":"asset_affected","type_id":1,"order_index":4},{"label":"Damage Description","field_name":"damage_description","data_column":"damage_description","type_id":1,"order_index":5},{"label":"Estimated Cost","field_name":"estimated_cost","data_column":"estimated_cost","type_id":2,"order_index":6},{"label":"Immediate Action","field_name":"immediate_action","data_column":"immediate_action","type_id":1,"order_index":7},{"label":"Responsible Person","field_name":"responsible_person","data_column":"responsible_person","type_id":1,"order_index":8},{"label":"Status","field_name":"status","data_column":"status","type_id":4,"order_index":9,"options":[{"display_text":"Reported","value":"reported"},{"display_text":"Investigating","value":"investigating"},{"display_text":"Closed","value":"closed)\nON CONFLICT DO NOTHING"}]},{"label":"Investigator","field_name":"investigator_id","data_column":"investigator_id","type_id":1,"order_index":10}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 13);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 14, 'Timesheet', 'Record daily timesheet totals', 'timesheets', '[{"label":"Date","field_name":"incident_date","data_column":"incident_date","type_id":3,"order_index":1},{"label":"Time","field_name":"incident_time","data_column":"incident_time","type_id":1,"order_index":2},{"label":"Location","field_name":"location","data_column":"location","type_id":1,"order_index":3},{"label":"Type of Incident","field_name":"env_incident_type","data_column":"env_incident_type","type_id":1,"order_index":4},{"label":"Impact Description","field_name":"impact_description","data_column":"impact_description","type_id":1,"order_index":5},{"label":"Area Affected","field_name":"area_affected","data_column":"area_affected","type_id":1,"order_index":6},{"label":"Volume/Quantity","field_name":"volume","data_column":"volume","type_id":2,"order_index":7},{"label":"Remediation Action","field_name":"remediation_action","data_column":"remediation_action","type_id":1,"order_index":8},{"label":"Status","field_name":"status","data_column":"status","type_id":4,"order_index":9,"options":[{"display_text":"Reported","value":"reported"},{"display_text":"Investigating","value":"investigating"},{"display_text":"Closed","value":"closed)\nON CONFLICT DO NOTHING"}]},{"label":"Investigator","field_name":"investigator_id","data_column":"investigator_id","type_id":1,"order_index":10}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 14);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 15, 'Permit Application', 'Default permit application form', 'permit_applications', '[{"label":"Date","field_name":"incident_date","data_column":"incident_date","type_id":3,"order_index":1},{"label":"Time","field_name":"incident_time","data_column":"incident_time","type_id":1,"order_index":2},{"label":"Location","field_name":"location","data_column":"location","type_id":1,"order_index":3},{"label":"Description of Near Miss","field_name":"description","data_column":"description","type_id":1,"order_index":4},{"label":"Hazard Identified","field_name":"hazard_identified","data_column":"hazard_identified","type_id":1,"order_index":5},{"label":"Potential Consequence","field_name":"potential_consequence","data_column":"potential_consequence","type_id":1,"order_index":6},{"label":"Immediate Action","field_name":"immediate_action","data_column":"immediate_action","type_id":1,"order_index":7},{"label":"Status","field_name":"status","data_column":"status","type_id":4,"order_index":8,"options":[{"display_text":"Reported","value":"reported"},{"display_text":"Investigating","value":"investigating"},{"display_text":"Closed","value":"closed)\nON CONFLICT DO NOTHING"}]},{"label":"Investigator","field_name":"investigator_id","data_column":"investigator_id","type_id":1,"order_index":9}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 15);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 16, 'OHS Incident – First Aid', 'Report incidents requiring first aid', 'ohs_incidents', '[{"label":"Date","field_name":"incident_date","data_column":"incident_date","type_id":3,"order_index":1},{"label":"Time","field_name":"incident_time","data_column":"incident_time","type_id":1,"order_index":2},{"label":"Location","field_name":"location","data_column":"location","type_id":1,"order_index":3},{"label":"Person Treated","field_name":"person_treated","data_column":"person_treated","type_id":1,"order_index":4},{"label":"Injury Description","field_name":"injury_description","data_column":"injury_description","type_id":1,"order_index":5},{"label":"First Aid Given","field_name":"first_aid_given","data_column":"first_aid_given","type_id":1,"order_index":6},{"label":"Treated By","field_name":"treated_by","data_column":"treated_by","type_id":1,"order_index":7},{"label":"Follow-Up Required?","field_name":"follow_up_required","data_column":"follow_up_required","type_id":4,"order_index":8,"options":[{"display_text":"Yes","value":"yes"},{"display_text":"No","value":"no)\nON CONFLICT DO NOTHING"}]},{"label":"Status","field_name":"status","data_column":"status","type_id":4,"order_index":9,"options":[{"display_text":"Reported","value":"reported"},{"display_text":"Investigating","value":"investigating"},{"display_text":"Closed","value":"closed)\nON CONFLICT DO NOTHING"}]},{"label":"Investigator","field_name":"investigator_id","data_column":"investigator_id","type_id":1,"order_index":10}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 16);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 17, 'OHS Incident – Medical Treatment', 'Report incidents requiring medical treatment', 'ohs_incidents', '[{"label":"Date","field_name":"incident_date","data_column":"incident_date","type_id":3,"order_index":1},{"label":"Time","field_name":"incident_time","data_column":"incident_time","type_id":1,"order_index":2},{"label":"Location","field_name":"location","data_column":"location","type_id":1,"order_index":3},{"label":"Person Treated","field_name":"person_treated","data_column":"person_treated","type_id":1,"order_index":4},{"label":"Injury Description","field_name":"injury_description","data_column":"injury_description","type_id":1,"order_index":5},{"label":"Medical Details","field_name":"medical_details","data_column":"medical_details","type_id":1,"order_index":6},{"label":"Provider","field_name":"medical_provider","data_column":"medical_provider","type_id":1,"order_index":7},{"label":"Follow-Up Required?","field_name":"follow_up_required","data_column":"follow_up_required","type_id":4,"order_index":8,"options":[{"display_text":"Yes","value":"yes"},{"display_text":"No","value":"no"}]},{"label":"Status","field_name":"status","data_column":"status","type_id":4,"order_index":9,"options":[{"display_text":"Reported","value":"reported"},{"display_text":"Investigating","value":"investigating"},{"display_text":"Closed","value":"closed)\nON CONFLICT DO NOTHING"}]},{"label":"Investigator","field_name":"investigator_id","data_column":"investigator_id","type_id":1,"order_index":10}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 17);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 18, 'OHS Incident – LTI', 'Report lost-time injuries', 'ohs_incidents', '[{"label":"Date","field_name":"incident_date","data_column":"incident_date","type_id":3,"order_index":1},{"label":"Time","field_name":"incident_time","data_column":"incident_time","type_id":1,"order_index":2},{"label":"Location","field_name":"location","data_column":"location","type_id":1,"order_index":3},{"label":"Person Injured","field_name":"person_injured","data_column":"person_injured","type_id":1,"order_index":4},{"label":"Injury Description","field_name":"injury_description","data_column":"injury_description","type_id":1,"order_index":5},{"label":"Days Lost","field_name":"days_lost","data_column":"days_lost","type_id":2,"order_index":6},{"label":"Return-to-Work Date","field_name":"rtw_date","data_column":"rtw_date","type_id":3,"order_index":7},{"label":"Corrective Action","field_name":"corrective_action","data_column":"corrective_action","type_id":1,"order_index":8},{"label":"Status","field_name":"status","data_column":"status","type_id":4,"order_index":9,"options":[{"display_text":"Reported","value":"reported"},{"display_text":"Investigating","value":"investigating"},{"display_text":"Closed","value":"closed)\nON CONFLICT DO NOTHING"}]},{"label":"Investigator","field_name":"investigator_id","data_column":"investigator_id","type_id":1,"order_index":10}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 18);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 19, 'OHS Incident – Fatality', 'Report fatalities', 'ohs_incidents', '[{"label":"Date","field_name":"incident_date","data_column":"incident_date","type_id":3,"order_index":1},{"label":"Time","field_name":"incident_time","data_column":"incident_time","type_id":1,"order_index":2},{"label":"Location","field_name":"location","data_column":"location","type_id":1,"order_index":3},{"label":"Deceased Name","field_name":"deceased_name","data_column":"deceased_name","type_id":1,"order_index":4},{"label":"Cause of Death","field_name":"cause_of_death","data_column":"cause_of_death","type_id":1,"order_index":5},{"label":"Reported to Authorities","field_name":"reported_authorities","data_column":"reported_authorities","type_id":3,"order_index":6},{"label":"Coroner Details","field_name":"coroner_details","data_column":"coroner_details","type_id":1,"order_index":7},{"label":"Corrective Action","field_name":"corrective_action","data_column":"corrective_action","type_id":1,"order_index":8},{"label":"Status","field_name":"status","data_column":"status","type_id":4,"order_index":9,"options":[{"display_text":"Reported","value":"reported"},{"display_text":"Investigating","value":"investigating"},{"display_text":"Closed","value":"closed)\nON CONFLICT DO NOTHING"}]},{"label":"Investigator","field_name":"investigator_id","data_column":"investigator_id","type_id":1,"order_index":10}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 19);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 20, 'OHS Incident', 'Default incident report form', 'ohs_incidents', '[{"label":"date","field_name":"date","data_column":"date","type_id":3,"order_index":1},{"label":"time","field_name":"time","data_column":"time","type_id":1,"order_index":2},{"label":"classification","field_name":"classification","data_column":"classification","type_id":4,"order_index":3,"options":[{"display_text":"Injury","value":"injury"},{"display_text":"Property Damage","value":"property_damage"},{"display_text":"Environmental","value":"environmental"},{"display_text":"Near Miss","value":"near_miss"},{"display_text":"First Aid","value":"first_aid"},{"display_text":"Medical Treatment","value":"medical_treatment"},{"display_text":"LTI","value":"lti"},{"display_text":"Fatality","value":"fatality)\nON CONFLICT DO NOTHING"}]},{"label":"location","field_name":"location","data_column":"location","type_id":1,"order_index":4},{"label":"nature","field_name":"nature","data_column":"nature","type_id":1,"order_index":5},{"label":"workplace_part","field_name":"workplace_part","data_column":"workplace_part","type_id":1,"order_index":6},{"label":"activity","field_name":"activity","data_column":"activity","type_id":1,"order_index":7},{"label":"unexpected","field_name":"unexpected","data_column":"unexpected","type_id":1,"order_index":8},{"label":"how_sustained","field_name":"how_sustained","data_column":"how_sustained","type_id":1,"order_index":9},{"label":"completed_by","field_name":"completed_by","data_column":"completed_by","type_id":1,"order_index":10},{"label":"position","field_name":"position","data_column":"position","type_id":1,"order_index":11},{"label":"outcome","field_name":"outcome","data_column":"outcome","type_id":1,"order_index":12},{"label":"preventative_action","field_name":"preventative_action","data_column":"preventative_action","type_id":1,"order_index":13},{"label":"investigator_id","field_name":"investigator_id","data_column":"investigator_id","type_id":1,"order_index":14},{"label":"status","field_name":"status","data_column":"status","type_id":4,"order_index":15,"options":[{"display_text":"Reported","value":"reported"},{"display_text":"Investigating","value":"investigating"},{"display_text":"Closed","value":"closed)\nON CONFLICT DO NOTHING"}]},{"label":"Days Lost","field_name":"days_lost","data_column":"days_lost","type_id":2,"order_index":16},{"label":"Return-to-Work Date","field_name":"rtw_date","data_column":"rtw_date","type_id":3,"order_index":17},{"label":"Restricted Duty Notes","field_name":"restricted_duty_notes","data_column":"restricted_duty_notes","type_id":1,"order_index":18}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 20);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 29, 'Vehicle Registration', 'Capture fleet vehicle details', 'vehicles', '[{"label":"vehicle_number","field_name":"vehicle_number","data_column":"vehicle_number","type_id":1,"order_index":1,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"},{"label":"vin","field_name":"vin","data_column":"vin","type_id":1,"order_index":2,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"},{"label":"engine_number","field_name":"engine_number","data_column":"engine_number","type_id":1,"order_index":3,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"},{"label":"mileage","field_name":"mileage","data_column":"mileage","type_id":2,"order_index":4,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"},{"label":"make","field_name":"make","data_column":"make","type_id":9,"order_index":5,"options_table":"vehicle_makes","options_label_column":"name","options_value_column":"id"},{"label":"model","field_name":"model","data_column":"model","type_id":9,"order_index":6,"options_table":"vehicle_models","options_label_column":"name","options_value_column":"id"},{"label":"type","field_name":"type","data_column":"type","type_id":9,"order_index":7,"options_table":"vehicle_types","options_label_column":"name","options_value_column":"id"},{"label":"year","field_name":"year","data_column":"year","type_id":2,"order_index":8,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"},{"label":"fitness_expires","field_name":"fitness_expires","data_column":"fitness_expires","type_id":3,"order_index":9,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 29);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 30, 'Trip Log', 'Record vehicle trips with mileage', ' NULL', '[{"label":"vehicle_id","field_name":"vehicle_id","data_column":"vehicle_id","type_id":2,"order_index":1},{"label":"driver_id","field_name":"driver_id","data_column":"driver_id","type_id":2,"order_index":2},{"label":"trip_date","field_name":"trip_date","data_column":"trip_date","type_id":3,"order_index":3},{"label":"start_time","field_name":"start_time","data_column":"start_time","type_id":8,"order_index":4},{"label":"end_time","field_name":"end_time","data_column":"end_time","type_id":8,"order_index":5},{"label":"start_location","field_name":"start_location","data_column":"start_location","type_id":1,"order_index":6},{"label":"end_location","field_name":"end_location","data_column":"end_location","type_id":1,"order_index":7},{"label":"start_mileage","field_name":"start_mileage","data_column":"start_mileage","type_id":2,"order_index":8},{"label":"end_mileage","field_name":"end_mileage","data_column":"end_mileage","type_id":2,"order_index":9},{"label":"distance_km","field_name":"distance_km","data_column":"distance_km","type_id":2,"order_index":10},{"label":"status","field_name":"status","data_column":"status","type_id":1,"order_index":11}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 30);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 31, 'Service Type', 'Define maintenance intervals', 'service_types', '[{"label":"name","field_name":"name","data_column":"name","type_id":1,"order_index":1,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"},{"label":"description","field_name":"description","data_column":"description","type_id":6,"order_index":2,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"},{"label":"make","field_name":"make","data_column":"make","type_id":9,"order_index":3,"options_table":"vehicle_makes","options_label_column":"name","options_value_column":"id"},{"label":"model","field_name":"model","data_column":"model","type_id":9,"order_index":4,"options_table":"vehicle_models","options_label_column":"name","options_value_column":"id"},{"label":"vehicle_type","field_name":"type","data_column":"type","type_id":9,"order_index":5,"options_table":"vehicle_types","options_label_column":"name","options_value_column":"id"},{"label":"km_interval","field_name":"km_interval","data_column":"km_interval","type_id":2,"order_index":6,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"},{"label":"month_interval","field_name":"month_interval","data_column":"month_interval","type_id":2,"order_index":7,"options_table":" NULL","options_label_column":" NULL","options_value_column":" NULL"}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 31);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 32, 'User Group', 'Manage user groups and permissions', 'groups', '[{"label":"name","field_name":"name","data_column":"name","type_id":1,"order_index":1},{"label":"description","field_name":"description","data_column":"description","type_id":6,"order_index":2},{"label":"parent_id","field_name":"parent_id","data_column":"parent_id","type_id":2,"order_index":3}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 32);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 33, 'Group Member', 'Assign users to groups', 'user_group_memberships', '[{"label":"user_id","field_name":"user_id","data_column":"user_id","type_id":2,"order_index":1},{"label":"group_id","field_name":"group_id","data_column":"group_id","type_id":2,"order_index":2},{"label":"role","field_name":"role","data_column":"role","type_id":1,"order_index":3}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 33);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 34, 'Vehicle Issue Report', 'Report vehicle issues', 'vehicle_reports', '[{"label":"vehicle_id","field_name":"vehicle_id","data_column":"vehicle_id","type_id":9,"order_index":1,"options_table":"vehicles","options_label_column":"vehicle_number","options_value_column":"id"},{"label":"report_type","field_name":"report_type","data_column":"report_type","type_id":4,"order_index":2,"options_table":"\n        NULL","options_label_column":" NULL","options_value_column":" NULL","options":[{"display_text":"minor","value":"minor"},{"display_text":"major","value":"major"},{"display_text":"breakdown","value":"breakdown"}]},{"label":"description","field_name":"description","data_column":"description","type_id":6,"order_index":3,"options_table":"\n        NULL","options_label_column":" NULL","options_value_column":" NULL"}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 34);
/* ---- Client form (id 35) – JSON format ---- */
INSERT INTO forms
        (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT  35,
        'Client',
        'Client details',
        'clients',
        '[
          {"label":"name","field_name":"name","data_column":"name","type_id":1,"order_index":1},
          {"label":"phone","field_name":"phone","data_column":"phone","type_id":1,"order_index":2},
          {"label":"email","field_name":"email","data_column":"email","type_id":8,"order_index":3},
          {"label":"description","field_name":"description","data_column":"description","type_id":6,"order_index":4},
          {"label":"comments","field_name":"comments","data_column":"comments","type_id":6,"order_index":5}
         ]',
        NULL,   -- tenant_id
        NULL    -- branch_id
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 35);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 36, 'Case', 'Case record', 'cases', '[]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 36);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 37, 'Lawyer', 'Lawyer user', 'users', '[{"label":"full_name","field_name":"full_name","data_column":"full_name","type_id":1,"order_index":1},{"label":"emails","field_name":"emails","data_column":"emails","type_id":0,"order_index":2},{"label":"phones","field_name":"phones","data_column":"phones","type_id":0,"order_index":3},{"label":"password","field_name":"password","data_column":"NULL","type_id":0,"order_index":4}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 37);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 38, 'Case Hour', 'Record hours worked on a case', 'case_hours', '[]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 38);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 39, 'Tenant', 'Tenant details', 'tenants', '[{"label":"name","field_name":"name","data_column":"name","type_id":1,"order_index":1},{"label":"subdomain","field_name":"subdomain","data_column":"subdomain","type_id":1,"order_index":2},{"label":"custom_domain","field_name":"custom_domain","data_column":"custom_domain","type_id":1,"order_index":3},{"label":"settings","field_name":"settings","data_column":"settings","type_id":7,"order_index":4},{"label":"product_name","field_name":"product_name","data_column":"product_name","type_id":1,"order_index":5},{"label":"dashboard_name","field_name":"dashboard_name","data_column":"dashboard_name","type_id":1,"order_index":6},{"label":"logo_url","field_name":"logo_url","data_column":"logo_url","type_id":1,"order_index":7}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 39);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 40, 'Admin', 'Admin user', 'users', '[{"label":"full_name","field_name":"full_name","data_column":"full_name","type_id":1,"order_index":1},{"label":"email","field_name":"emails","data_column":"emails","type_id":15,"order_index":2},{"label":"phones","field_name":"phones","data_column":"phones","type_id":15,"order_index":3},{"label":"password","field_name":"password","data_column":"password","type_id":1,"order_index":4},{"label":"tenant_id","field_name":"tenant_id","data_column":"tenant_id","type_id":4,"options_table":"tenants","options_label_column":"name","options_value_column":"id","order_index":5}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 40);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 41, 'User', 'User account details', 'users', '[]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 41);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 42, 'Vehicle Downtime', 'Record vehicle downtime periods', 'vehicle_downtime', '[]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 42);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 44, 'Invoice Settings', 'Configure invoice defaults', 'invoice_settings', '[{"label":"template_id","field_name":"template_id","data_column":"template_id","type_id":0,"order_index":1,"options_table":"invoice_templates","options_label_column":"name","options_value_column":"id"},{"label":"logo_document_id","field_name":"logo_document_id","data_column":"logo_document_id","type_id":0,"order_index":2},{"label":"instructions","field_name":"instructions","data_column":"instructions","type_id":0,"order_index":3},{"label":"disclaimer","field_name":"disclaimer","data_column":"disclaimer","type_id":0,"order_index":4},{"label":"bank_details","field_name":"bank_details","data_column":"bank_details","type_id":0,"order_index":5},{"label":"number_format","field_name":"number_format","data_column":"number_format","type_id":0,"order_index":6},{"label":"starting_number","field_name":"starting_number","data_column":"starting_number","type_id":0,"order_index":7},{"label":"rollover_date","field_name":"rollover_date","data_column":"rollover_date","type_id":0,"order_index":8}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 44);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 45, 'Driver', 'Driver user', 'users', '[{"label":"full_name","field_name":"full_name","data_column":"full_name","type_id":1,"order_index":1},{"label":"email","field_name":"email","data_column":"NULL","type_id":0,"order_index":2},{"label":"phone","field_name":"phone","data_column":"NULL","type_id":1,"order_index":3},{"label":"password","field_name":"password","data_column":"NULL","type_id":0,"order_index":4}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 45);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 46, 'Fleet Engineer', 'Fleet engineer user', 'users', '[{"label":"full_name","field_name":"full_name","data_column":"full_name","type_id":1,"order_index":1},{"label":"email","field_name":"email","data_column":"NULL","type_id":0,"order_index":2},{"label":"phone","field_name":"phone","data_column":"NULL","type_id":1,"order_index":3},{"label":"password","field_name":"password","data_column":"NULL","type_id":0,"order_index":4}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 46);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 47, 'Case Instruction', 'Matter instruction', 'case_instructions', '[{"label":"case_id","field_name":"case_id","data_column":"case_id","type_id":0,"order_index":1},{"label":"instruction_date","field_name":"instruction_date","data_column":"instruction_date","type_id":0,"order_index":2},{"label":"instruction","field_name":"instruction","data_column":"instruction","type_id":0,"order_index":3},{"label":"documents","field_name":"document_ids","data_column":"document_ids","type_id":0,"order_index":4}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 47);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 48, 'Case Expense', 'Case related expense', 'expenses', '[{"label":"case","field_name":"case_id","data_column":"case_id","type_id":0,"order_index":1},{"label":"expense_date","field_name":"expense_date","data_column":"expense_date","type_id":0,"order_index":2},{"label":"amount","field_name":"amount","data_column":"amount","type_id":0,"order_index":3},{"label":"description","field_name":"description","data_column":"description","type_id":0,"order_index":4},{"label":"employee","field_name":"employee_id","data_column":"employee_id","type_id":0,"order_index":5,"options_table":"employees","options_label_column":"name","options_value_column":"id"},{"label":"documents","field_name":"document_ids","data_column":"document_ids","type_id":0,"order_index":6}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 48);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 49, 'Case Invoice', 'Invoice for a case', 'invoices', '[{"label":"reference_id","field_name":"reference_id","data_column":"reference_id","type_id":0,"order_index":1},{"label":"invoice_number","field_name":"invoice_number","data_column":"invoice_number","type_id":0,"order_index":2},{"label":"invoice_date","field_name":"invoice_date","data_column":"invoice_date","type_id":0,"order_index":3},{"label":"amount","field_name":"amount","data_column":"amount","type_id":0,"order_index":4},{"label":"status","field_name":"status","data_column":"status","type_id":0,"order_index":5},{"label":"invoice_template_id","field_name":"invoice_template_id","data_column":"invoice_template_id","type_id":0,"order_index":6,"options_table":"invoice_templates","options_label_column":"name","options_value_column":"id"}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 49);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 50, 'Case Payment', 'Payment for a case invoice', 'payments', '[{"label":"invoice_id","field_name":"invoice_id","data_column":"invoice_id","type_id":0,"order_index":1,"options_table":"invoices","options_label_column":"invoice_number","options_value_column":"id"},{"label":"payment_date","field_name":"payment_date","data_column":"payment_date","type_id":0,"order_index":2},{"label":"amount","field_name":"amount","data_column":"amount","type_id":0,"order_index":3},{"label":"payment_method","field_name":"payment_method","data_column":"payment_method","type_id":0,"order_index":4},{"label":"documents","field_name":"document_ids","data_column":"document_ids","type_id":0,"order_index":5}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 50);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 51, 'Case Approval', 'Approve or reject case', NULL, '[{"label":"case_id","field_name":"case_id","data_column":"case_id","type_id":0,"order_index":1},{"label":"comments","field_name":"comments","data_column":"comments","type_id":0,"order_index":2}]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 51);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 52, 'OHS Action', 'Action taken for an incident', 'ohs_actions', '[{"label":"description","field_name":"description","data_column":"description","type_id":0,"order_index":1},{"label":"responsible_user_id","field_name":"responsible_user_id","data_column":"responsible_user_id","type_id":0,"order_index":2},{"label":"target_date","field_name":"target_date","data_column":"target_date","type_id":0,"order_index":3},{"label":"status","field_name":"status","data_column":"status","type_id":0,"order_index":4},{"label":"completed_at","field_name":"completed_at","data_column":"completed_at","type_id":0,"order_index":5}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 52);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 53, 'OHS Regulation', 'Record safety regulations', 'ohs_regulations', '[{"label":"title","field_name":"title","data_column":"title","type_id":0,"order_index":1},{"label":"description","field_name":"description","data_column":"description","type_id":0,"order_index":2},{"label":"effective_date","field_name":"effective_date","data_column":"effective_date","type_id":0,"order_index":3}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 53);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 54, 'OHS Compliance Task', 'Task to meet a regulation', 'ohs_compliance_tasks', '[{"label":"regulation_id","field_name":"regulation_id","data_column":"regulation_id","type_id":0,"order_index":1,"options_table":"ohs_regulations","options_label_column":"title","options_value_column":"id"},{"label":"title","field_name":"title","data_column":"title","type_id":0,"order_index":2},{"label":"due_date","field_name":"due_date","data_column":"due_date","type_id":0,"order_index":3},{"label":"assigned_to","field_name":"assigned_to","data_column":"assigned_to","type_id":0,"order_index":4},{"label":"status","field_name":"status","data_column":"status","type_id":0,"order_index":5}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 54);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 55, 'Permit Inspection', 'Record permit inspections', 'permit_inspections', '[]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 55);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 56, 'Hazard Type', 'Manage hazard classifications', 'ohs_hazard_types', '[]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 56);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 57, 'Incident Type', 'Manage incident categories', 'ohs_incident_types', '[]', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 57);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 58, 'OHS Assignment Rule', 'Investigator assignment rule', 'ohs_assignment_rules', '[]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 58);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 59, 'OHS Incident Classification', 'Select incident type and location', 'ohs_incidents', '[{"label":"classification","field_name":"classification","data_column":"classification","type_id":0,"order_index":1,"options_table":"ohs_incident_types","options_label_column":"name","options_value_column":"name"},{"label":"location","field_name":"location","data_column":"location","type_id":0,"order_index":2},{"label":"severity","field_name":"severity","data_column":"severity","type_id":0,"order_index":3,"options":[{"display_text":"1","value":"1"},{"display_text":"2","value":"2"},{"display_text":"3","value":"3"},{"display_text":"4","value":"4"},{"display_text":"5","value":"5)\nON CONFLICT DO NOTHING"}]}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 59);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 66, 'Issues Log', 'Record safety issues', 'ohs_issues', '[{"label":"description","field_name":"description","data_column":"description","type_id":0,"order_index":1},{"label":"type","field_name":"type","data_column":"type","type_id":0,"order_index":2},{"label":"category","field_name":"category","data_column":"category","type_id":0,"order_index":3},{"label":"impact","field_name":"impact","data_column":"impact","type_id":0,"order_index":4},{"label":"risk_or_opportunity","field_name":"risk_or_opportunity","data_column":"risk_or_opportunity","type_id":0,"order_index":5},{"label":"action_taken","field_name":"action_taken","data_column":"action_taken","type_id":0,"order_index":6},{"label":"owner","field_name":"owner","data_column":"owner","type_id":0,"order_index":7},{"label":"review_date","field_name":"review_date","data_column":"review_date","type_id":0,"order_index":8}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 66);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 60, 'RA Section 1', 'Administrative information', 'risk_assessments', '[{"label":"title","field_name":"title","data_column":"title","type_id":0,"order_index":1},{"label":"reference_id","field_name":"reference_id","data_column":"reference_id","type_id":0,"order_index":2},{"label":"department_id","field_name":"department_id","data_column":"department_id","type_id":0,"order_index":3},{"label":"location","field_name":"location","data_column":"location","type_id":0,"order_index":4},{"label":"assessor_names","field_name":"assessor_names","data_column":"assessor_names","type_id":0,"order_index":5},{"label":"assessment_date","field_name":"assessment_date","data_column":"assessment_date","type_id":0,"order_index":6},{"label":"review_date","field_name":"review_date","data_column":"review_date","type_id":0,"order_index":7},{"label":"approver_name","field_name":"approver_name","data_column":"approver_name","type_id":0,"order_index":8},{"label":"work_description","field_name":"work_description","data_column":"work_description","type_id":0,"order_index":9},{"label":"people_involved","field_name":"people_involved","data_column":"people_involved","type_id":0,"order_index":10},{"label":"duration","field_name":"duration","data_column":"duration","type_id":0,"order_index":11},{"label":"permit_requirements","field_name":"permit_requirements","data_column":"permit_requirements","type_id":0,"order_index":12},{"label":"title","field_name":"title","data_column":"title","type_id":0,"order_index":1},{"label":"reference_id","field_name":"reference_id","data_column":"reference_id","type_id":0,"order_index":2},{"label":"department_id","field_name":"department_id","data_column":"department_id","type_id":0,"order_index":3},{"label":"location","field_name":"location","data_column":"location","type_id":0,"order_index":4},{"label":"assessor_names","field_name":"assessor_names","data_column":"assessor_names","type_id":0,"order_index":5},{"label":"assessment_date","field_name":"assessment_date","data_column":"assessment_date","type_id":0,"order_index":6}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 60);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 61, 'RA Task Description', 'Work details for assessment', 'risk_assessments', '[{"label":"work_description","field_name":"work_description","data_column":"work_description","type_id":0,"order_index":1},{"label":"people_involved","field_name":"people_involved","data_column":"people_involved","type_id":0,"order_index":2},{"label":"duration","field_name":"duration","data_column":"duration","type_id":0,"order_index":3},{"label":"permit_requirements","field_name":"permit_requirements","data_column":"permit_requirements","type_id":0,"order_index":4}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 61);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 62, 'RA Hazard', 'Identify hazards and risk ratings', 'risk_assessment_hazards', '[{"label":"hazard_description","field_name":"hazard_description","data_column":"hazard_description","type_id":0,"order_index":1},{"label":"who_might_be_harmed","field_name":"who_might_be_harmed","data_column":"who_might_be_harmed","type_id":0,"order_index":2},{"label":"existing_control_measures","field_name":"existing_control_measures","data_column":"existing_control_measures","type_id":0,"order_index":3},{"label":"risk_rating_before","field_name":"risk_rating_before","data_column":"risk_rating_before","type_id":0,"order_index":4},{"label":"additional_controls","field_name":"additional_controls","data_column":"additional_controls","type_id":0,"order_index":5},{"label":"residual_risk_rating","field_name":"residual_risk_rating","data_column":"residual_risk_rating","type_id":0,"order_index":6},{"label":"responsible_person","field_name":"responsible_person","data_column":"responsible_person","type_id":0,"order_index":7}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 62);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 63, 'Emergency Procedures', 'Response steps', ' NULL', '[{"label":"procedures","field_name":"procedures","data_column":"procedures","type_id":0,"order_index":1}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 63);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 64, 'PPE Checklist', 'Personal protective equipment list', 'risk_assessment_ppe', '[{"label":"checklist_item","field_name":"checklist_item","data_column":"checklist_item","type_id":0,"order_index":1}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 64);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 65, 'Risk Assessment Sign-off', 'Approval sign-off', 'risk_assessment_signoffs', '[{"label":"name","field_name":"name","data_column":"name","type_id":0,"order_index":1},{"label":"position","field_name":"position","data_column":"position","type_id":0,"order_index":2},{"label":"signature","field_name":"signature","data_column":"signature","type_id":0,"order_index":3},{"label":"signed_at","field_name":"signed_at","data_column":"signed_at","type_id":0,"order_index":4}]',  NULL,  NULL)
ON CONFLICT DO NOTHING
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 65);
INSERT INTO forms (id, name, description, mapped_table, elements, tenant_id, branch_id)
SELECT 67, 'Needs & Expectations Assessment', 'Stakeholder needs and expectations', 'ohs_needs_expectations', '[{"label":"interested_party","field_name":"interested_party","data_column":"interested_party","type_id":0,"order_index":1},{"label":"needs","field_name":"needs","data_column":"needs","type_id":0,"order_index":2},{"label":"expectations","field_name":"expectations","data_column":"expectations","type_id":0,"order_index":3},{"label":"compliance_required","field_name":"compliance_required","data_column":"compliance_required","type_id":0,"order_index":4},{"label":"source","field_name":"source","data_column":"source","type_id":0,"order_index":5},{"label":"status","field_name":"status","data_column":"status","type_id":0,"order_index":6},{"label":"notes","field_name":"notes","data_column":"notes","type_id":0,"order_index":7},{"label":"review_date","field_name":"review_date","data_column":"review_date","type_id":0,"order_index":8},{"label":"review_by","field_name":"review_by","data_column":"review_by","type_id":0,"order_index":9}]',  NULL,  NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 67);