<?php
/**
 * GGM Commerce Inventory Tools
 *
 * MCP Tools for inventory management operations
 * Tools are executable actions that AI can invoke
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

class GGM_Commerce_Inventory_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 inventory tools
     */
    private function register_tools() {
        // Update product stock
        $this->server->register_tool(
            'update_product_stock',
            'Update product stock quantity',
            [
                'type' => 'object',
                'properties' => [
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID',
                        'minimum' => 1
                    ],
                    'stock_quantity' => [
                        'type' => 'integer',
                        'description' => 'New stock quantity',
                        'minimum' => 0
                    ]
                ],
                'required' => ['product_id', 'stock_quantity']
            ],
            [$this, 'update_product_stock']
        );

        // Adjust stock (increase or decrease)
        $this->server->register_tool(
            'adjust_product_stock',
            'Increase or decrease product stock by a specified amount',
            [
                'type' => 'object',
                'properties' => [
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID',
                        'minimum' => 1
                    ],
                    'adjustment' => [
                        'type' => 'integer',
                        'description' => 'Stock adjustment (positive to increase, negative to decrease)'
                    ],
                    'reason' => [
                        'type' => 'string',
                        'description' => 'Reason for adjustment'
                    ]
                ],
                'required' => ['product_id', 'adjustment']
            ],
            [$this, 'adjust_product_stock']
        );

        // Update product price
        $this->server->register_tool(
            'update_product_price',
            'Update product price',
            [
                'type' => 'object',
                'properties' => [
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID',
                        'minimum' => 1
                    ],
                    'price' => [
                        'type' => 'number',
                        'description' => 'New price',
                        'minimum' => 0
                    ],
                    'sale_price' => [
                        'type' => 'number',
                        'description' => 'Optional sale price',
                        'minimum' => 0
                    ]
                ],
                'required' => ['product_id', 'price']
            ],
            [$this, 'update_product_price']
        );

        // Bulk stock update
        $this->server->register_tool(
            'bulk_update_stock',
            'Update stock for multiple products at once',
            [
                'type' => 'object',
                'properties' => [
                    'updates' => [
                        'type' => 'array',
                        'description' => 'Array of product stock updates',
                        'items' => [
                            'type' => 'object',
                            'properties' => [
                                'product_id' => ['type' => 'integer', 'minimum' => 1],
                                'stock_quantity' => ['type' => 'integer', 'minimum' => 0]
                            ],
                            'required' => ['product_id', 'stock_quantity']
                        ]
                    ]
                ],
                'required' => ['updates']
            ],
            [$this, 'bulk_update_stock']
        );

        // Set low stock threshold
        $this->server->register_tool(
            'set_low_stock_threshold',
            'Set the low stock alert threshold for a product',
            [
                'type' => 'object',
                'properties' => [
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID',
                        'minimum' => 1
                    ],
                    'threshold' => [
                        'type' => 'integer',
                        'description' => 'Low stock threshold',
                        'minimum' => 0
                    ]
                ],
                'required' => ['product_id', 'threshold']
            ],
            [$this, 'set_low_stock_threshold']
        );
    }

    /**
     * Update product stock
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function update_product_stock($args) {
        $product_id = intval($args['product_id']);
        $stock_quantity = intval($args['stock_quantity']);

        global $wpdb;

        // Check product exists
        $product = $wpdb->get_row($wpdb->prepare(
            "SELECT id, name, stock FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $product_id
        ));

        if (!$product) {
            return [
                'success' => false,
                'error' => 'Product not found'
            ];
        }

        $old_stock = (int) $product->stock;

        // Determine stock status
        $stock_status = $stock_quantity > 0 ? 'instock' : 'outofstock';

        // Update product
        $updated = $wpdb->update(
            "{$wpdb->prefix}ggmc_products",
            [
                'stock' => $stock_quantity,
                'stock_status' => $stock_status,
                'updated_at' => current_time('mysql')
            ],
            ['id' => $product_id]
        );

        if ($updated === false) {
            return [
                'success' => false,
                'error' => 'Failed to update stock'
            ];
        }

        return [
            'success' => true,
            'message' => 'Stock updated successfully',
            'product_id' => $product_id,
            'product_name' => $product->name,
            'old_stock' => $old_stock,
            'new_stock' => $stock_quantity,
            'change' => $stock_quantity - $old_stock
        ];
    }

    /**
     * Adjust product stock (increase or decrease)
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function adjust_product_stock($args) {
        $product_id = intval($args['product_id']);
        $adjustment = intval($args['adjustment']);
        $reason = isset($args['reason']) ? sanitize_text_field($args['reason']) : 'Manual adjustment';

        global $wpdb;

        // Get current stock
        $product = $wpdb->get_row($wpdb->prepare(
            "SELECT id, name, stock FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $product_id
        ));

        if (!$product) {
            return [
                'success' => false,
                'error' => 'Product not found'
            ];
        }

        $old_stock = (int) $product->stock;
        $new_stock = max(0, $old_stock + $adjustment); // Prevent negative stock

        // Determine stock status
        $stock_status = $new_stock > 0 ? 'instock' : 'outofstock';

        // Update product
        $updated = $wpdb->update(
            "{$wpdb->prefix}ggmc_products",
            [
                'stock' => $new_stock,
                'stock_status' => $stock_status,
                'updated_at' => current_time('mysql')
            ],
            ['id' => $product_id]
        );

        if ($updated === false) {
            return [
                'success' => false,
                'error' => 'Failed to adjust stock'
            ];
        }

        $action = $adjustment > 0 ? 'increased' : 'decreased';

        return [
            'success' => true,
            'message' => "Stock {$action} successfully",
            'product_id' => $product_id,
            'product_name' => $product->name,
            'old_stock' => $old_stock,
            'new_stock' => $new_stock,
            'adjustment' => $adjustment,
            'reason' => $reason
        ];
    }

    /**
     * Update product price
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function update_product_price($args) {
        $product_id = intval($args['product_id']);
        $price = floatval($args['price']);
        $sale_price = isset($args['sale_price']) ? floatval($args['sale_price']) : null;

        global $wpdb;

        // Check product exists
        $product = $wpdb->get_row($wpdb->prepare(
            "SELECT id, name, price, sale_price FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $product_id
        ));

        if (!$product) {
            return [
                'success' => false,
                'error' => 'Product not found'
            ];
        }

        $old_price = (float) $product->price;
        $old_sale_price = isset($product->sale_price) ? (float) $product->sale_price : null;

        // Update data
        $update_data = [
            'price' => $price,
            'updated_at' => current_time('mysql')
        ];

        if ($sale_price !== null) {
            if ($sale_price >= $price) {
                return [
                    'success' => false,
                    'error' => 'Sale price must be less than regular price'
                ];
            }
            $update_data['sale_price'] = $sale_price;
        } else {
            $update_data['sale_price'] = null;
        }

        // Update product
        $updated = $wpdb->update(
            "{$wpdb->prefix}ggmc_products",
            $update_data,
            ['id' => $product_id]
        );

        if ($updated === false) {
            return [
                'success' => false,
                'error' => 'Failed to update price'
            ];
        }

        return [
            'success' => true,
            'message' => 'Price updated successfully',
            'product_id' => $product_id,
            'product_name' => $product->name,
            'old_price' => $old_price,
            'new_price' => $price,
            'old_sale_price' => $old_sale_price,
            'new_sale_price' => $sale_price
        ];
    }

    /**
     * Bulk update stock for multiple products
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function bulk_update_stock($args) {
        if (empty($args['updates']) || !is_array($args['updates'])) {
            return [
                'success' => false,
                'error' => 'Updates array is required'
            ];
        }

        global $wpdb;

        $results = [];
        $success_count = 0;
        $error_count = 0;

        foreach ($args['updates'] as $update) {
            $product_id = intval($update['product_id']);
            $stock_quantity = intval($update['stock_quantity']);

            // Get product
            $product = $wpdb->get_row($wpdb->prepare(
                "SELECT id, name FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
                $product_id
            ));

            if (!$product) {
                $results[] = [
                    'product_id' => $product_id,
                    'success' => false,
                    'error' => 'Product not found'
                ];
                $error_count++;
                continue;
            }

            // Determine stock status
            $stock_status = $stock_quantity > 0 ? 'instock' : 'outofstock';

            // Update
            $updated = $wpdb->update(
                "{$wpdb->prefix}ggmc_products",
                [
                    'stock' => $stock_quantity,
                    'stock_status' => $stock_status,
                    'updated_at' => current_time('mysql')
                ],
                ['id' => $product_id]
            );

            if ($updated === false) {
                $results[] = [
                    'product_id' => $product_id,
                    'product_name' => $product->name,
                    'success' => false,
                    'error' => 'Failed to update'
                ];
                $error_count++;
            } else {
                $results[] = [
                    'product_id' => $product_id,
                    'product_name' => $product->name,
                    'success' => true,
                    'new_stock' => $stock_quantity
                ];
                $success_count++;
            }
        }

        return [
            'success' => $error_count === 0,
            'message' => "Updated {$success_count} product(s), {$error_count} error(s)",
            'summary' => [
                'total' => count($args['updates']),
                'success' => $success_count,
                'errors' => $error_count
            ],
            'results' => $results
        ];
    }

    /**
     * Set low stock threshold for a product
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function set_low_stock_threshold($args) {
        $product_id = intval($args['product_id']);
        $threshold = intval($args['threshold']);

        global $wpdb;

        // Check product exists
        $product = $wpdb->get_row($wpdb->prepare(
            "SELECT id, name, stock, low_stock_threshold FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $product_id
        ));

        if (!$product) {
            return [
                'success' => false,
                'error' => 'Product not found'
            ];
        }

        $old_threshold = isset($product->low_stock_threshold) ? (int) $product->low_stock_threshold : 10;

        // Update product
        $updated = $wpdb->update(
            "{$wpdb->prefix}ggmc_products",
            [
                'low_stock_threshold' => $threshold,
                'updated_at' => current_time('mysql')
            ],
            ['id' => $product_id]
        );

        if ($updated === false) {
            return [
                'success' => false,
                'error' => 'Failed to update threshold'
            ];
        }

        $current_stock = (int) $product->stock;
        $is_low_stock = $current_stock <= $threshold && $current_stock > 0;

        return [
            'success' => true,
            'message' => 'Low stock threshold updated',
            'product_id' => $product_id,
            'product_name' => $product->name,
            'old_threshold' => $old_threshold,
            'new_threshold' => $threshold,
            'current_stock' => $current_stock,
            'is_low_stock' => $is_low_stock,
            'alert' => $is_low_stock ? 'WARNING: Product is currently below threshold' : null
        ];
    }
}
