<?php
namespace AI_BotKit\Public;

use AI_BotKit\Integration\PEP_Detector;

/**
 * Render "Ask AI" button on WooCommerce product pages.
 *
 * @package AI_BotKit\Public
 */
class Product_Button {

    /**
     * Initialize hooks.
     */
    public function __construct() {
        $this->register_hooks();
    }

    /**
     * Register WooCommerce hooks for button rendering.
     */
    private function register_hooks(): void {
        $settings = get_option( 'ai_botkit_pep_settings', [] );
        if ( empty( $settings['enabled'] ) || ! PEP_Detector::is_woocommerce_active() ) {
            return;
        }

        if ( $this->is_mpe_enabled() && PEP_Detector::is_pep_active()) {
            // MPE mode: button on enquiry cart page only
            add_action( 'quoteup_after_enquiry_cart_table', [ $this, 'render_enquiry_cart_button' ], 10 );
            add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_assets' ] );
            return;
        }
        // Non-MPE mode: product page buttons
        $button_mode = $settings['button_mode'] ?? 'new';
        $position    = $settings['button_position'] ?? 'after_add_to_cart';

        if ( 'new' === $button_mode ) {
            // Single product page
            if ( 'after_add_to_cart' === $position ) {
                add_action( 'woocommerce_after_add_to_cart_button', [ $this, 'render_button' ], 99 );
            } else {
                add_action( 'woocommerce_single_product_summary', [ $this, 'render_button' ], 99 );
            }
            // Archive pages - visible button
            add_action( 'woocommerce_after_shop_loop_item', [ $this, 'render_loop_button' ], 99 );
        } else {
            // Override mode - archive pages need hidden data for JS reference
            add_action( 'woocommerce_after_shop_loop_item', [ $this, 'render_loop_hidden_data' ], 99 );
        }

        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_assets' ] );
    }

    /**
     * Check if Multi Product Enquiry (MPE) is enabled in PEP settings.
     */
    private function is_mpe_enabled(): bool {
        $form_data = get_option( 'wdm_form_data', [] );
        return ! empty( $form_data['enable_disable_mpe'] );
    }

    /**
     * Get the Enquiry Cart page ID from PEP settings.
     */
    private function get_enquiry_cart_page_id(): int {
        $form_data = get_option( 'wdm_form_data', [] );
        return isset( $form_data['mpe_cart_page'] ) ? intval( $form_data['mpe_cart_page'] ) : 0;
    }

    /**
     * Check if current page is the Enquiry Cart page.
     */
    private function is_enquiry_cart_page(): bool {
        $cart_page_id = $this->get_enquiry_cart_page_id();
        return $cart_page_id > 0 && is_page( $cart_page_id );
    }

    /**
     * Check if the selected PEP chatbot is active on the current page/post.
     */
    private function is_selected_bot_active(): bool {
        $settings   = get_option( 'ai_botkit_pep_settings', [] );
        $chatbot_id = $settings['chatbot_id'] ?? '';

        if ( empty( $chatbot_id ) ) {
            return false;
        }

        $site_wide_chatbot_id = get_option( 'ai_botkit_chatbot_sitewide_enabled', 0 );
        if ( $site_wide_chatbot_id === $chatbot_id ) {
            return true;
        }

        $enabled_pages = get_option( 'ai_botkit_chatbot_enabled_pages', [] );
        $current_id    = get_the_ID();

        if ( is_array( $enabled_pages ) && isset( $enabled_pages[ $current_id ] ) ) {
            return in_array( $chatbot_id, $enabled_pages[ $current_id ], true );
        }

        $enabled_post_types = get_option( 'ai_botkit_chatbot_enabled_post_types', [] );
        $current_post_type  = get_post_type();

        if ( is_array( $enabled_post_types ) && isset( $enabled_post_types[ $current_post_type ] ) ) {
            return in_array( $chatbot_id, $enabled_post_types[ $current_post_type ], true );
        }

        return false;
    }

    /**
     * Check if the selected bot is active for the current page context.
     * Used for enqueue_assets which runs outside the loop.
     */
    private function is_bot_active_for_page(): bool {
        $settings   = get_option( 'ai_botkit_pep_settings', [] );
        $chatbot_id = $settings['chatbot_id'] ?? '';

        if ( empty( $chatbot_id ) ) {
            return false;
        }

        // Sitewide
        $site_wide_chatbot_id = get_option( 'ai_botkit_chatbot_sitewide_enabled', 0 );
        if ( $site_wide_chatbot_id === $chatbot_id ) {
            return true;
        }

        // Post type check
        $enabled_post_types = get_option( 'ai_botkit_chatbot_enabled_post_types', [] );
        $current_post_type  = get_post_type();
        if ( is_array( $enabled_post_types ) && isset( $enabled_post_types[ $current_post_type ] ) ) {
            if ( in_array( $chatbot_id, $enabled_post_types[ $current_post_type ], true ) ) {
                return true;
            }
        }

        // Specific page check
        $page_id = null;
        if ( is_product() ) {
            $page_id = get_the_ID();
        } elseif ( is_shop() ) {
            $page_id = wc_get_page_id( 'shop' );
        } elseif ( $this->is_enquiry_cart_page() ) {
            $page_id = $this->get_enquiry_cart_page_id();
        }

        if ( $page_id ) {
            $enabled_pages = get_option( 'ai_botkit_chatbot_enabled_pages', [] );
            if ( is_array( $enabled_pages ) && isset( $enabled_pages[ $page_id ] ) ) {
                if ( in_array( $chatbot_id, $enabled_pages[ $page_id ], true ) ) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Get product data and settings for the button.
     *
     * @param \WC_Product|null $product Optional product object.
     * @return array|null Button data or null if not applicable.
     */
    private function get_button_data( ?\WC_Product $product = null ): ?array {
        if ( ! $this->is_selected_bot_active() ) {
            return null;
        }

        if ( ! $product ) {
            $product = wc_get_product( get_the_ID() );
        }

        if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
            return null;
        }

        $settings    = get_option( 'ai_botkit_pep_settings', [] );
        $label       = ! empty( $settings['button_label'] ) ? $settings['button_label'] : __( 'Get Quote', 'ai-botkit-for-lead-generation' );
        $chatbot_id  = $settings['chatbot_id'] ?? '';
        $button_mode = $settings['button_mode'] ?? 'new';

        return [
            'productId'    => $product->get_id(),
            'productName'  => $product->get_name(),
            'productPrice' => html_entity_decode( wp_strip_all_tags( wc_price( $product->get_price() ) ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
            'chatbotId'    => $chatbot_id,
            'buttonLabel'  => $label,
            'buttonMode'   => $button_mode,
        ];
    }

    /**
     * Render the Ask AI button on single product pages.
     */
    public function render_button(): void {
        if ( ! is_product() ) {
            return;
        }

        $data = $this->get_button_data();
        if ( ! $data ) {
            return;
        }

        $this->output_button( $data );
    }

    /**
     * Render the Ask AI button on archive/shop pages.
     */
    public function render_loop_button(): void {
        $data = $this->get_button_data();
        if ( ! $data ) {
            return;
        }

        $this->output_button( $data );
    }

    /**
     * Render hidden product data for override mode on archive pages.
     */
    public function render_loop_hidden_data(): void {
        $data = $this->get_button_data();
        if ( ! $data ) {
            return;
        }

        ?>
        <span class="ai-botkit-product-data" style="display:none;"
            data-product-id="<?php echo esc_attr( $data['productId'] ); ?>"
            data-product-name="<?php echo esc_attr( $data['productName'] ); ?>"
            data-product-price="<?php echo esc_attr( $data['productPrice'] ); ?>"
            data-chatbot-id="<?php echo esc_attr( $data['chatbotId'] ); ?>"
            data-button-label="<?php echo esc_attr( $data['buttonLabel'] ); ?>">
        </span>
        <?php
    }

    /**
     * Build the message from PEP enquiry cart products.
     *
     * @return string Message listing cart products.
     */
    private function build_enquiry_cart_message(): string {
        global $quoteup;

        if ( ! $quoteup || ! isset( $quoteup->wcCartSession ) ) {
            return __( 'I have products in my enquiry cart and would like a quotation.', 'ai-botkit-for-lead-generation' );
        }

        $products = $quoteup->wcCartSession->get( 'wdm_product_info' );
        if ( empty( $products ) || ! is_array( $products ) ) {
            return __( 'I have products in my enquiry cart and would like a quotation.', 'ai-botkit-for-lead-generation' );
        }

        $lines = [];
        foreach ( $products as $product ) {
            $title = $product['title'] ?? '';
            $qty   = $product['quantity'] ?? 1;

            if ( empty( $title ) ) {
                continue;
            }

            $line = $title;
            if ( $qty > 1 ) {
                $line .= ' (Qty: ' . $qty . ')';
            }
            $lines[] = $line;
        }

        if ( empty( $lines ) ) {
            return __( 'I have products in my enquiry cart and would like a quotation.', 'ai-botkit-for-lead-generation' );
        }

        $product_list = implode( ', ', $lines );
        return sprintf(
            __( 'I want a quotation for the following products in my enquiry cart: %s', 'ai-botkit-for-lead-generation' ),
            $product_list
        );
    }

    /**
     * Render the Ask AI button on the Enquiry Cart page (MPE mode).
     */
    public function render_enquiry_cart_button(): void {
        if ( ! $this->is_bot_active_for_page() ) {
            return;
        }

        $settings   = get_option( 'ai_botkit_pep_settings', [] );
        $label      = ! empty( $settings['button_label'] ) ? $settings['button_label'] : __( 'Get Quote', 'ai-botkit-for-lead-generation' );
        $chatbot_id = $settings['chatbot_id'] ?? '';
        $message    = $this->build_enquiry_cart_message();

        ?>
        <button
            type="button"
            class="button ai-botkit-enquiry-cart-btn"
            data-chatbot-id="<?php echo esc_attr( $chatbot_id ); ?>"
            data-message="<?php echo esc_attr( $message ); ?>"
        >
            <?php echo esc_html( $label ); ?>
        </button>
        <?php
    }

    /**
     * Output the button HTML.
     *
     * @param array $data Button data.
     */
    private function output_button( array $data ): void {
        ?>
        <button
            type="button"
            class="ai-botkit-ask-ai-btn"
            data-product-id="<?php echo esc_attr( $data['productId'] ); ?>"
            data-product-name="<?php echo esc_attr( $data['productName'] ); ?>"
            data-product-price="<?php echo esc_attr( $data['productPrice'] ); ?>"
            data-chatbot-id="<?php echo esc_attr( $data['chatbotId'] ); ?>"
        >
            <?php echo esc_html( $data['buttonLabel'] ); ?>
        </button>
        <?php
    }

    /**
     * Get the cached chatbot primary color for PEP button theming.
     *
     * @return string|null Hex color or null if not set.
     */
    private function get_chatbot_primary_color(): ?string {
        $style = get_option( 'ai_botkit_pep_chatbot_style', [] );
        if ( ! empty( $style['primaryColor'] ) ) {
            return sanitize_hex_color( $style['primaryColor'] ) ?: null;
        }
        return null;
    }

    /**
     * Darken a hex color by a given percentage.
     *
     * @param string $hex Hex color.
     * @param int    $percent Percentage to darken (0-100).
     * @return string Darkened hex color.
     */
    private function darken_color( string $hex, int $percent = 25 ): string {
        $hex = ltrim( $hex, '#' );
        if ( strlen( $hex ) === 3 ) {
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
        }
        $r = max( 0, min( 255, hexdec( substr( $hex, 0, 2 ) ) - round( 255 * $percent / 100 ) ) );
        $g = max( 0, min( 255, hexdec( substr( $hex, 2, 2 ) ) - round( 255 * $percent / 100 ) ) );
        $b = max( 0, min( 255, hexdec( substr( $hex, 4, 2 ) ) - round( 255 * $percent / 100 ) ) );
        return sprintf( '#%02x%02x%02x', $r, $g, $b );
    }

    /**
     * Build inline CSS for dynamic button theming based on chatbot primary color.
     *
     * @return string CSS rules.
     */
    private function get_button_inline_css(): string {
        $primary = $this->get_chatbot_primary_color();
        if ( ! $primary ) {
            return '';
        }

        $dark = $this->darken_color( $primary, 20 );

        return '
            .ai-botkit-ask-ai-btn,
            .ai-botkit-enquiry-cart-btn {
                background: linear-gradient(135deg, ' . esc_attr( $primary ) . ' 0%, ' . esc_attr( $dark ) . ' 100%) !important;
                box-shadow: 0 2px 8px ' . esc_attr( $this->hex_to_rgba( $primary, 0.25 ) ) . ' !important;
            }
            .ai-botkit-ask-ai-btn:hover,
            .ai-botkit-enquiry-cart-btn:hover {
                background: linear-gradient(135deg, ' . esc_attr( $dark ) . ' 0%, ' . esc_attr( $primary ) . ' 100%) !important;
                box-shadow: 0 4px 12px ' . esc_attr( $this->hex_to_rgba( $primary, 0.35 ) ) . ' !important;
            }
            .ai-botkit-ask-ai-btn:active,
            .ai-botkit-enquiry-cart-btn:active {
                box-shadow: 0 1px 4px ' . esc_attr( $this->hex_to_rgba( $primary, 0.25 ) ) . ' !important;
            }
        ';
    }

    /**
     * Convert hex color to rgba string.
     *
     * @param string $hex Hex color.
     * @param float  $alpha Alpha value (0-1).
     * @return string rgba() string.
     */
    private function hex_to_rgba( string $hex, float $alpha ): string {
        $hex = ltrim( $hex, '#' );
        if ( strlen( $hex ) === 3 ) {
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
        }
        $r = hexdec( substr( $hex, 0, 2 ) );
        $g = hexdec( substr( $hex, 2, 2 ) );
        $b = hexdec( substr( $hex, 4, 2 ) );
        return 'rgba(' . $r . ', ' . $g . ', ' . $b . ', ' . $alpha . ')';
    }

    /**
     * Enqueue frontend assets.
     */
    public function enqueue_assets(): void {
        $is_product_page   = is_product() || is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy();
        $is_enquiry_cart   = $this->is_enquiry_cart_page();

        if ( ! $is_product_page && ! $is_enquiry_cart ) {
            return;
        }

        if ( ! $this->is_bot_active_for_page() ) {
            return;
        }

        wp_enqueue_style(
            'ai-botkit-product-button',
            AI_BOTKIT_PLUGIN_URL . 'public/css/product-button.css',
            [],
            AI_BOTKIT_VERSION
        );

        $inline_css = $this->get_button_inline_css();
        if ( $inline_css ) {
            wp_add_inline_style( 'ai-botkit-product-button', $inline_css );
        }

        wp_enqueue_script(
            'ai-botkit-product-button',
            AI_BOTKIT_PLUGIN_URL . 'public/js/product-button.js',
            [],
            AI_BOTKIT_VERSION,
            true
        );

        // Localize with single product data only on single product pages
        if ( is_product() ) {
            $data = $this->get_button_data();
            if ( $data ) {
                wp_localize_script(
                    'ai-botkit-product-button',
                    'aiBotKitPep',
                    $data
                );
            }
        }
    }
}
