<?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_monthly_disabled',
						'label'                => 'Disable monthly billing for this card',
						'name'                 => 'monthly_disabled',
						'type'                 => 'true_false',
						'instructions'         => 'When ON: in the Monthly view this card is greyed out, the monthly price is replaced with "Annual only", and the monthly buy button is hidden. The Annual view is unaffected.',
						'default_value'        => 0,
						'ui'                   => 1,
						'ui_on_text'           => 'Annual only',
						'ui_off_text'          => 'Both',
						'wrapper'              => ['width' => '100'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_enable_options',
						'label'                => 'Enable options dropdown',
						'name'                 => 'enable_options',
						'type'                 => 'true_false',
						'instructions'         => 'Show a dropdown under the billed-as line. Each option overrides the card\'s monthly price, annual price, and buy URL when selected. The first option is the default.',
						'default_value'        => 0,
						'ui'                   => 1,
						'ui_on_text'           => 'Show dropdown',
						'ui_off_text'          => 'Hide',
						'wrapper'              => ['width' => '100'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type',        'operator' => '!=', 'value' => 'enterprise'],
							['field' => 'field_hp_pt_plan_monthly_disabled', 'operator' => '==', 'value' => '1'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_options',
						'label'                => 'Options',
						'name'                 => 'options',
						'type'                 => 'repeater',
						'layout'               => 'table',
						'button_label'         => 'Add option',
						'min'                  => 1,
						'instructions'         => 'Each row becomes one entry in the dropdown. The first row is selected by default and drives the card\'s initial price and buy URL.',
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_enable_options', 'operator' => '==', 'value' => '1'],
						]],
						'sub_fields'           => [
							[
								'key'     => 'field_hp_pt_plan_option_label',
								'label'   => 'Label',
								'name'    => 'label',
								'type'    => 'text',
								'wrapper' => ['width' => '24'],
							],
							[
								'key'          => 'field_hp_pt_plan_option_price_monthly',
								'label'        => 'Price /mo (display)',
								'name'         => 'price_monthly',
								'type'         => 'text',
								'instructions' => 'Shown as the big /mo number.',
								'wrapper'      => ['width' => '14'],
							],
							[
								'key'          => 'field_hp_pt_plan_option_price_annual',
								'label'        => 'Annual total ($)',
								'name'         => 'price_annual',
								'type'         => 'text',
								'instructions' => 'Used to auto-format the billed-as line if "Billed-as text" is empty.',
								'wrapper'      => ['width' => '14'],
							],
							[
								'key'          => 'field_hp_pt_plan_option_billed_as',
								'label'        => 'Billed-as text',
								'name'         => 'billed_as',
								'type'         => 'text',
								'instructions' => 'Optional verbatim text under the price. If empty, falls back to "Billed as {annual total}/yr".',
								'wrapper'      => ['width' => '24'],
							],
							[
								'key'     => 'field_hp_pt_plan_option_purchase_url',
								'label'   => 'Purchase URL',
								'name'    => 'purchase_url',
								'type'    => 'url',
								'wrapper' => ['width' => '24'],
							],
						],
					],
					[
						'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_button_color',
						'label'                => 'Buy button background color',
						'name'                 => 'button_color',
						'type'                 => 'color_picker',
						'instructions'         => 'Optional. Overrides the default orange Stripe button background for this card. Leave blank to use the default. Hover darkens automatically.',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_button_text_color',
						'label'                => 'Buy button text color',
						'name'                 => 'button_text_color',
						'type'                 => 'color_picker',
						'instructions'         => 'Optional. Defaults to white. Pick a dark color if your background is light.',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_button_hover_color',
						'label'                => 'Buy button background color (hover)',
						'name'                 => 'button_hover_color',
						'type'                 => 'color_picker',
						'instructions'         => 'Optional. Used on hover/focus. If blank, the base color is auto-darkened by ~8%.',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_button_hover_text_color',
						'label'                => 'Buy button text color (hover)',
						'name'                 => 'button_hover_text_color',
						'type'                 => 'color_picker',
						'instructions'         => 'Optional. Used on hover/focus. If blank, the base text color is kept.',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '!=', 'value' => 'enterprise'],
						]],
					],
					// Enterprise CTAs render bottom-up in the order: cta_* (bottom),
					// cta3_* (middle), cta2_* (top). Sidebar lists them top-down so
					// editors see them in visual order on the card.
					[
						'key'                  => 'field_hp_pt_plan_cta2_text',
						'label'                => 'Top CTA: text',
						'name'                 => 'cta2_text',
						'type'                 => 'text',
						'instructions'         => 'Top button on the Enterprise card. Example: "Schedule a demo". Leave blank to hide.',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '==', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_cta2_url',
						'label'                => 'Top CTA: URL',
						'name'                 => 'cta2_url',
						'type'                 => 'url',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '==', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_cta3_text',
						'label'                => 'Middle CTA: text',
						'name'                 => 'cta3_text',
						'type'                 => 'text',
						'instructions'         => 'Middle button. Example: "Email sales". Leave blank to hide.',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '==', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_cta3_url',
						'label'                => 'Middle CTA: URL',
						'name'                 => 'cta3_url',
						'type'                 => 'url',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '==', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_cta_text',
						'label'                => 'Bottom CTA: text',
						'name'                 => 'cta_text',
						'type'                 => 'text',
						'instructions'         => 'Bottom button (the existing CTA). Example: "Call us — 248-669-6900". Leave blank to hide.',
						'wrapper'              => ['width' => '50'],
						'conditional_logic'    => [[
							['field' => 'field_hp_pt_plan_card_type', 'operator' => '==', 'value' => 'enterprise'],
						]],
					],
					[
						'key'                  => 'field_hp_pt_plan_cta_url',
						'label'                => 'Bottom 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',
			],
		],
	]);
});
