<?php
/**
 * GGM Commerce Cart Tools
 *
 * MCP Tools for cart 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_Cart_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 cart tools
     */
    private function register_tools() {
        // Add to cart
        $this->server->register_tool(
            'add_to_cart',
            'Add a product to the shopping cart',
            [
                'type' => 'object',
                'properties' => [
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID to add to cart',
                        'minimum' => 1
                    ],
                    'quantity' => [
                        'type' => 'integer',
                        'description' => 'Quantity to add',
                        'minimum' => 1,
                        'default' => 1
                    ],
                    'session_id' => [
                        'type' => 'string',
                        'description' => 'Session ID for the cart (optional, will create new if not provided)'
                    ]
                ],
                'required' => ['product_id']
            ],
            [$this, 'add_to_cart']
        );

        // Get cart contents
        $this->server->register_tool(
            'get_cart_contents',
            'Retrieve current cart contents with product details',
            [
                'type' => 'object',
                'properties' => [
                    'session_id' => [
                        'type' => 'string',
                        'description' => 'Session ID for the cart'
                    ]
                ],
                'required' => ['session_id']
            ],
            [$this, 'get_cart_contents']
        );

        // Update cart item quantity
        $this->server->register_tool(
            'update_cart_item',
            'Update the quantity of a cart item',
            [
                'type' => 'object',
                'properties' => [
                    'session_id' => [
                        'type' => 'string',
                        'description' => 'Session ID for the cart'
                    ],
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID to update',
                        'minimum' => 1
                    ],
                    'quantity' => [
                        'type' => 'integer',
                        'description' => 'New quantity (0 to remove)',
                        'minimum' => 0
                    ]
                ],
                'required' => ['session_id', 'product_id', 'quantity']
            ],
            [$this, 'update_cart_item']
        );

        // Remove from cart
        $this->server->register_tool(
            'remove_from_cart',
            'Remove a product from the shopping cart',
            [
                'type' => 'object',
                'properties' => [
                    'session_id' => [
                        'type' => 'string',
                        'description' => 'Session ID for the cart'
                    ],
                    'product_id' => [
                        'type' => 'integer',
                        'description' => 'Product ID to remove',
                        'minimum' => 1
                    ]
                ],
                'required' => ['session_id', 'product_id']
            ],
            [$this, 'remove_from_cart']
        );

        // Clear cart
        $this->server->register_tool(
            'clear_cart',
            'Remove all items from the shopping cart',
            [
                'type' => 'object',
                'properties' => [
                    'session_id' => [
                        'type' => 'string',
                        'description' => 'Session ID for the cart'
                    ]
                ],
                'required' => ['session_id']
            ],
            [$this, 'clear_cart']
        );
    }

    /**
     * Add product to cart
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function add_to_cart($args) {
        $product_id = intval($args['product_id']);
        $quantity = isset($args['quantity']) ? intval($args['quantity']) : 1;
        $session_id = isset($args['session_id']) ? sanitize_text_field($args['session_id']) : $this->generate_session_id();

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

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

        // Check stock availability
        if ($product->stock < $quantity) {
            return [
                'success' => false,
                'error' => 'Insufficient stock. Available: ' . $product->stock
            ];
        }

        // Check if product already in cart
        $existing = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_cart
            WHERE session_id = %s AND product_id = %d",
            $session_id,
            $product_id
        ));

        if ($existing) {
            // Update quantity
            $new_quantity = $existing->quantity + $quantity;

            if ($product->stock < $new_quantity) {
                return [
                    'success' => false,
                    'error' => 'Insufficient stock for total quantity. Available: ' . $product->stock
                ];
            }

            $wpdb->update(
                "{$wpdb->prefix}ggmc_cart",
                ['quantity' => $new_quantity],
                ['id' => $existing->id]
            );
        } else {
            // Insert new cart item
            $wpdb->insert(
                "{$wpdb->prefix}ggmc_cart",
                [
                    'session_id' => $session_id,
                    'product_id' => $product_id,
                    'quantity' => $quantity,
                    'created_at' => current_time('mysql')
                ]
            );
        }

        // Get updated cart totals
        $cart_data = $this->get_cart_data($session_id);

        return [
            'success' => true,
            'message' => "Added {$quantity}x {$product->name} to cart",
            'session_id' => $session_id,
            'cart' => $cart_data
        ];
    }

    /**
     * Get cart contents
     *
     * @param array $args Tool arguments
     * @return array Cart contents
     */
    public function get_cart_contents($args) {
        $session_id = sanitize_text_field($args['session_id']);

        $cart_data = $this->get_cart_data($session_id);

        return [
            'success' => true,
            'session_id' => $session_id,
            'cart' => $cart_data
        ];
    }

    /**
     * Update cart item quantity
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function update_cart_item($args) {
        $session_id = sanitize_text_field($args['session_id']);
        $product_id = intval($args['product_id']);
        $quantity = intval($args['quantity']);

        global $wpdb;

        // If quantity is 0, remove item
        if ($quantity === 0) {
            $wpdb->delete(
                "{$wpdb->prefix}ggmc_cart",
                [
                    'session_id' => $session_id,
                    'product_id' => $product_id
                ]
            );

            $cart_data = $this->get_cart_data($session_id);

            return [
                'success' => true,
                'message' => 'Item removed from cart',
                'cart' => $cart_data
            ];
        }

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

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

        if ($product->stock < $quantity) {
            return [
                'success' => false,
                'error' => 'Insufficient stock. Available: ' . $product->stock
            ];
        }

        // Update quantity
        $updated = $wpdb->update(
            "{$wpdb->prefix}ggmc_cart",
            ['quantity' => $quantity],
            [
                'session_id' => $session_id,
                'product_id' => $product_id
            ]
        );

        if ($updated === false) {
            return [
                'success' => false,
                'error' => 'Cart item not found'
            ];
        }

        $cart_data = $this->get_cart_data($session_id);

        return [
            'success' => true,
            'message' => 'Cart updated',
            'cart' => $cart_data
        ];
    }

    /**
     * Remove item from cart
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function remove_from_cart($args) {
        $session_id = sanitize_text_field($args['session_id']);
        $product_id = intval($args['product_id']);

        global $wpdb;

        $deleted = $wpdb->delete(
            "{$wpdb->prefix}ggmc_cart",
            [
                'session_id' => $session_id,
                'product_id' => $product_id
            ]
        );

        if ($deleted === false || $deleted === 0) {
            return [
                'success' => false,
                'error' => 'Cart item not found'
            ];
        }

        $cart_data = $this->get_cart_data($session_id);

        return [
            'success' => true,
            'message' => 'Item removed from cart',
            'cart' => $cart_data
        ];
    }

    /**
     * Clear entire cart
     *
     * @param array $args Tool arguments
     * @return array Result
     */
    public function clear_cart($args) {
        $session_id = sanitize_text_field($args['session_id']);

        global $wpdb;

        $wpdb->delete(
            "{$wpdb->prefix}ggmc_cart",
            ['session_id' => $session_id]
        );

        return [
            'success' => true,
            'message' => 'Cart cleared',
            'cart' => [
                'items' => [],
                'count' => 0,
                'total' => 0
            ]
        ];
    }

    /**
     * Get cart data with product details
     *
     * @param string $session_id Session ID
     * @return array Cart data
     */
    private function get_cart_data($session_id) {
        global $wpdb;

        $items = $wpdb->get_results($wpdb->prepare(
            "SELECT
                c.*,
                p.name,
                p.sku,
                p.price,
                p.image_url,
                p.stock
            FROM {$wpdb->prefix}ggmc_cart c
            INNER JOIN {$wpdb->prefix}ggmc_products p ON c.product_id = p.id
            WHERE c.session_id = %s",
            $session_id
        ));

        $total = 0;
        $count = 0;

        foreach ($items as &$item) {
            $item->subtotal = $item->price * $item->quantity;
            $total += $item->subtotal;
            $count += $item->quantity;
        }

        return [
            'items' => $items,
            'count' => $count,
            'total' => $total
        ];
    }

    /**
     * Generate a new session ID
     *
     * @return string Session ID
     */
    private function generate_session_id() {
        return 'mcp_' . bin2hex(random_bytes(16));
    }
}
