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

wp_register_ability('sprout/tpae-advanced-buttons', [
'label' => __('Advanced Buttons', 'sprout-mcp'),
    'description' => __('Adds The Plus "Advanced Buttons" widget (tp-advanced-buttons) to an Elementor container.', 'sprout-mcp'),
    'category' => 'tpae',
    'input_schema' => ['type' => 'object', 'properties' => [
        'post_id'               => ['type' => 'integer', 'description' => 'Elementor page/post ID'],
        'parent_id'             => ['type' => 'string',  'description' => 'Target Elementor container ID'],
        'position'              => ['type' => 'integer', 'description' => 'Insert position (-1 = append)', 'default' => -1],
        'ab_button_type'        => ['type' => 'string',  'enum' => ['cta', 'download'], 'description' => 'Button category', 'default' => 'cta'],
        'cta_button_style'      => ['type' => 'string',  'enum' => ['tp_cta_st_1', 'tp_cta_st_2', 'tp_cta_st_3', 'tp_cta_st_4', 'tp_cta_st_5', 'tp_cta_st_6', 'tp_cta_st_7', 'tp_cta_st_8', 'tp_cta_st_9', 'tp_cta_st_10', 'tp_cta_st_11', 'tp_cta_st_12', 'tp_cta_st_13', 'tp_cta_st_14'], 'description' => 'CTA style options', 'default' => 'tp_cta_st_1'],
        'download_button_style' => ['type' => 'string',  'enum' => ['tp_download_st_1', 'tp_download_st_2', 'tp_download_st_3', 'tp_download_st_4', 'tp_download_st_5'], 'description' => 'Download style options', 'default' => 'tp_download_st_1'],
        'common_button_text'    => ['type' => 'string',  'description' => 'Primary button label', 'default' => 'Read More'],
        'dbt_button_text_2'     => ['type' => 'string',  'description' => 'Loading Text (Download St 5)', 'default' => 'downloading...'],
        'dbt_button_text_3'     => ['type' => 'string',  'description' => 'Success Text (Download St 5)', 'default' => 'done!'],
        'common_button_text_2'  => ['type' => 'string',  'description' => 'Extra Text 1 (CTA St 6/9/13)', 'default' => 'Theplus'],
        'db_common_button_text_2'=> ['type' => 'string',  'description' => 'Extra Text (Download St 3)', 'default' => 'Theplus'],
        'db_common_min_width'   => ['type' => 'integer', 'description' => 'Minimum Width (Download St 3)', 'default' => 115],
        'common_button_text_3'  => ['type' => 'string',  'description' => 'Extra Text 2 (CTA St 6/9/13)', 'default' => 'Theplus'],
        'common_emoji_normal'   => ['type' => 'string',  'description' => 'Normal Emoji (CTA St 8)', 'default' => '💯'],
        'common_emoji_hover'    => ['type' => 'string',  'description' => 'Hover Emoji (CTA St 8)', 'default' => '👏'],
        'st14_button_width'     => ['type' => 'integer', 'description' => 'Button Width (CTA St 14)'],
        'st10_button_width'     => ['type' => 'integer', 'description' => 'Button Width (CTA St 10)', 'default' => 155],
        'st10_button_height'    => ['type' => 'integer', 'description' => 'Button Height (CTA St 10)', 'default' => 55],
        'button_link'           => ['type' => 'string',  'description' => 'URL for the button'],
        'download_file_name'    => ['type' => 'string',  'description' => 'Name for the downloaded file', 'default' => 'download'],
        'button_align'          => ['type' => 'string',  'enum' => ['flex-start', 'center', 'flex-end'], 'description' => 'Horizontal alignment', 'default' => 'flex-start'],
        'button_align_d_st5'    => ['type' => 'string',  'enum' => ['flex-start', 'center', 'flex-end'], 'description' => 'Alignment (Download St 5)', 'default' => 'flex-start'],
        'tooltip_alignment'     => ['type' => 'string',  'enum' => ['st13_tt_align_left', 'st13_tt_align_right'], 'description' => 'Tooltip Position (CTA St 13)', 'default' => 'st13_tt_align_left'],
        'min_width_st5'         => ['type' => 'integer', 'description' => 'Minimum Width (CTA St 5)'],
        'animate_duration_normal'=> ['type' => 'integer', 'description' => 'Normal Animation Speed (1-10)'],
        'animate_duration_hover'=> ['type' => 'integer', 'description' => 'Hover Animation Speed (1-10)'],
        'marquee_speed'         => ['type' => 'integer', 'description' => 'Marquee Speed (CTA St 6)', 'default' => 12],
        'marquee_direction'     => ['type' => 'string',  'enum' => ['left', 'right'], 'description' => 'Marquee Direction (CTA St 6)', 'default' => 'left'],
        'settings'              => ['type' => 'object',  'description' => 'Raw Elementor control key/value pairs to merge.'],
    ], 'required' => ['post_id', 'parent_id'], 'additionalProperties' => false],
    'output_schema' => ['type' => 'object', 'properties' => [
        'element_id'  => ['type' => 'string'],
        'widget_type' => ['type' => 'string'],
        'post_id'     => ['type' => 'integer'],
    ]],
    'execute_callback'    => 'sprout_mcp_theplus_advanced_buttons_ability',
    'permission_callback' => 'sprout_mcp_theplus_advanced_buttons_permission',
    'meta' => ['show_in_rest' => true, 'mcp' => ['public' => true, 'type' => 'tool']],
]);

function sprout_mcp_theplus_advanced_buttons_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 sprout_mcp_theplus_advanced_buttons_ability(array $input) {
    if (!sprout_mcp_has_elementor()) { return new WP_Error('elementor_missing', __('Elementor must be active.', 'sprout-mcp')); }
    $widget_type = 'tp-advanced-buttons';
    if (!sprout_mcp_has_registered_widget($widget_type)) { return new WP_Error('widget_missing', __('The Plus Advanced Buttons widget is not registered.', 'sprout-mcp')); }
    $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.', 'sprout-mcp')); }
    $post = get_post($post_id);
    if (!$post instanceof WP_Post) { return new WP_Error('invalid_post', __('Target post was not found.', 'sprout-mcp')); }
    $page_data = sprout_mcp_get_elementor_page_data($post_id);
    if (is_wp_error($page_data)) { return $page_data; }

    $settings = [
        'ab_button_type'        => sanitize_key($input['ab_button_type'] ?? 'cta'),
        'button_align'          => sanitize_key($input['button_align'] ?? 'flex-start'),
        'common_button_text'    => sanitize_text_field($input['common_button_text'] ?? 'Click Here'),
        'button_link'           => ['url' => esc_url_raw($input['button_link'] ?? '#')],
    ];

    $string_keys = [
        'cta_button_style', 'download_button_style', 'dbt_button_text_2', 'dbt_button_text_3',
        'common_button_text_2', 'db_common_button_text_2', 'common_button_text_3',
        'common_emoji_normal', 'common_emoji_hover', 'download_file_name',
        'button_align_d_st5', 'tooltip_alignment', 'marquee_direction'
    ];

    $number_keys = [
        'st14_button_width', 'st10_button_width', 'st10_button_height', 
        'animate_duration_normal', 'animate_duration_hover', 'marquee_speed'
    ];
    
    foreach ($string_keys as $key) {
        if (isset($input[$key])) {
            $settings[$key] = sanitize_text_field($input[$key]);
        }
    }
    foreach ($number_keys as $key) {
        if (isset($input[$key])) {
            $settings[$key] = intval($input[$key]);
        }
    }

    if (isset($input['db_common_min_width'])) {
        $settings['db_common_min_width'] = ['unit' => 'px', 'size' => intval($input['db_common_min_width'])];
    }
    if (isset($input['min_width_st5'])) {
        $settings['min_width_st5'] = ['unit' => 'px', 'size' => intval($input['min_width_st5'])];
    }

    $settings = sprout_mcp_merge_widget_settings($settings, $input['settings'] ?? []);
    $widget = [
        'id'         => sprout_mcp_generate_elementor_element_id(),
        'elType'     => 'widget',
        'widgetType' => $widget_type,
        'isInner'    => false,
        'settings'   => $settings,
        'elements'   => [],
    ];
    if (!sprout_mcp_insert_elementor_element($page_data, $parent_id, $widget, $position)) { return new WP_Error('parent_not_found', __('Parent container not found.', 'sprout-mcp')); }
    $save_result = sprout_mcp_save_elementor_page_data($post_id, $page_data);
    if (is_wp_error($save_result)) { return $save_result; }
    return ['element_id' => $widget['id'], 'widget_type' => $widget_type, 'post_id' => $post_id];
}
