<?php
/**
 * GGM Commerce MCP Discount Tools
 * Provides MCP tools for discount and voucher operations
 *
 * @package GGM_Commerce
 */

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

/**
 * MCP Discount Tools class
 */
class GGM_Commerce_MCP_Discount_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();
    }

    /**
     * Check if discounts feature is activated
     *
     * @return bool
     */
    private function is_activated() {
        return class_exists( 'GGM_Commerce_Discounts' ) && GGM_Commerce_Discounts::is_activated();
    }

    /**
     * Register MCP tools
     */
    private function register_tools() {
        // Create discount tool.
        $this->server->register_tool(
            'create_discount',
            __( 'Create a new discount code, percentage discount, fixed discount, or voucher', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'code'                   => array(
                        'type'        => 'string',
                        'description' => __( 'Unique discount code (will be uppercased)', 'ggm-commerce' ),
                    ),
                    'name'                   => array(
                        'type'        => 'string',
                        'description' => __( 'Internal name for the discount', 'ggm-commerce' ),
                    ),
                    'description'            => array(
                        'type'        => 'string',
                        'description' => __( 'Optional description', 'ggm-commerce' ),
                    ),
                    'discount_type'          => array(
                        'type'        => 'string',
                        'enum'        => array( 'percentage', 'fixed_amount', 'voucher' ),
                        'description' => __( 'Type of discount: percentage, fixed_amount, or voucher', 'ggm-commerce' ),
                        'default'     => 'percentage',
                    ),
                    'amount'                 => array(
                        'type'        => 'number',
                        'description' => __( 'Discount amount (percentage value or currency amount)', 'ggm-commerce' ),
                    ),
                    'usage_limit'            => array(
                        'type'        => 'integer',
                        'description' => __( 'Maximum number of times this discount can be used (null for unlimited)', 'ggm-commerce' ),
                    ),
                    'usage_limit_per_user'   => array(
                        'type'        => 'integer',
                        'description' => __( 'Maximum times a single customer can use this discount', 'ggm-commerce' ),
                    ),
                    'minimum_order_amount'   => array(
                        'type'        => 'number',
                        'description' => __( 'Minimum order total required to use this discount', 'ggm-commerce' ),
                    ),
                    'maximum_discount_amount' => array(
                        'type'        => 'number',
                        'description' => __( 'Maximum discount amount (caps percentage discounts)', 'ggm-commerce' ),
                    ),
                    'valid_from'             => array(
                        'type'        => 'string',
                        'description' => __( 'Start date/time for validity (YYYY-MM-DD HH:MM:SS)', 'ggm-commerce' ),
                    ),
                    'valid_to'               => array(
                        'type'        => 'string',
                        'description' => __( 'End date/time for validity (YYYY-MM-DD HH:MM:SS)', 'ggm-commerce' ),
                    ),
                    'free_shipping'          => array(
                        'type'        => 'boolean',
                        'description' => __( 'Whether this discount includes free shipping', 'ggm-commerce' ),
                    ),
                    'single_use_voucher'     => array(
                        'type'        => 'boolean',
                        'description' => __( 'For vouchers: entire balance used at once (true) or partial use allowed (false)', 'ggm-commerce' ),
                    ),
                    'status'                 => array(
                        'type'        => 'string',
                        'enum'        => array( 'active', 'inactive' ),
                        'description' => __( 'Discount status', 'ggm-commerce' ),
                        'default'     => 'active',
                    ),
                ),
                'required'   => array( 'code', 'name', 'amount' ),
            ),
            array( $this, 'create_discount' )
        );

        // Update discount tool.
        $this->server->register_tool(
            'update_discount',
            __( 'Update an existing discount', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'id'                     => array(
                        'type'        => 'integer',
                        'description' => __( 'Discount ID to update', 'ggm-commerce' ),
                    ),
                    'name'                   => array(
                        'type'        => 'string',
                        'description' => __( 'Internal name for the discount', 'ggm-commerce' ),
                    ),
                    'description'            => array(
                        'type'        => 'string',
                        'description' => __( 'Optional description', 'ggm-commerce' ),
                    ),
                    'amount'                 => array(
                        'type'        => 'number',
                        'description' => __( 'Discount amount', 'ggm-commerce' ),
                    ),
                    'usage_limit'            => array(
                        'type'        => 'integer',
                        'description' => __( 'Maximum number of times this discount can be used', 'ggm-commerce' ),
                    ),
                    'usage_limit_per_user'   => array(
                        'type'        => 'integer',
                        'description' => __( 'Maximum times a single customer can use this discount', 'ggm-commerce' ),
                    ),
                    'minimum_order_amount'   => array(
                        'type'        => 'number',
                        'description' => __( 'Minimum order total required', 'ggm-commerce' ),
                    ),
                    'maximum_discount_amount' => array(
                        'type'        => 'number',
                        'description' => __( 'Maximum discount amount', 'ggm-commerce' ),
                    ),
                    'valid_from'             => array(
                        'type'        => 'string',
                        'description' => __( 'Start date/time for validity', 'ggm-commerce' ),
                    ),
                    'valid_to'               => array(
                        'type'        => 'string',
                        'description' => __( 'End date/time for validity', 'ggm-commerce' ),
                    ),
                    'free_shipping'          => array(
                        'type'        => 'boolean',
                        'description' => __( 'Whether this discount includes free shipping', 'ggm-commerce' ),
                    ),
                    'status'                 => array(
                        'type'        => 'string',
                        'enum'        => array( 'active', 'inactive' ),
                        'description' => __( 'Discount status', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'id' ),
            ),
            array( $this, 'update_discount' )
        );

        // Delete discount tool.
        $this->server->register_tool(
            'delete_discount',
            __( 'Delete a discount', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'id' => array(
                        'type'        => 'integer',
                        'description' => __( 'Discount ID to delete', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'id' ),
            ),
            array( $this, 'delete_discount' )
        );

        // Validate discount code tool.
        $this->server->register_tool(
            'validate_discount_code',
            __( 'Validate a discount code for a given cart total', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'code'           => array(
                        'type'        => 'string',
                        'description' => __( 'Discount code to validate', 'ggm-commerce' ),
                    ),
                    'cart_total'     => array(
                        'type'        => 'number',
                        'description' => __( 'Cart subtotal to validate against', 'ggm-commerce' ),
                    ),
                    'customer_email' => array(
                        'type'        => 'string',
                        'description' => __( 'Customer email for per-user limit checking', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'code', 'cart_total' ),
            ),
            array( $this, 'validate_discount_code' )
        );

        // Get voucher balance tool.
        $this->server->register_tool(
            'get_voucher_balance',
            __( 'Get the current balance of a voucher', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'code' => array(
                        'type'        => 'string',
                        'description' => __( 'Voucher code', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'code' ),
            ),
            array( $this, 'get_voucher_balance' )
        );

        // Bulk generate vouchers tool.
        $this->server->register_tool(
            'bulk_generate_vouchers',
            __( 'Generate multiple voucher codes with the same value', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'count'       => array(
                        'type'        => 'integer',
                        'description' => __( 'Number of vouchers to generate (max 1000)', 'ggm-commerce' ),
                    ),
                    'value'       => array(
                        'type'        => 'number',
                        'description' => __( 'Value of each voucher', 'ggm-commerce' ),
                    ),
                    'prefix'      => array(
                        'type'        => 'string',
                        'description' => __( 'Code prefix (default: GIFT)', 'ggm-commerce' ),
                        'default'     => 'GIFT',
                    ),
                    'single_use'  => array(
                        'type'        => 'boolean',
                        'description' => __( 'Single-use vouchers (entire balance at once)', 'ggm-commerce' ),
                        'default'     => false,
                    ),
                    'expiry_date' => array(
                        'type'        => 'string',
                        'description' => __( 'Expiry date in YYYY-MM-DD format', 'ggm-commerce' ),
                    ),
                ),
                'required'   => array( 'count', 'value' ),
            ),
            array( $this, 'bulk_generate_vouchers' )
        );

        // Generate voucher from gift card product tool.
        $this->server->register_tool(
            'generate_gift_card_voucher',
            __( 'Manually generate a voucher from a gift card product configuration', 'ggm-commerce' ),
            array(
                'type'       => 'object',
                'properties' => array(
                    'product_id'      => array(
                        'type'        => 'integer',
                        'description' => __( 'Gift card product ID', 'ggm-commerce' ),
                    ),
                    'recipient_email' => array(
                        'type'        => 'string',
                        'description' => __( 'Email address to send the voucher to', 'ggm-commerce' ),
                    ),
                    'send_email'      => array(
                        'type'        => 'boolean',
                        'description' => __( 'Whether to send the voucher email to the recipient', 'ggm-commerce' ),
                        'default'     => true,
                    ),
                ),
                'required'   => array( 'product_id', 'recipient_email' ),
            ),
            array( $this, 'generate_gift_card_voucher' )
        );
    }

    /**
     * Create discount tool handler
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function create_discount( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'success' => false,
                'error'   => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $discounts = GGM_Commerce_Discounts::get_instance();
        return $discounts->create_discount( $args );
    }

    /**
     * Update discount tool handler
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function update_discount( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'success' => false,
                'error'   => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $id = isset( $args['id'] ) ? absint( $args['id'] ) : 0;
        unset( $args['id'] );

        $discounts = GGM_Commerce_Discounts::get_instance();
        return $discounts->update_discount( $id, $args );
    }

    /**
     * Delete discount tool handler
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function delete_discount( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'success' => false,
                'error'   => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $id = isset( $args['id'] ) ? absint( $args['id'] ) : 0;

        $discounts = GGM_Commerce_Discounts::get_instance();
        return $discounts->delete_discount( $id );
    }

    /**
     * Validate discount code tool handler
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function validate_discount_code( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'success' => false,
                'error'   => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $code = isset( $args['code'] ) ? sanitize_text_field( $args['code'] ) : '';
        $cart_total = isset( $args['cart_total'] ) ? floatval( $args['cart_total'] ) : 0;
        $customer_email = isset( $args['customer_email'] ) ? sanitize_email( $args['customer_email'] ) : '';

        $discounts = GGM_Commerce_Discounts::get_instance();
        $result = $discounts->validate_discount_code( $code, $cart_total, $customer_email );

        if ( $result['valid'] ) {
            return array(
                'success'         => true,
                'valid'           => true,
                'discount_code'   => $result['discount']->code,
                'discount_type'   => $result['discount']->discount_type,
                'discount_amount' => $result['discount_amount'],
                'message'         => $result['message'],
            );
        }

        return array(
            'success' => true,
            'valid'   => false,
            'error'   => $result['error'],
        );
    }

    /**
     * Get voucher balance tool handler
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function get_voucher_balance( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'success' => false,
                'error'   => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $code = isset( $args['code'] ) ? sanitize_text_field( $args['code'] ) : '';

        $discounts = GGM_Commerce_Discounts::get_instance();
        return $discounts->get_voucher_balance( $code );
    }

    /**
     * Bulk generate vouchers tool handler
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function bulk_generate_vouchers( $args ) {
        if ( ! $this->is_activated() ) {
            return array(
                'success' => false,
                'error'   => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $count = isset( $args['count'] ) ? absint( $args['count'] ) : 0;
        $value = isset( $args['value'] ) ? floatval( $args['value'] ) : 0;
        $prefix = isset( $args['prefix'] ) ? sanitize_text_field( $args['prefix'] ) : 'GIFT';
        $options = array(
            'single_use'  => isset( $args['single_use'] ) ? (bool) $args['single_use'] : false,
            'expiry_date' => isset( $args['expiry_date'] ) ? sanitize_text_field( $args['expiry_date'] ) : null,
        );

        $discounts = GGM_Commerce_Discounts::get_instance();
        return $discounts->bulk_generate_vouchers( $count, $value, $prefix, $options );
    }

    /**
     * Generate gift card voucher tool handler
     *
     * @param array $args Tool arguments.
     * @return array Result.
     */
    public function generate_gift_card_voucher( $args ) {
        global $wpdb;

        if ( ! $this->is_activated() ) {
            return array(
                'success' => false,
                'error'   => __( 'Discounts & Vouchers feature is not activated.', 'ggm-commerce' ),
            );
        }

        $product_id = isset( $args['product_id'] ) ? absint( $args['product_id'] ) : 0;
        $recipient_email = isset( $args['recipient_email'] ) ? sanitize_email( $args['recipient_email'] ) : '';
        $send_email = isset( $args['send_email'] ) ? (bool) $args['send_email'] : true;

        if ( ! $product_id || ! is_email( $recipient_email ) ) {
            return array(
                'success' => false,
                'error'   => __( 'Valid product ID and recipient email are required.', 'ggm-commerce' ),
            );
        }

        // Get product with gift card settings.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $product = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ggmc_products WHERE id = %d AND product_type = 'gift_card'",
                $product_id
            )
        );

        if ( ! $product ) {
            return array(
                'success' => false,
                'error'   => __( 'Gift card product not found.', 'ggm-commerce' ),
            );
        }

        // Create a mock order item object for the voucher generation.
        $item = (object) array(
            'gift_card_value'       => $product->gift_card_value,
            'gift_card_type'        => $product->gift_card_type ?? 'fixed',
            'gift_card_single_use'  => $product->gift_card_single_use ?? 0,
            'gift_card_valid_days'  => $product->gift_card_valid_days,
            'gift_card_code_prefix' => $product->gift_card_code_prefix ?? 'GC',
            'product_name'          => $product->name,
            'product_price'         => $product->price,
        );

        // Create a mock order object.
        $order = (object) array(
            'id'             => 0,
            'order_number'   => 'MANUAL-' . time(),
            'customer_email' => $recipient_email,
            'created_at'     => current_time( 'mysql' ),
        );

        $discounts = GGM_Commerce_Discounts::get_instance();
        $result = $discounts->generate_gift_card_voucher( $item, $order );

        if ( $result['success'] && $send_email ) {
            $discounts->send_voucher_email( $result, $order, $item );
        }

        return $result;
    }
}
