-- Step 1: Update the order of the last two controls for each block
UPDATE {prefix}_abcon_controls c1
JOIN (
    SELECT id,
           ROW_NUMBER() OVER (PARTITION BY blockId ORDER BY order_num DESC) AS rn
    FROM {prefix}_abcon_controls
) ranks ON c1.id = ranks.id
SET c1.order_num = c1.order_num + 3
WHERE ranks.rn <= 2;

-- Step 2: Insert 'Sizing' control if it doesn't already exist
INSERT INTO {prefix}_abcon_controls 
(default_clone, blockId, title, type, state, target, config, order_num)
SELECT 
    1, b.id, 'Sizing', 'sizing', 'active', 
    '{\"common\":\"{\\\"type\\\":\\\"\\\"}"}', '', 
    COALESCE((
        SELECT MAX(c.order_num) - 4
        FROM {prefix}_abcon_controls c 
        WHERE c.blockId = b.id
    ), 0)
FROM {prefix}_abcon_blocks b
WHERE NOT EXISTS (
    SELECT 1 FROM {prefix}_abcon_controls c 
    WHERE c.blockId = b.id AND c.type = 'sizing'
);

-- Step 3: Insert 'Position' control if it doesn't already exist
INSERT INTO {prefix}_abcon_controls 
(default_clone, blockId, title, type, state, target, config, order_num)
SELECT 
    1, b.id, 'Position', 'position', 'active', 
    '{\"common\":\"{\\\"type\\\":\\\"\\\"}"}', '', 
    COALESCE((
        SELECT MAX(c.order_num) - 3
        FROM {prefix}_abcon_controls c 
        WHERE c.blockId = b.id
    ), 1)
FROM {prefix}_abcon_blocks b
WHERE NOT EXISTS (
    SELECT 1 FROM {prefix}_abcon_controls c 
    WHERE c.blockId = b.id AND c.type = 'position'
);

-- Step 4: Insert 'Layout' control if it doesn't already exist
INSERT INTO {prefix}_abcon_controls 
(default_clone, blockId, title, type, state, target, config, order_num)
SELECT 
    1, b.id, 'Layout', 'layout', 'active', 
    '{\"common\":\"{\\\"type\\\":\\\"\\\"}"}', '', 
    COALESCE((
        SELECT MAX(c.order_num) - 2
        FROM {prefix}_abcon_controls c 
        WHERE c.blockId = b.id
    ), 2)
FROM {prefix}_abcon_blocks b
WHERE NOT EXISTS (
    SELECT 1 FROM {prefix}_abcon_controls c 
    WHERE c.blockId = b.id AND c.type = 'layout'
);
