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

wp_register_ability('tpaep/tpaep-flip-box', [
'label' => __('Flip Box (Pro)', 'theplus'),
    'description' => __('Adds The Plus "Flip Box" widget (tp-flip-box) to an Elementor container. Pro version with advanced template support.', '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],
        'flipbox_type'    => ['type' => 'string',  'enum' => ['basic', 'advanced'], 'description' => 'Primary Flipbox Style', 'default' => 'basic'],
        'info_box_layout' => ['type' => 'string',  'enum' => ['single_layout', 'carousel_layout'], 'description' => 'Sub Layout for Basic Type', 'default' => 'single_layout'],
        'advanced_type'   => ['type' => 'string',  'enum' => ['normal', 'repeater'], 'description' => 'Sub Layout for Advanced Type', 'default' => 'normal'],
        'flip_style'      => ['type' => 'string',  'enum' => ['horizontal', 'vertical'], 'description' => 'Flip direction', 'default' => 'horizontal'],
        
        'title'           => ['type' => 'string',  'description' => 'Front side heading'],
        'image_icon'      => ['type' => 'string',  'enum' => ['none', 'icon', 'image', 'svg'], 'description' => 'Front side icon type', 'default' => 'icon'],
        'select_image'    => ['type' => 'string',  'description' => 'URL for image (when image_icon=image)'],
        'content_desc'    => ['type' => 'string',  'description' => 'Back side HTML content description'],
        'display_button'  => ['type' => 'string',  'enum' => ['yes', 'no']],
        'button_text'     => ['type' => 'string',  'description' => 'Back side button text'],
        'button_link'     => ['type' => 'string',  'description' => 'Back side button URL'],
        'button_style'    => ['type' => 'string',  'enum' => ['style-7', 'style-8', 'style-9']],
        
        'normal_front_template' => ['type' => 'string', 'description' => 'Elementor Template ID for Front (advanced/normal)'],
        'normal_back_template'  => ['type' => 'string', 'description' => 'Elementor Template ID for Back (advanced/normal)'],
        
        'carousel_direction'    => ['type' => 'string', 'enum' => ['ltr', 'rtl']],
        'slider_desktop_column' => ['type' => 'string', 'enum' => ['1', '2', '3', '4', '5', '6']],
        'slider_infinite'       => ['type' => 'string', 'enum' => ['yes', 'no']],
        'slider_autoplay'       => ['type' => 'string', 'enum' => ['yes', 'no']],
        'autoplay_speed'        => ['type' => 'integer', 'description' => 'Autoplay speed in ms'],
        'slider_dots'           => ['type' => 'string', 'enum' => ['yes', 'no']],
        'slider_arrows'         => ['type' => 'string', 'enum' => ['yes', 'no']],
        
        'items' => [
            'type' => 'array',
            'description' => 'Items mapping for carousel or advanced repeater layouts',
            'items' => [
                'type' => 'object',
                'properties' => [
                    'loop_title'              => ['type' => 'string'],
                    'loop_image_icon'         => ['type' => 'string'],
                    'loop_select_image'       => ['type' => 'string', 'description' => 'Image URL'],
                    'loop_content_desc'       => ['type' => 'string', 'description' => 'Back side HTML descriptor'],
                    'loop_button_text'        => ['type' => 'string'],
                    'loop_button_link'        => ['type' => 'string'],
                    'repeater_front_template' => ['type' => 'string', 'description' => 'Advanced repeater template ID'],
                ]
            ]
        ],
        '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_pro_flip_box_ability',
    'permission_callback' => 'tpaep_mcp_theplus_pro_flip_box_permission',
    'meta' => ['show_in_rest' => true, 'mcp' => ['public' => true, 'type' => 'tool']],
]);

function tpaep_mcp_theplus_pro_flip_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_pro_flip_box_ability(array $input) {
    if (!tpaep_mcp_has_elementor()) { return new WP_Error('elementor_missing', __('Elementor must be active.', 'theplus')); }
    $widget_type = 'tp-flip-box';
    if (!tpaep_mcp_has_registered_widget($widget_type)) { return new WP_Error('widget_missing', __('The Plus Flip 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; }
    
    $settings = [
        'flipbox_type' => sanitize_key($input['flipbox_type'] ?? 'basic'),
    ];

    $string_keys = [
        'info_box_layout', 'advanced_type', 'flip_style', 'title', 'image_icon',
        'display_button', 'button_text', 'button_style', 'normal_front_template', 'normal_back_template',
        'carousel_direction', 'slider_desktop_column', 'slider_infinite', 'slider_autoplay',
        'slider_dots', 'slider_arrows'
    ];
    $number_keys = [
        'autoplay_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]);
        }
    }
    
    // Html content
    if (isset($input['content_desc'])) {
        $settings['content_desc'] = wp_kses_post($input['content_desc']);
    }
    // Backward compatibility for back_content => content_desc
    if (isset($input['back_content']) && !isset($input['content_desc'])) {
        $settings['content_desc'] = wp_kses_post($input['back_content']);
    }

    if (!empty($input['select_image'])) {
        $settings['select_image'] = ['url' => esc_url_raw($input['select_image'])];
    }
    
    if (!empty($input['button_link'])) {
        $settings['button_link'] = ['url' => esc_url_raw($input['button_link'])];
    }
    
    if (!empty($input['items']) && is_array($input['items'])) {
        $repeater_arr = array_map(function($item) {
            $tab = [];
            $item_string_keys = ['loop_title', 'loop_image_icon', 'loop_button_text', 'repeater_front_template'];
            foreach ($item_string_keys as $key) {
                if (isset($item[$key])) {
                    $tab[$key] = sanitize_text_field((string)$item[$key]);
                }
            }
            if (isset($item['loop_content_desc'])) {
                $tab['loop_content_desc'] = wp_kses_post($item['loop_content_desc']);
            }
            if (!empty($item['loop_select_image'])) {
                $tab['loop_select_image'] = ['url' => esc_url_raw($item['loop_select_image'])];
            }
            if (!empty($item['loop_button_link'])) {
                $tab['loop_button_link'] = ['url' => esc_url_raw($item['loop_button_link'])];
            }
            return $tab;
        }, $input['items']);
        
        if ($settings['flipbox_type'] === 'advanced' && ($settings['advanced_type'] ?? 'normal') === 'repeater') {
            $settings['advanced_repeaters'] = $repeater_arr;
        } else {
            $settings['loop_content'] = $repeater_arr;
        }
    }
    
    $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];
}
