START TRANSACTION;

SET @allow_demo_option_exists := (
	SELECT COUNT(*)
	FROM `options`
	WHERE `foreign_id` = 1
		AND `key` = 'o_allow_demo_purchases'
);

INSERT INTO `options`
(`foreign_id`, `key`, `tab_id`, `value`, `label`, `type`, `order`, `is_visible`, `style`)
SELECT
	1,
	'o_allow_demo_purchases',
	2,
	'Yes|No::Yes',
	'Yes|No',
	'enum',
	5,
	1,
	NULL
WHERE @allow_demo_option_exists = 0;

UPDATE `options`
SET `value` = 'Yes|No::Yes'
WHERE `foreign_id` = 1
	AND `key` = 'o_allow_demo_purchases'
	AND (`value` IS NULL OR `value` = '' OR `value` = 'Yes|No::No');

UPDATE `options`
SET `order` = `order` + 1
WHERE @allow_demo_option_exists = 0
	AND `foreign_id` = 1
	AND `tab_id` = 2
	AND `key` IN ('o_insurance', 'o_insurance_type', 'o_thankyou_page')
	AND `order` >= 5;

SET @field_id := (SELECT `id` FROM `plugin_base_fields` WHERE `key` = 'opt_o_allow_demo_purchases' LIMIT 1);

INSERT INTO `plugin_base_fields` (`id`, `key`, `type`, `label`, `source`, `modified`)
SELECT
	NULL,
	'opt_o_allow_demo_purchases',
	'backend',
	'Options / Allow demo product purchases',
	'script',
	NOW()
WHERE @field_id IS NULL;

SET @field_id := COALESCE(@field_id, LAST_INSERT_ID());

INSERT INTO `plugin_base_multi_lang`
(`id`, `foreign_id`, `model`, `locale`, `field`, `content`, `source`)
SELECT
	NULL,
	@field_id,
	'pjField',
	l.`id`,
	'title',
	'Allow demo product purchases',
	'script'
FROM `plugin_base_locale` l
WHERE NOT EXISTS (
	SELECT 1
	FROM `plugin_base_multi_lang` m
	WHERE `foreign_id` = @field_id
		AND `model` = 'pjField'
		AND `locale` = l.`id`
		AND `field` = 'title'
);

SET @field_id := (SELECT `id` FROM `plugin_base_fields` WHERE `key` = 'opt_o_allow_demo_purchases_text' LIMIT 1);

INSERT INTO `plugin_base_fields` (`id`, `key`, `type`, `label`, `source`, `modified`)
SELECT
	NULL,
	'opt_o_allow_demo_purchases_text',
	'backend',
	'Options / Allow demo product purchases',
	'script',
	NOW()
WHERE @field_id IS NULL;

SET @field_id := COALESCE(@field_id, LAST_INSERT_ID());

INSERT INTO `plugin_base_multi_lang`
(`id`, `foreign_id`, `model`, `locale`, `field`, `content`, `source`)
SELECT
	NULL,
	@field_id,
	'pjField',
	l.`id`,
	'title',
	'When enabled, sample/demo products can be added to cart and purchased for testing. When disabled, demo products remain view-only.',
	'script'
FROM `plugin_base_locale` l
WHERE NOT EXISTS (
	SELECT 1
	FROM `plugin_base_multi_lang` m
	WHERE `foreign_id` = @field_id
		AND `model` = 'pjField'
		AND `locale` = l.`id`
		AND `field` = 'title'
);

COMMIT;
