<?php

namespace AIPT\Api\Chatbot\Actions;

use AIPT\Api\Chatbot\ChatActionInterface;
use AIPT\Api\Chatbot\ChatbotSettings;

/**
 * Add to Cart action for chatbot.
 *
 * Adds a product to the WooCommerce cart.
 * Disabled for variable products (requires option selection).
 *
 * @package AIPT\Api\Chatbot\Actions
 * @since 2.5.0
 */
class AddToCartAction implements ChatActionInterface {

    /**
     * Get unique action identifier.
     *
     * @return string Action ID.
     */
    public function getId(): string {
        return 'add_to_cart';
    }

    /**
     * Get action label for button.
     *
     * @param string $language Language code for translation.
     * @return string Translated label.
     */
    public function getLabel(string $language = 'en'): string {
        $labels = ChatbotSettings::getLabelsForLanguage($language);
        return $labels['add_to_cart'] ?? __( 'Add to Cart', 'ai-product-tools' );
    }

    /**
     * Get action icon identifier.
     *
     * @return string Icon name.
     */
    public function getIcon(): string {
        return 'cart-plus';
    }

    /**
     * Check if action is available for a specific product.
     *
     * Variable products are NOT available for direct cart add.
     *
     * @param int $product_id WooCommerce product ID.
     * @return bool True if action can be performed.
     */
    public function isAvailable(int $product_id): bool {
        $product = wc_get_product($product_id);

        if (!$product) {
            return false;
        }

        if ($product->is_type('variable')) {
            return false;
        }

        if ($product->is_type('grouped')) {
            return false;
        }

        if ($product->is_type('external')) {
            return false;
        }

        return $product->is_purchasable() && $product->is_in_stock();
    }

    /**
     * Execute the action.
     *
     * @param int   $product_id WooCommerce product ID.
     * @param array $params     Additional parameters from request.
     * @return array Execution result.
     */
    public function execute(int $product_id, array $params = []): array {
        $product = wc_get_product($product_id);

        if (!$product) {
            return [
                'success' => false,
                'message' => __('Product not found.', 'ai-product-tools'),
            ];
        }

        if ($product->is_type('variable')) {
            return [
                'success' => false,
                'message' => __('Please select options on the product page.', 'ai-product-tools'),
                'data' => [
                    'is_variable' => true,
                    'permalink' => $product->get_permalink(),
                ],
            ];
        }

        if (!$product->is_purchasable()) {
            return [
                'success' => false,
                'message' => __('This product cannot be purchased.', 'ai-product-tools'),
            ];
        }

        if (!$product->is_in_stock()) {
            return [
                'success' => false,
                'message' => __('This product is out of stock.', 'ai-product-tools'),
            ];
        }

        $quantity = isset($params['quantity']) ? absint($params['quantity']) : 1;
        $quantity = max(1, $quantity);

        $max_purchase_qty = $product->get_max_purchase_quantity();
        if ( $max_purchase_qty > 0 && $quantity > $max_purchase_qty ) {
            return [
                'success' => false,
                'message' => sprintf(
                    /* translators: %d: maximum purchase quantity */
                    __('You can only purchase a maximum of %d of this product.', 'ai-product-tools'),
                    $max_purchase_qty
                ),
            ];
        }

        if ( $product->managing_stock() ) {
            $stock_qty = $product->get_stock_quantity();
            if ( $stock_qty !== null && $quantity > $stock_qty ) {
                return [
                    'success' => false,
                    'message' => sprintf(
                        /* translators: %d: available stock quantity */
                        __('Only %d units are available.', 'ai-product-tools'),
                        $stock_qty
                    ),
                ];
            }
        }

        if ( ! WC()->session || ! WC()->cart ) {
            wc_load_cart();
        }

        if ( ! WC()->cart ) {
            return [
                'success' => false,
                'message' => __('Cart is not available.', 'ai-product-tools'),
            ];
        }

        $cart_item_key = WC()->cart->add_to_cart($product_id, $quantity);

        if ($cart_item_key) {
            return [
                'success' => true,
                'message' => __('Product added to cart.', 'ai-product-tools'),
                'data' => [
                    'cart_hash' => WC()->cart->get_cart_hash(),
                    'cart_count' => WC()->cart->get_cart_contents_count(),
                    'cart_item_key' => $cart_item_key,
                ],
            ];
        }

        return [
            'success' => false,
            'message' => __('Could not add product to cart.', 'ai-product-tools'),
        ];
    }

    /**
     * Get action priority for ordering.
     *
     * @return int Priority value.
     */
    public function getPriority(): int {
        return 20;
    }
}
