<?php
declare(strict_types=1);
if ( ! defined( 'ABSPATH' ) ) {
	exit; }

wp_register_ability(
	'tpaep/tpaep-accordion',
	array(
'label' => __('Accordion/FAQ (Pro)', 'theplus'),
    'description'         => __( 'Adds The Plus "Accordion/FAQ" widget (tp-accordion) to an Elementor container with full professional options.', 'theplus' ),
		'category' => 'tpae',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'post_id'                      => array(
					'type'        => 'integer',
					'description' => 'Elementor page/post ID',
				),
				'parent_id'                    => array(
					'type'        => 'string',
					'description' => 'Target Elementor container ID',
				),
				'position'                     => array(
					'type'        => 'integer',
					'description' => 'Insert position (-1 = append)',
					'default'     => -1,
				),
				'accordion_type'               => array(
					'type'        => 'string',
					'enum'        => array( 'content', 'acf_repeater' ),
					'description' => 'Source type',
					'default'     => 'content',
				),
				'acf_repeater_key'             => array(
					'type'        => 'string',
					'description' => 'ACF Repeater field key (if accordion_type is acf_repeater)',
				),
				'acf_tab_title'                => array(
					'type'        => 'string',
					'description' => 'ACF field key for Title (if accordion_type is acf_repeater)',
				),
				'acf_tab_content'              => array(
					'type'        => 'string',
					'description' => 'ACF field key for Content (if accordion_type is acf_repeater)',
				),
				'display_icon'                 => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Show Global Toggle Icon',
					'default'     => 'yes',
				),
				'icon_align'                   => array(
					'type'        => 'string',
					'enum'        => array( 'left', 'right' ),
					'description' => 'Toggle icon alignment',
					'default'     => 'left',
				),
				'icon_style'                   => array(
					'type'        => 'string',
					'enum'        => array( 'font_awesome', 'font_awesome_5', 'icon_mind' ),
					'description' => 'Global Icon Font',
					'default'     => 'font_awesome',
				),
				'icon_fontawesome'             => array(
					'type'        => 'string',
					'description' => 'Global closed icon class (e.g. fa fa-plus)',
				),
				'icon_fontawesome_active'      => array(
					'type'        => 'string',
					'description' => 'Global opened icon class (e.g. fa fa-minus)',
				),
				'icon_fontawesome_5'           => array(
					'type'        => 'object',
					'description' => 'Global closed FA5 icon (e.g. {"value":"fas fa-plus","library":"solid"})',
				),
				'icon_fontawesome_5_active'    => array(
					'type'        => 'object',
					'description' => 'Global opened FA5 icon',
				),
				'icons_mind'                   => array(
					'type'        => 'string',
					'description' => 'Global closed Icons Mind class',
				),
				'icons_mind_active'            => array(
					'type'        => 'string',
					'description' => 'Global opened Icons Mind class',
				),
				'title_html_tag'               => array(
					'type'        => 'string',
					'enum'        => array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div' ),
					'description' => 'Title HTML tag',
					'default'     => 'div',
				),
				'on_hover_accordion'           => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Enable hover to open',
					'default'     => 'no',
				),
				'horizontal_accordion'         => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Horizontal layout',
					'default'     => 'no',
				),
				'horizontal_accordion_layout'  => array(
					'type'        => 'string',
					'enum'        => array( 'tp_hal_1', 'tp_hal_2' ),
					'description' => 'Horizontal layout style',
					'default'     => 'tp_hal_1',
				),
				'tabs_autoplay'                => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Autoplay items',
					'default'     => 'no',
				),
				'tabs_autoplaypause'           => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Show Play/Pause Button',
					'default'     => 'no',
				),
				'expand_collapse_accordion'    => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Show Expand/Collapse button',
					'default'     => 'no',
				),
				'eca_position'                 => array(
					'type'        => 'string',
					'enum'        => array( 'ecabefore', 'ecaafter' ),
					'description' => 'Expand/Collapse button position',
					'default'     => 'ecabefore',
				),
				'eca_colall'                   => array(
					'type'        => 'string',
					'description' => 'Collapse All text',
					'default'     => 'Collapse All',
				),
				'eca_expall'                   => array(
					'type'        => 'string',
					'description' => 'Expand All text',
					'default'     => 'Expand All',
				),
				'search_accordion'             => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Show search bar',
					'default'     => 'no',
				),
				'search_text_highlight'        => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no', '' ),
					'description' => 'Highlight search text',
					'default'     => '',
				),
				'search_accordion_length'      => array(
					'type'        => 'integer',
					'description' => 'Minimum search length',
					'default'     => 3,
				),
				'search_accordion_placeholder' => array(
					'type'        => 'string',
					'description' => 'Search input placeholder',
					'default'     => 'Enter Search',
				),
				'slider_accordion'             => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Slider & Pagination for accordion',
					'default'     => 'no',
				),
				'slider_accordion_align'       => array(
					'type'        => 'string',
					'enum'        => array( 'tpsaleft', 'tpsacenter', 'tpsaright' ),
					'description' => 'Slider align',
					'default'     => 'tpsaleft',
				),
				'slider_accordion_show'        => array(
					'type'        => 'integer',
					'description' => 'Slide Per Page',
					'default'     => 3,
				),
				'slider_accordion_text_prev'   => array(
					'type'        => 'string',
					'description' => 'Slider Previous Text',
				),
				'slider_accordion_text_nxt'    => array(
					'type'        => 'string',
					'description' => 'Slider Next Text',
				),
				'active_accordion'             => array(
					'type'        => 'string',
					'description' => 'Default active item index (1, 2... or "0" for none)',
					'default'     => '1',
				),
				'accordion_scroll_top'         => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Auto scroll top on open',
					'default'     => 'no',
				),
				'act_offset'                   => array(
					'type'        => 'integer',
					'description' => 'Scroll offset',
					'default'     => 0,
				),
				'act_speed'                    => array(
					'type'        => 'integer',
					'description' => 'Scroll speed',
					'default'     => 500,
				),
				'accordion_stager'             => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Stagger Animation',
					'default'     => 'no',
				),
				'accordion_stager_visi_delay'  => array(
					'type'        => 'integer',
					'description' => 'Stagger Visibility Delay',
					'default'     => 500,
				),
				'accordion_stager_gap'         => array(
					'type'        => 'integer',
					'description' => 'Stagger Gap',
					'default'     => 500,
				),
				'schema_accordion'             => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'SEO FAQ Schema Markup',
					'default'     => 'no',
				),
				'connection_unique_id'         => array(
					'type'        => 'string',
					'description' => 'Carousel Connection ID',
				),
				'accordion_items'              => array(
					'type'        => 'array',
					'description' => 'Manual accordion items (used if accordion_type is content)',
					'items'       => array(
						'type'       => 'object',
						'properties' => array(
							'tab_title'                => array(
								'type'        => 'string',
								'description' => 'Label for the item',
							),
							'content_source'           => array(
								'type'        => 'string',
								'enum'        => array( 'content', 'page_template' ),
								'description' => 'Content or Elementor Page Template',
								'default'     => 'content',
							),
							'tab_content'              => array(
								'type'        => 'string',
								'description' => 'Content text or HTML',
							),
							'content_template'         => array(
								'type'        => 'string',
								'description' => 'Template ID if source is page_template',
							),
							'backend_preview_template' => array(
								'type'        => 'string',
								'enum'        => array( 'yes', 'no' ),
								'description' => 'Show template in backend',
								'default'     => 'no',
							),
							'display_icon'             => array(
								'type'        => 'string',
								'enum'        => array( 'yes', 'no' ),
								'description' => 'Show icon for this item',
								'default'     => 'no',
							),
							'icon_style'               => array(
								'type'        => 'string',
								'enum'        => array( 'font_awesome', 'font_awesome_5', 'icon_mind' ),
								'description' => 'Icon style for this item',
							),
							'icon_fontawesome'         => array(
								'type'        => 'string',
								'description' => 'FontAwesome icon class (e.g. fa fa-download)',
							),
							'icon_fontawesome_5'       => array(
								'type'        => 'object',
								'description' => 'FontAwesome 5 icon object',
							),
							'icons_mind'               => array(
								'type'        => 'string',
								'description' => 'Icons Mind class',
							),
							'tab_hashid'               => array(
								'type'        => 'string',
								'description' => 'Unique ID for anchor links',
							),
						),
						'required'   => array( 'tab_title' ),
					),
				),
				'settings'                     => array(
					'type'        => 'object',
					'description' => 'Raw Elementor control key/value pairs to merge.',
				),
			),
			'required'             => array( 'post_id', 'parent_id' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array(
				'element_id'  => array( 'type' => 'string' ),
				'widget_type' => array( 'type' => 'string' ),
				'post_id'     => array( 'type' => 'integer' ),
			),
		),
		'execute_callback'    => 'tpaep_mcp_theplus_pro_accordion_ability',
		'permission_callback' => 'tpaep_mcp_theplus_pro_accordion_permission',
		'meta'                => array(
			'show_in_rest' => true,
			'mcp'          => array(
				'public' => true,
				'type'   => 'tool',
			),
		),
	)
);

function tpaep_mcp_theplus_pro_accordion_permission( ?array $input = null ): bool {
	if ( ! current_user_can( 'edit_posts' ) ) {
		return false; }
	$post_id = absint( $input['post_id'] ?? 0 );
	if ( $post_id > 0 && ! current_user_can( 'edit_post', $post_id ) ) {
		return false; }
	return true;
}

function tpaep_mcp_theplus_pro_accordion_ability( array $input ) {
	if ( ! tpaep_mcp_has_elementor() ) {
		return new WP_Error( 'elementor_missing', __( 'Elementor must be active.', 'theplus' ) ); }
	$widget_type = 'tp-accordion';
	if ( ! tpaep_mcp_has_registered_widget( $widget_type ) ) {
		return new WP_Error( 'widget_missing', __( 'The Plus Accordion widget is not registered.', 'theplus' ) ); }
	$post_id   = absint( $input['post_id'] ?? 0 );
	$parent_id = sanitize_text_field( (string) ( $input['parent_id'] ?? '' ) );
	$position  = intval( $input['position'] ?? -1 );
	if ( $post_id <= 0 || $parent_id === '' ) {
		return new WP_Error( 'missing_params', __( 'post_id and parent_id are required.', 'theplus' ) ); }
	$post = get_post( $post_id );
	if ( ! $post instanceof WP_Post ) {
		return new WP_Error( 'invalid_post', __( 'Target post was not found.', 'theplus' ) ); }
	$page_data = tpaep_mcp_get_elementor_page_data( $post_id );
	if ( is_wp_error( $page_data ) ) {
		return $page_data; }

	$settings = array(
		'accordion_type' => sanitize_key( $input['accordion_type'] ?? 'content' ),
	);

	$general_keys = array(
		'acf_repeater_key',
		'acf_tab_title',
		'acf_tab_content',
		'display_icon',
		'icon_align',
		'icon_style',
		'icon_fontawesome',
		'icon_fontawesome_active',
		'icons_mind',
		'icons_mind_active',
		'title_html_tag',
		'on_hover_accordion',
		'horizontal_accordion',
		'horizontal_accordion_layout',
		'tabs_autoplay',
		'tabs_autoplaypause',
		'expand_collapse_accordion',
		'eca_position',
		'eca_colall',
		'eca_expall',
		'search_accordion',
		'search_text_highlight',
		'search_accordion_placeholder',
		'slider_accordion',
		'slider_accordion_align',
		'slider_accordion_text_prev',
		'slider_accordion_text_nxt',
		'active_accordion',
		'accordion_scroll_top',
		'accordion_stager',
		'schema_accordion',
		'connection_unique_id',
	);
	$number_keys  = array(
		'search_accordion_length',
		'slider_accordion_show',
		'act_offset',
		'act_speed',
		'accordion_stager_visi_delay',
		'accordion_stager_gap',
	);
	$object_keys  = array(
		'icon_fontawesome_5',
		'icon_fontawesome_5_active',
	);

	foreach ( $general_keys as $key ) {
		if ( isset( $input[ $key ] ) ) {
			$settings[ $key ] = sanitize_text_field( (string) $input[ $key ] );
		}
	}
	foreach ( $number_keys as $key ) {
		if ( isset( $input[ $key ] ) ) {
			$settings[ $key ] = intval( $input[ $key ] );
		}
	}
	foreach ( $object_keys as $key ) {
		if ( isset( $input[ $key ] ) && is_array( $input[ $key ] ) ) {
			$settings[ $key ] = $input[ $key ];
		}
	}

	if ( ! empty( $input['accordion_items'] ) && is_array( $input['accordion_items'] ) ) {
		$settings['tabs'] = array_map(
			function ( $item ) {
				$tab = array(
					'tab_title'      => sanitize_text_field( (string) ( $item['tab_title'] ?? '' ) ),
					'tab_content'    => wp_kses_post( (string) ( $item['tab_content'] ?? '' ) ),
					'content_source' => sanitize_text_field( (string) ( $item['content_source'] ?? 'content' ) ),
				);

				$tab_keys = array( 'content_template', 'backend_preview_template', 'display_icon', 'icon_style', 'icon_fontawesome', 'icons_mind', 'tab_hashid' );
				foreach ( $tab_keys as $key ) {
					if ( isset( $item[ $key ] ) ) {
						$tab[ $key ] = sanitize_text_field( (string) $item[ $key ] );
					}
				}
				if ( isset( $item['icon_fontawesome_5'] ) && is_array( $item['icon_fontawesome_5'] ) ) {
					$tab['icon_fontawesome_5'] = $item['icon_fontawesome_5'];
				}

				return $tab;
			},
			$input['accordion_items']
		);
	}

	$settings = tpaep_mcp_merge_widget_settings( $settings, $input['settings'] ?? array() );
	$widget   = array(
		'id'         => tpaep_mcp_generate_elementor_element_id(),
		'elType'     => 'widget',
		'widgetType' => $widget_type,
		'isInner'    => false,
		'settings'   => $settings,
		'elements'   => array(),
	);
	if ( ! tpaep_mcp_insert_elementor_element( $page_data, $parent_id, $widget, $position ) ) {
		return new WP_Error( 'parent_not_found', __( 'Parent container not found.', 'theplus' ) ); }
	$save_result = tpaep_mcp_save_elementor_page_data( $post_id, $page_data );
	if ( is_wp_error( $save_result ) ) {
		return $save_result; }
	return array(
		'element_id'  => $widget['id'],
		'widget_type' => $widget_type,
		'post_id'     => $post_id,
	);
}
