<?php
/**
 * Pricing Table block.
 *
 * Renders the HaloPrograms pricing grid: four plan cards with a Monthly/Annual
 * toggle, per-row feature lists with curated icons, "Most popular" highlight,
 * and a dedicated Enterprise card with a Call-us CTA.
 */

require_once __DIR__ . '/hp-pricing-table/icons.php';
require_once __DIR__ . '/hp-pricing-table/defaults.php';

// Pre-fill the Plans repeater on a freshly-inserted block so the editor
// shows the canonical four-plan layout instead of an empty repeater.
// Once the block is saved, the saved rows are returned as-is.
add_filter('acf/load_value/key=field_hp_pt_plans', function ($value, $post_id, $field) {
	if (!empty($value)) {
		return $value;
	}
	if (!is_string($post_id) || strpos($post_id, 'block_') !== 0) {
		return $value;
	}
	return hp_pricing_default_plans();
}, 10, 3);

add_action('acf/init', function () {
	if (!function_exists('acf_register_block_type')) {
		return;
	}

	acf_register_block_type([
		'name'            => 'hp-pricing-table',
		'title'           => __('Pricing Table'),
		'description'     => __('Plan cards with Monthly/Annual toggle, feature icons, and Stripe IDs.'),
		'render_callback' => 'bw_render_acf_block',
		'category'        => 'design',
		'icon'            => 'money-alt',
		'keywords'        => ['pricing', 'plans', 'stripe', 'tiers'],
		'mode'            => 'preview',
		'supports'        => [
			'align' => ['wide', 'full'],
			'jsx'   => true,
		],
	]);
});

// Render the icon dropdown options with their actual SVG (not just the text label).
// Hooks ACF's Select2 init for the per-feature `icon` field and rewrites its
// templateResult/templateSelection so each row shows the icon next to the label.
add_action('acf/input/admin_enqueue_scripts', function () {
	if (!function_exists('hp_pricing_icon_options') || !function_exists('hp_pricing_icon')) {
		return;
	}

	$icons = [];
	foreach (hp_pricing_icon_options() as $key => $label) {
		$icons[$key] = [
			'label' => $label,
			'svg'   => hp_pricing_icon($key),
		];
	}

	$data = 'window.HP_PRICING_ICONS = ' . wp_json_encode($icons) . ';';
	$css  = '.hp-icon-option{display:inline-flex;align-items:center;gap:8px;line-height:1.2}'
		. '.hp-icon-option .hp-feature__svg{width:16px;height:16px;flex:0 0 16px;color:#13233f}'
		. '.select2-results__option .hp-icon-option{padding:2px 0}'
		. '.select2-selection__rendered .hp-icon-option{vertical-align:middle}';

	$js = <<<'JS'
(function () {
	if (typeof acf === 'undefined' || typeof jQuery === 'undefined') return;
	var $ = jQuery;

	var styleEl = document.createElement('style');
	styleEl.setAttribute('data-hp-pricing-icons', '1');
	styleEl.textContent = window.HP_PRICING_ICON_CSS || '';
	document.head.appendChild(styleEl);

	function renderIcon(state) {
		if (!state.id) return state.text;
		var icons = window.HP_PRICING_ICONS || {};
		var icon = icons[state.id];
		if (!icon) return state.text;
		var $el = $(
			'<span class="hp-icon-option">' + icon.svg +
			'<span class="hp-icon-option__label"></span></span>'
		);
		$el.find('.hp-icon-option__label').text(icon.label || state.text);
		return $el;
	}

	acf.addFilter('select2_args', function (args, $select) {
		var $wrap = $select.closest('.acf-field');
		if (!$wrap.length || $wrap.data('key') !== 'field_hp_pt_feature_icon') return args;
		args.templateResult = renderIcon;
		args.templateSelection = renderIcon;
		args.escapeMarkup = function (m) { return m; };
		return args;
	});
})();
JS;

	$inline = $data . "\nwindow.HP_PRICING_ICON_CSS = " . wp_json_encode($css) . ";\n" . $js;
	wp_add_inline_script('acf-input', $inline);
});

add_action('acf/init', function () {
	if (!function_exists('acf_add_local_field_group')) {
		return;
	}

	$icon_choices = hp_pricing_icon_options();

	acf_add_local_field_group([
		'key'      => 'group_hp_pricing_table',
		'title'    => 'Pricing Table',
		'location' => [[[
			'param'    => 'block',
			'operator' => '==',
			'value'    => 'acf/hp-pricing-table',
		]]],
		'fields'   => [
			[
				'key'           => 'field_hp_pt_default_billing',
				'label'         => 'Default billing view',
				'name'          => 'default_billing',
				'type'          => 'radio',
				'choices'       => ['annual' => 'Annual', 'monthly' => 'Monthly'],
				'default_value' => 'annual',
				'layout'        => 'horizontal',
			],
			[
				'key'           => 'field_hp_pt_toggle_monthly',
				'label'         => 'Toggle: Monthly label',
				'name'          => 'toggle_monthly_label',
				'type'          => 'text',
				'default_value' => 'Monthly',
				'wrapper'       => ['width' => '40'],
			],
			[
				'key'           => 'field_hp_pt_toggle_annual',
				'label'         => 'Toggle: Annual label',
				'name'          => 'toggle_annual_label',
				'type'          => 'text',
				'default_value' => 'Annual',
				'wrapper'       => ['width' => '40'],
			],
			[
				'key'           => 'field_hp_pt_toggle_save',
				'label'         => 'Toggle: savings badge',
				'name'          => 'toggle_save_badge',
				'type'          => 'text',
				'default_value' => 'Save –16%',
				'wrapper'       => ['width' => '20'],
			],
			[
				'key'          => 'field_hp_pt_plans',
				'label'        => 'Plans',
				'name'         => 'plans',
				'type'         => 'repeater',
				'layout'       => 'block',
				'button_label' => 'Add plan',
				'min'          => 1,
				'sub_fields'   => [
					[
						'key'           => 'field_hp_pt_plan_card_type',
						'label'         => 'Card type',
						'name'          => 'card_type',
						'type'          => 'radio',
						'choices'       => [
							'standard'   => 'Standard',
							'popular'    => 'Standard + "Most popular" badge',
							'enterprise' => 'Enterprise (Custom price, CTA button)',
						],
						'default_value' => 'standard',
						'layout'        => 'vertical',
					],
					[
						'key'   => 'field_hp_pt_plan_name',
						'label' => 'Plan name',
						'name'  => 'name',
						'type'  => 'text',
					],
					[
						'key'     => 'field_hp_pt_plan_users_line',
						'label'   => 'Users line (bold)',
						'name'    => 'users_line',
						'type'    => 'text',
						'wrapper' => ['width' => '50'],
					],
					[
						'key'     => 'field_hp_pt_plan_contacts_line',
						'label'   => 'Contacts line (sub)',
						'name'    => 'contacts_line',
						'type'    => 'text',
						'wrapper' => ['width' => '50'],
					],
					[
						'key'          => 'field_hp_pt_plan_extra_note',
						'label'        => 'Extra small note (grey, under contacts)',
						'name'         => 'extra_note',
						'type'         => 'text',
						'instructions' => 'Optional. Example: "1,500 contacts per user". Leave blank to hide.',
					],
					[
						'key'                  => 'field_hp_pt_plan_price_monthly',
						'label'                => 'Monthly price',
						'name'                 => 'price_monthly',
						'type'                 => 'text',
						'wrapper'              => ['width' => '33'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_price_annual',
						'label'                => 'Annual-equivalent monthly price',
						'name'                 => 'price_annual',
						'type'                 => 'text',
						'wrapper'              => ['width' => '33'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_billed_as',
						'label'                => 'Billed-as line (annual only)',
						'name'                 => 'billed_as',
						'type'                 => 'text',
						'wrapper'              => ['width' => '34'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_enterprise_price',
						'label'                => 'Enterprise price label',
						'name'                 => 'enterprise_price_label',
						'type'                 => 'text',
						'default_value'        => 'Custom',
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '==', 'value' => 'enterprise'],
						]],
					],
					[
						'key'          => 'field_hp_pt_plan_features',
						'label'        => 'Features',
						'name'         => 'features',
						'type'         => 'repeater',
						'layout'       => 'table',
						'button_label' => 'Add feature',
						'sub_fields'   => [
							[
								'key'           => 'field_hp_pt_feature_icon',
								'label'         => 'Icon',
								'name'          => 'icon',
								'type'          => 'select',
								'choices'       => $icon_choices,
								'default_value' => 'check',
								'ui'            => 1,
							],
							[
								'key'   => 'field_hp_pt_feature_label',
								'label' => 'Label',
								'name'  => 'label',
								'type'  => 'text',
							],
						],
					],
					[
						'key'   => 'field_hp_pt_plan_footer_note',
						'label' => 'Footer note (gray pill at bottom of card)',
						'name'  => 'footer_note',
						'type'  => 'textarea',
						'rows'  => 2,
					],
					[
						'key'                  => 'field_hp_pt_plan_button_text',
						'label'                => 'Button text',
						'name'                 => 'button_text',
						'type'                 => 'text',
						'default_value'        => 'Get Started',
						'wrapper'              => ['width' => '34'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_button_url_monthly',
						'label'                => 'Button URL (monthly)',
						'name'                 => 'button_url_monthly',
						'type'                 => 'url',
						'wrapper'              => ['width' => '33'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_button_url_annual',
						'label'                => 'Button URL (annual)',
						'name'                 => 'button_url_annual',
						'type'                 => 'url',
						'wrapper'              => ['width' => '33'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_cta_text',
						'label'                => 'CTA text',
						'name'                 => 'cta_text',
						'type'                 => 'text',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '==', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_cta_url',
						'label'                => 'CTA URL',
						'name'                 => 'cta_url',
						'type'                 => 'url',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '==', 'value' => 'enterprise'],
						]],
					],
				],
			],
			[
				'key'           => 'field_hp_pt_bottom_strip',
				'label'         => 'Bottom strip (separator with " | ")',
				'name'          => 'bottom_strip',
				'type'          => 'text',
				'default_value' => 'Print mail, EDDM & on-demand mktg available in the Contractor Store | All plans auto-renew | Annual plans billed upfront',
			],
		],
	]);
});
