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

wp_register_ability('tpaep/tpaep-info-box', [
'label' => __('Info Box', 'theplus'),
    'description' => __('Adds The Plus "Info Box" widget (tp-info-box) with full style and layout options.', 'theplus'),
    '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],
        
        'info_box_layout'     => ['type' => 'string',  'enum' => ['single_layout', 'carousel_layout'], 'description' => 'Display layout'],
        'main_style'          => ['type' => 'string',  'enum' => ['style_1', 'style_2', 'style_3', 'style_4', 'style_7', 'style_11'], 'description' => 'Box style (Note: style_7 is Style-5 and style_11 is Style-6)'],
        
        'title'               => ['type' => 'string',  'description' => 'Box title'],
        'content_desc'        => ['type' => 'string',  'description' => 'Description text'],
        'title_tag'           => ['type' => 'string',  'description' => 'Title HTML tag (e.g. h1, h2, div, span)'],
        'text_align'          => ['type' => 'string',  'enum' => ['left', 'center', 'right'], 'description' => 'Content alignment'],
        
        'image_icon'          => ['type' => 'string',  'enum' => ['', 'icon', 'image', 'svg', 'lottie', 'text'], 'description' => 'Media type to display'],
        'icon_font_style'     => ['type' => 'string',  'enum' => ['font_awesome', 'font_awesome_5', 'icon_mind', 'icon_image'], 'description' => 'Icon family'],
        'icon_fontawesome'    => ['type' => 'string',  'description' => 'Font Awesome class string (e.g., fa fa-bank)'],
        'icon_fontawesome_5'  => ['type' => 'string',  'description' => 'Font Awesome 5 class string (e.g., fas fa-plus)'],
        'icons_mind'          => ['type' => 'string',  'description' => 'Icon Mind class string'],
        'icons_image'         => ['type' => 'string',  'description' => 'URL to image icon'],
        
        'svg_icon'            => ['type' => 'string',  'enum' => ['img', 'svg'], 'description' => 'SVG type (img/custom or svg/prebuilt)'],
        'svg_image'           => ['type' => 'string',  'description' => 'URL to custom SVG if svg_icon=img'],
        'svg_d_icon'          => ['type' => 'string',  'description' => 'Prebuilt SVG name if svg_icon=svg'],
        'select_image'        => ['type' => 'string',  'description' => 'URL to image if image_icon=image'],
        'lottieUrl'           => ['type' => 'string',  'description' => 'Animation URL if image_icon=lottie'],
        'tp_info_title'       => ['type' => 'string',  'description' => 'Text inside icon area if image_icon=text'],
        
        'display_button'      => ['type' => 'string',  'enum' => ['yes', 'no'], 'description' => 'Show CTA button', 'default' => 'no'],
        'button_style'        => ['type' => 'string',  'enum' => ['style-7', 'style-8', 'style-9'], 'description' => 'Button style'],
        'button_text'         => ['type' => 'string',  'description' => 'Button label'],
        'button_link'         => ['type' => 'string',  'description' => 'Button URL'],
        'button_icon_style'   => ['type' => 'string',  'enum' => ['', 'font_awesome', 'font_awesome_5', 'icon_mind']],
        'button_icon'         => ['type' => 'string',  'description' => 'Button Font Awesome 4 icon'],
        'button_icon_5'       => ['type' => 'string',  'description' => 'Button Font Awesome 5 icon'],
        'button_icons_mind'   => ['type' => 'string',  'description' => 'Button Icon Mind class'],
        'before_after'        => ['type' => 'string',  'enum' => ['before', 'after'], 'description' => 'Button Icon position'],
        
        'display_pin_text'    => ['type' => 'string',  'enum' => ['yes', 'no'], 'description' => 'Show pin text badge (for style_3)'],
        'pin_text_title'      => ['type' => 'string',  'description' => 'Pin text content'],
        
        'full_infobox_switch' => ['type' => 'string',  'enum' => ['yes', 'no'], 'description' => 'Make full infobox a link'],
        'full_infobox_link'   => ['type' => 'string',  'description' => 'Link URL if full infobox is a link'],
        
        'items'               => [
            'type' => 'array',
            'description' => 'Items for carousel layout',
            'items' => [
                'type' => 'object',
                'properties' => [
                    'loop_title' => ['type' => 'string'],
                    'loop_content_desc' => ['type' => 'string'],
                    'loop_url_link' => ['type' => 'string'],
                    'loop_image_icon' => ['type' => 'string', 'enum' => ['', 'icon', 'image', 'svg', 'lottie']],
                    'loop_svg_icon' => ['type' => 'string', 'enum' => ['img', 'svg']],
                    'loop_svg_image' => ['type' => 'string'],
                    'loop_svg_d_icon' => ['type' => 'string'],
                    'loop_select_image' => ['type' => 'string'],
                    'lottieUrl' => ['type' => 'string'],
                    'loop_icon_style' => ['type' => 'string', 'enum' => ['font_awesome', 'font_awesome_5', 'icon_mind']],
                    'loop_icon_fontawesome' => ['type' => 'string'],
                    'loop_icon_fontawesome_5' => ['type' => 'string'],
                    'loop_icons_mind' => ['type' => 'string'],
                    'loop_button_text' => ['type' => 'string'],
                    'loop_button_link' => ['type' => 'string'],
                ]
            ]
        ],
        
        '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'    => 'tpaep_mcp_theplus_info_box_ability',
    'permission_callback' => 'tpaep_mcp_theplus_info_box_permission',
    'meta' => ['show_in_rest' => true, 'mcp' => ['public' => true, 'type' => 'tool']],
]);

function tpaep_mcp_theplus_info_box_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_info_box_ability(array $input) {
    if (!tpaep_mcp_has_elementor()) { return new WP_Error('elementor_missing', __('Elementor must be active.', 'theplus')); }
    $widget_type = 'tp-info-box';
    if (!tpaep_mcp_has_registered_widget($widget_type)) { return new WP_Error('widget_missing', __('The Plus Info Box 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; }

    // Base map for keys natively matched by 1:1 ID strings.
    $string_keys = [
        'info_box_layout', 'main_style', 'title', 'title_tag', 'text_align', 'image_icon',
        'icon_font_style', 'icon_fontawesome', 'icons_mind', 'svg_icon', 'svg_d_icon',
        'tp_info_title', 'display_button', 'button_style', 'button_text', 'button_icon_style',
        'button_icon', 'button_icons_mind', 'before_after', 'display_pin_text',
        'pin_text_title', 'full_infobox_switch'
    ];
    $html_keys = ['content_desc'];

    $settings = [];
    foreach ($string_keys as $key) {
        if (isset($input[$key])) {
            $settings[$key] = sanitize_text_field($input[$key]);
        }
    }
    foreach ($html_keys as $key) {
        if (isset($input[$key])) {
            $settings[$key] = wp_kses_post($input[$key]);
        }
    }
    
    // Fix legacy inputs if sent
    if (isset($settings['info_box_layout']) && $settings['info_box_layout'] === 'listing') {
        $settings['info_box_layout'] = 'single_layout';
    } else if (isset($settings['info_box_layout']) && $settings['info_box_layout'] === 'carousel') {
        $settings['info_box_layout'] = 'carousel_layout';
    }
    if (isset($settings['main_style'])) {
        $settings['main_style'] = str_replace('-', '_', $settings['main_style']);
    }

    $url_keys = ['button_link', 'lottieUrl', 'full_infobox_link'];
    foreach ($url_keys as $key) {
        if (!empty($input[$key])) {
            if ($key === 'lottieUrl') {
                $settings['lottieUrl'] = ['url' => esc_url_raw($input[$key])];
            } else {
                $settings[$key] = ['url' => esc_url_raw($input[$key])];
            }
        }
    }
    
    $image_media_keys = ['select_image', 'svg_image', 'icons_image'];
    foreach ($image_media_keys as $key) {
        if (!empty($input[$key])) {
            $settings[$key] = ['url' => esc_url_raw($input[$key]), 'id' => ''];
        }
    }

    $fa5_keys = ['icon_fontawesome_5', 'button_icon_5'];
    foreach ($fa5_keys as $key) {
        if (!empty($input[$key])) {
            $settings[$key] = ['value' => sanitize_text_field($input[$key]), 'library' => 'solid'];
        }
    }

    if (!empty($input['items']) && is_array($input['items'])) {
        $loop_content = [];
        foreach ($input['items'] as $item) {
            $mapped_item = [];
            $loop_str_keys = [
                'loop_title', 'loop_image_icon', 'loop_svg_icon', 'loop_svg_d_icon',
                'loop_icon_style', 'loop_icon_fontawesome', 'loop_icons_mind', 'loop_button_text'
            ];
            foreach ($loop_str_keys as $key) {
                if (isset($item[$key])) {
                    $mapped_item[$key] = sanitize_text_field($item[$key]);
                }
            }
            if (isset($item['loop_content_desc'])) {
                $mapped_item['loop_content_desc'] = wp_kses_post($item['loop_content_desc']);
            }
            if (!empty($item['loop_url_link'])) {
                $mapped_item['loop_url_link'] = ['url' => esc_url_raw($item['loop_url_link'])];
            }
            if (!empty($item['lottieUrl'])) {
                $mapped_item['lottieUrl'] = ['url' => esc_url_raw($item['lottieUrl'])];
            }
            if (!empty($item['loop_button_link'])) {
                $mapped_item['loop_button_link'] = ['url' => esc_url_raw($item['loop_button_link'])];
            }
            if (!empty($item['loop_svg_image'])) {
                $mapped_item['loop_svg_image'] = ['url' => esc_url_raw($item['loop_svg_image']), 'id' => ''];
            }
            if (!empty($item['loop_select_image'])) {
                $mapped_item['loop_select_image'] = ['url' => esc_url_raw($item['loop_select_image']), 'id' => ''];
            }
            if (!empty($item['loop_icon_fontawesome_5'])) {
                $mapped_item['loop_icon_fontawesome_5'] = ['value' => sanitize_text_field($item['loop_icon_fontawesome_5']), 'library' => 'solid'];
            }
            $mapped_item['_id'] = uniqid('item_');
            $loop_content[] = $mapped_item;
        }
        $settings['loop_content'] = $loop_content;
    }

    $settings = tpaep_mcp_merge_widget_settings($settings, $input['settings'] ?? []);
    $widget = [
        'id'         => tpaep_mcp_generate_elementor_element_id(),
        'elType'     => 'widget',
        'widgetType' => $widget_type,
        'isInner'    => false,
        'settings'   => $settings,
        'elements'   => [],
    ];
    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 ['element_id' => $widget['id'], 'widget_type' => $widget_type, 'post_id' => $post_id];
}
