<?php
/**
 * GGM Commerce Attribute Tools
 *
 * MCP Tools for attribute group and product attribute management
 * Tools are executable actions that AI can invoke
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class GGM_Commerce_Attribute_Tools {

    /**
     * MCP Server instance
     * @var GGM_Commerce_MCP_Server
     */
    private $server;

    /**
     * Constructor
     *
     * @param GGM_Commerce_MCP_Server $server MCP server instance
     */
    public function __construct($server) {
        $this->server = $server;
        $this->register_tools();
    }

    /**
     * Register all attribute tools
     */
    private function register_tools() {
        // List attribute groups
        $this->server->register_tool(
            'list_attribute_groups',
            'List all attribute groups',
            [
                'type' => 'object',
                'properties' => [
                    'include_attributes' => [
                        'type' => 'boolean',
                        'description' => 'Include attributes in each group',
                        'default' => false
                    ]
                ]
            ],
            [$this, 'list_attribute_groups']
        );

        // Create attribute group
        $this->server->register_tool(
            'create_attribute_group',
            'Create a new attribute group',
            [
                'type' => 'object',
                'properties' => [
                    'name' => [
                        'type' => 'string',
                        'description' => 'Group name (required)'
                    ],
                    'description' => [
                        'type' => 'string',
                        'description' => 'Group description'
                    ],
                    'display_order' => [
                        'type' => 'integer',
                        'description' => 'Display order',
                        'default' => 0
                    ]
                ],
                'required' => ['name']
            ],
            [$this, 'create_attribute_group']
        );

        // List attributes
        $this->server->register_tool(
            'list_attributes',
            'List all attributes, optionally filtered by group',
            [
                'type' => 'object',
                'properties' => [
                    'group_id' => [
                        'type' => 'integer',
                        'description' => 'Filter by group ID',
                        'minimum' => 1
                    ]
                ]
            ],
            [$this, 'list_attributes']
        );

        // Create attribute
        $this->server->register_tool(
            'create_attribute',
            'Create a new attribute',
            [
                'type' => 'object',
                'properties' => [
                    'name' => [
                        'type' => 'string',
                        'description' => 'Attribute name (required)'
                    ],
                    'group_id' => [
                        'type' => 'integer',
                        'description' => 'Group ID to assign attribute to',
                        'minimum' => 1
                    ],
                    'attribute_type' => [
                        'type' => 'string',
                        'description' => 'Attribute type: text, number, or select',
                        'enum' => ['text', 'number', 'select'],
                        'default' => 'text'
                    ],
                    'options' => [
                        'type' => 'array',
                        'description' => 'Options for select type attributes',
                        'items' => ['type' => 'string']
                    ],
                    'unit' => [
                        'type' => 'string',
                        'description' => 'Unit of measurement (e.g., m², kg)'
                    ],
                    'filterable' => [
                        'type' => 'boolean',
                        'description' => 'Whether attribute can be used for filtering',
                        'default' => false
                    ],
                    'display_order' => [
                        'type' => 'integer',
                        'description' => 'Display order',
                        'default' => 0
                    ]
                ],
                'required' => ['name']
            ],
            [$this, 'create_attribute']
        );

        // Set product attributes
        $this->server->register_tool(
            'set_product_attributes',
            'Set attribute values for a product',
            [
                'type' => 'object',
                'properties' => [
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID (required)',
                        'minimum' => 1
                    ],
                    'attributes' => [
                        'type' => 'array',
                        'description' => 'Array of attribute values to set',
                        'items' => [
                            'type' => 'object',
                            'properties' => [
                                'attribute_id' => [
                                    'type' => 'integer',
                                    'description' => 'Attribute ID'
                                ],
                                'value' => [
                                    'type' => 'string',
                                    'description' => 'Attribute value'
                                ]
                            ],
                            'required' => ['attribute_id', 'value']
                        ]
                    ]
                ],
                'required' => ['product_id', 'attributes']
            ],
            [$this, 'set_product_attributes']
        );

        // Get product attributes
        $this->server->register_tool(
            'get_product_attributes',
            'Get all attribute values for a product',
            [
                'type' => 'object',
                'properties' => [
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID (required)',
                        'minimum' => 1
                    ]
                ],
                'required' => ['product_id']
            ],
            [$this, 'get_product_attributes']
        );

        // Add attributes from group to product
        $this->server->register_tool(
            'add_group_attributes_to_product',
            'Add all attributes from a group to a product (with empty values)',
            [
                'type' => 'object',
                'properties' => [
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID (required)',
                        'minimum' => 1
                    ],
                    'group_id' => [
                        'type' => 'integer',
                        'description' => 'Attribute group ID (required)',
                        'minimum' => 1
                    ]
                ],
                'required' => ['product_id', 'group_id']
            ],
            [$this, 'add_group_attributes_to_product']
        );
    }

    /**
     * List attribute groups
     */
    public function list_attribute_groups($args) {
        $attributes_class = GGM_Commerce_Attributes::get_instance();
        $groups = $attributes_class->get_attribute_groups();

        $result = [];
        foreach ($groups as $group) {
            $group_data = [
                'id' => (int) $group->id,
                'name' => $group->name,
                'description' => $group->description,
                'display_order' => (int) $group->display_order,
                'status' => $group->status
            ];

            if (!empty($args['include_attributes'])) {
                $attrs = $attributes_class->get_group_attributes($group->id);
                $group_data['attributes'] = array_map(function($attr) {
                    return [
                        'id' => (int) $attr->id,
                        'name' => $attr->name,
                        'attribute_type' => $attr->attribute_type,
                        'options' => !empty($attr->options) ? json_decode($attr->options, true) : [],
                        'unit' => $attr->unit,
                        'filterable' => (bool) $attr->filterable
                    ];
                }, $attrs);
            }

            $result[] = $group_data;
        }

        return [
            'success' => true,
            'groups' => $result,
            'count' => count($result)
        ];
    }

    /**
     * Create attribute group
     */
    public function create_attribute_group($args) {
        if (empty($args['name'])) {
            return ['success' => false, 'error' => 'Group name is required'];
        }

        $attributes_class = GGM_Commerce_Attributes::get_instance();
        $result = $attributes_class->create_attribute_group([
            'name' => sanitize_text_field($args['name']),
            'description' => sanitize_textarea_field($args['description'] ?? ''),
            'display_order' => intval($args['display_order'] ?? 0),
            'status' => 'active'
        ]);

        if (is_wp_error($result)) {
            return ['success' => false, 'error' => $result->get_error_message()];
        }

        return [
            'success' => true,
            'group_id' => $result,
            'message' => 'Attribute group created successfully'
        ];
    }

    /**
     * List attributes
     */
    public function list_attributes($args) {
        $attributes_class = GGM_Commerce_Attributes::get_instance();

        if (!empty($args['group_id'])) {
            $attrs = $attributes_class->get_group_attributes((int) $args['group_id']);
        } else {
            $attrs = $attributes_class->get_all_attributes();
        }

        $result = array_map(function($attr) {
            return [
                'id' => (int) $attr->id,
                'name' => $attr->name,
                'group_id' => $attr->group_id ? (int) $attr->group_id : null,
                'group_name' => $attr->group_name ?? null,
                'attribute_type' => $attr->attribute_type,
                'options' => !empty($attr->options) ? json_decode($attr->options, true) : [],
                'unit' => $attr->unit,
                'filterable' => (bool) ($attr->filterable ?? false),
                'display_order' => (int) $attr->display_order
            ];
        }, $attrs);

        return [
            'success' => true,
            'attributes' => $result,
            'count' => count($result)
        ];
    }

    /**
     * Create attribute
     */
    public function create_attribute($args) {
        if (empty($args['name'])) {
            return ['success' => false, 'error' => 'Attribute name is required'];
        }

        $attributes_class = GGM_Commerce_Attributes::get_instance();

        $data = [
            'name' => sanitize_text_field($args['name']),
            'attribute_type' => sanitize_text_field($args['attribute_type'] ?? 'text'),
            'unit' => sanitize_text_field($args['unit'] ?? ''),
            'filterable' => !empty($args['filterable']),
            'display_order' => intval($args['display_order'] ?? 0),
            'status' => 'active'
        ];

        if (!empty($args['group_id'])) {
            $data['group_id'] = (int) $args['group_id'];
        }

        if (!empty($args['options']) && is_array($args['options'])) {
            $data['options'] = $args['options'];
        }

        $result = $attributes_class->create_attribute($data);

        if (is_wp_error($result)) {
            return ['success' => false, 'error' => $result->get_error_message()];
        }

        // If group_id provided, also add to group membership
        if (!empty($args['group_id'])) {
            $attributes_class->add_attribute_to_group((int) $args['group_id'], $result);
        }

        return [
            'success' => true,
            'attribute_id' => $result,
            'message' => 'Attribute created successfully'
        ];
    }

    /**
     * Set product attributes
     */
    public function set_product_attributes($args) {
        if (empty($args['product_id'])) {
            return ['success' => false, 'error' => 'Product ID is required'];
        }

        if (empty($args['attributes']) || !is_array($args['attributes'])) {
            return ['success' => false, 'error' => 'Attributes array is required'];
        }

        $attributes_class = GGM_Commerce_Attributes::get_instance();

        $set_count = 0;
        foreach ($args['attributes'] as $attr) {
            if (empty($attr['attribute_id'])) {
                continue;
            }

            $result = $attributes_class->add_attribute_to_product(
                (int) $args['product_id'],
                (int) $attr['attribute_id'],
                sanitize_text_field($attr['value'] ?? '')
            );

            if (!is_wp_error($result)) {
                $set_count++;
            }
        }

        return [
            'success' => true,
            'attributes_set' => $set_count,
            'message' => "Set {$set_count} attribute(s) for product"
        ];
    }

    /**
     * Get product attributes
     */
    public function get_product_attributes($args) {
        if (empty($args['product_id'])) {
            return ['success' => false, 'error' => 'Product ID is required'];
        }

        $attributes_class = GGM_Commerce_Attributes::get_instance();
        $attrs = $attributes_class->get_product_attributes((int) $args['product_id']);

        $result = array_map(function($attr) {
            return [
                'attribute_id' => (int) $attr->attribute_id,
                'name' => $attr->name,
                'value' => $attr->attribute_value,
                'unit' => $attr->unit,
                'type' => $attr->attribute_type,
                'group_id' => $attr->group_id ? (int) $attr->group_id : null,
                'group_name' => $attr->group_name
            ];
        }, $attrs);

        return [
            'success' => true,
            'product_id' => (int) $args['product_id'],
            'attributes' => $result,
            'count' => count($result)
        ];
    }

    /**
     * Add all attributes from a group to a product
     */
    public function add_group_attributes_to_product($args) {
        if (empty($args['product_id'])) {
            return ['success' => false, 'error' => 'Product ID is required'];
        }

        if (empty($args['group_id'])) {
            return ['success' => false, 'error' => 'Group ID is required'];
        }

        $attributes_class = GGM_Commerce_Attributes::get_instance();
        $result = $attributes_class->add_attributes_from_group(
            (int) $args['product_id'],
            (int) $args['group_id']
        );

        if (is_wp_error($result)) {
            return ['success' => false, 'error' => $result->get_error_message()];
        }

        return [
            'success' => true,
            'added_attribute_ids' => $result,
            'count' => count($result),
            'message' => 'Added ' . count($result) . ' attribute(s) from group to product'
        ];
    }
}
