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

wp_register_ability('tpaep/tpaep-number-counter', [
'label' => __('Number Counter', 'theplus'),
    'description' => __('Adds The Plus "Number Counter" widget (tp-number-counter) with animation and symbol 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],
        'style'            => ['type' => 'string',  'enum' => ['style-1', 'style-2'], 'description' => 'Visual style', 'default' => 'style-1'],
        'title'            => ['type' => 'string',  'description' => 'Label text'],
        'alignment'        => ['type' => 'string',  'enum' => ['left', 'center', 'right'], 'description' => 'Horizontal alignment for style-1', 'default' => 'center'],
        'alignment_2'      => ['type' => 'string',  'enum' => ['left', 'right'], 'description' => 'Horizontal alignment for style-2', 'default' => 'left'],
        
        'max_number'       => ['type' => 'integer', 'description' => 'Target value to count to', 'default' => 1000],
        'min_number'       => ['type' => 'integer', 'description' => 'Starting value', 'default' => 0],
        'increment_number' => ['type' => 'integer', 'description' => 'Number Gap for Animation in each step', 'default' => 5],
        'delay_number'     => ['type' => 'integer', 'description' => 'Time Delay in ms between each number increase', 'default' => 5],
        
        'symbol'           => ['type' => 'string',  'description' => 'Prefix/Suffix symbol (e.g. %, +)'],
        'symbol_position'  => ['type' => 'string',  'enum' => ['before', 'after'], 'description' => 'Position of symbol', 'default' => 'after'],
        
        'icon_type'        => ['type' => 'string',  'enum' => ['', 'icon', 'image', 'svg', 'lottie'], 'description' => 'Select Media Type for icon'],
        'icon_font_style'  => ['type' => 'string',  'enum' => ['font_awesome', 'font_awesome_5', 'icon_mind'], 'description' => 'Icon style if icon_type is icon'],
        'icon_fontawesome' => ['type' => 'string',  'description' => 'Font Awesome 4 icon class'],
        'icon_fontawesome_5'=>['type' => 'string',  'description' => 'Font Awesome 5 icon class'],
        'icons_mind'       => ['type' => 'string',  'description' => 'Icons Mind icon class'],
        
        'svg_icon'         => ['type' => 'string',  'enum' => ['img', 'svg'], 'description' => 'SVG type if icon_type is svg'],
        'svg_image'        => ['type' => 'string',  'description' => 'URL to custom SVG file if svg_icon is img'],
        'svg_d_icon'       => ['type' => 'string',  'description' => 'Prebuilt SVG filename if svg_icon is svg'],
        
        'icon_image'       => ['type' => 'string',  'description' => 'URL to image if icon_type is image'],
        'lottieUrl'        => ['type' => 'string',  'description' => 'URL to lottie JSON if icon_type is lottie'],
        'url_link'         => ['type' => 'string',  'description' => 'External link URL for the entire widget'],
        
        '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_number_counter_ability',
    'permission_callback' => 'tpaep_mcp_theplus_number_counter_permission',
    'meta' => ['show_in_rest' => true, 'mcp' => ['public' => true, 'type' => 'tool']],
]);

function tpaep_mcp_theplus_number_counter_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_number_counter_ability(array $input) {
    if (!tpaep_mcp_has_elementor()) { return new WP_Error('elementor_missing', __('Elementor must be active.', 'theplus')); }
    $widget_type = 'tp-number-counter';
    if (!tpaep_mcp_has_registered_widget($widget_type)) { return new WP_Error('widget_missing', __('The Plus Number Counter 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 = [
        'style'           => sanitize_key($input['style'] ?? 'style-1'),
        'title'           => sanitize_text_field($input['title'] ?? 'Counter'),
        'alignment'       => sanitize_key($input['alignment'] ?? 'center'),
        'alignment_2'     => sanitize_key($input['alignment_2'] ?? 'left'),
        'max_number'      => intval($input['max_number'] ?? 1000),
        'min_number'      => intval($input['min_number'] ?? 0),
        'increment_number'=> ['size' => intval($input['increment_number'] ?? 5)],
        'delay_number'    => ['size' => intval($input['delay_number'] ?? 5)],
        'symbol'          => sanitize_text_field($input['symbol'] ?? ''),
        'symbol_position' => sanitize_key($input['symbol_position'] ?? 'after'),
    ];

    $string_keys = ['icon_type', 'icon_font_style', 'icon_fontawesome', 'icons_mind', 'svg_icon', 'svg_d_icon'];
    foreach ($string_keys as $key) {
        if (isset($input[$key])) {
            $settings[$key] = sanitize_text_field($input[$key]);
        }
    }

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

    $image_media_keys = ['svg_image', 'icon_image'];
    foreach ($image_media_keys as $key) {
        if (!empty($input[$key])) {
            $settings[$key] = ['url' => esc_url_raw($input[$key]), 'id' => ''];
        }
    }

    $url_keys = ['lottieUrl', 'url_link'];
    foreach ($url_keys as $key) {
        if (!empty($input[$key])) {
            $settings[$key] = ['url' => esc_url_raw($input[$key])];
        }
    }

    $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];
}
