-- Ensure Vehicle Registration form exists and update Vehicles modal

INSERT INTO forms (id, name, description, mapped_table, tenant_id, branch_id)
SELECT 16, 'Vehicle Registration', 'Capture fleet vehicle details', 'vehicles', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 16);

-- Required fields for Vehicle Registration form
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 16, 'vehicle_number', 'vehicle_number', 'vehicle_number', 1, 1
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 16 AND field_name = 'vehicle_number');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 16, 'vin', 'vin', 'vin', 1, 2
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 16 AND field_name = 'vin');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 16, 'engine_number', 'engine_number', 'engine_number', 1, 3
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 16 AND field_name = 'engine_number');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 16, 'mileage', 'mileage', 'mileage', 2, 4
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 16 AND field_name = 'mileage');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 16, 'make', 'make', 'make', 1, 5
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 16 AND field_name = 'make');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 16, 'model', 'model', 'model', 1, 6
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 16 AND field_name = 'model');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 16, 'type', 'type', 'type', 1, 7
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 16 AND field_name = 'type');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 16, 'year', 'year', 'year', 2, 8
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 16 AND field_name = 'year');

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

UPDATE ui_modals
SET config = '{"title":"Vehicles","addFormName":"Vehicle Registration","header":[{"type":"button","label":"Add Vehicle","onClick":"openVehicleForm"}],"body":[{"type":"table","options":{"tableName":"vehicles","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'
WHERE name = 'Vehicles';
