<?php
/**
 * Widget injection functionality
 *
 * @package TrylyAI
 * @since   1.0.0
 */

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

/**
 * Widget class.
 *
 * @since 1.0.0
 */
class Tryly_Widget {

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 */
    public function __construct() {
        add_action( 'wp_enqueue_scripts', array( $this, 'inject_widget_script' ) );
    }

	/**
	 * Inject widget script in head.
	 *
	 * @since 1.0.0
	 */
    public function inject_widget_script() {
        // Only enqueue on product pages if WooCommerce is active.
        if ( ! $this->should_load_widget() ) {
            return;
        }

        $merchant_key = get_option( 'tryly_merchant_key' );

        // Only enqueue if connected.
        if ( empty( $merchant_key ) || ! get_option( 'tryly_connected', false ) ) {
            return;
        }

        // Get cached settings or fetch new ones.
        $settings = $this->get_widget_settings( $merchant_key );

        $handle = 'tryly-widget';
        $src    = trailingslashit( TRYLY_API_URL ) . 'widget-v3.min.js';

        // Register script with a stable version (cache-busting handled by WP).
        wp_register_script( $handle, $src, array(), TRYLY_VERSION, false );

        // Build attributes (including merchant key) and add via filter.
        $attributes_html = $this->build_data_attributes_html( $settings, $merchant_key );
        add_filter(
            'script_loader_tag',
            function ( $tag, $script_handle, $src_attr ) use ( $handle, $attributes_html ) {
                if ( $script_handle !== $handle ) {
                    return $tag;
                }
                $injection = 'async ' . trim( $attributes_html ) . ' ';
                return str_replace( '<script ', '<script ' . $injection, $tag );
            },
            10,
            3
        );

        // Inline product configuration BEFORE the external script runs.
        $inline_js = $this->get_inline_config_js();
        if ( $inline_js ) {
            wp_add_inline_script( $handle, $inline_js, 'before' );
        }

        wp_enqueue_script( $handle );
    }

	/**
	 * Check if widget should load on current page.
	 *
	 * @since 1.0.0
	 * @return bool
	 */
	private function should_load_widget() {
		// Check if WooCommerce is active.
		if ( ! function_exists( 'is_product' ) ) {
			return false;
		}

		// Load on product pages.
		if ( is_product() ) {
			return true;
		}

		// Allow filtering for custom pages.
		return apply_filters( 'tryly_load_widget', false );
	}

	/**
	 * Get widget settings from cache or API.
	 *
	 * @since 1.0.0
	 * @param string $merchant_key Merchant key.
	 * @return array Widget settings.
	 */
	private function get_widget_settings( $merchant_key ) {
		// NO CACHING - Always fetch fresh settings for immediate dashboard updates
		// This ensures changes in Tryly dashboard reflect instantly on WordPress sites

		// Fetch from API using safe URL building.
		$url = add_query_arg( 'key', $merchant_key, TRYLY_API_URL . '/api/widget/settings' );
		$response = wp_remote_get(
			$url,
			array(
				'timeout' => 5,
				'headers' => array(
					'Accept' => 'application/json',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			// Return empty settings on error.
			return array();
		}

		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		if ( ! empty( $data['settings'] ) ) {
			$settings = $data['settings'];
			// NO CACHING - Return fresh settings immediately
			return $settings;
		}

		return array();
	}

	/**
	 * Output data attributes for widget settings - ALWAYS fetches from API for real-time updates.
	 *
	 * @since 1.0.0
	 * @param array $settings Widget settings from API.
	 * @param string $merchant_key Merchant key.
	 */
    private function build_data_attributes_html( $settings, $merchant_key ) {
        $parts   = array();
        $parts[] = 'data-merchant-key="' . esc_attr( $merchant_key ) . '"';

        // Use settings from API (no caching for immediate updates)
        // This ensures dashboard changes are reflected instantly
        if ( ! empty( $settings ) ) {
            // Map API settings to data attributes
            $attribute_map = array(
                'buttonText' => 'button-text',
                'buttonColor' => 'button-color',
                'buttonStyle' => 'button-style',
                'gradientType' => 'gradient-type',
                'textAlign' => 'text-align',
                'buttonShape' => 'button-shape',
                'buttonSize' => 'button-size',
                'placement' => 'placement',
                'placementPosition' => 'placement-position',
                'hasIcon' => 'has-icon',
                'iconType' => 'icon-type',
                'showBadge' => 'show-badge',
                'badgeText' => 'badge-text',
                'badgeColor' => 'badge-color',
                'badgeType' => 'badge-type',
            );

            foreach ( $attribute_map as $api_key => $data_key ) {
                if ( isset( $settings[ $api_key ] ) ) {
                    $value = $settings[ $api_key ];
                    // Convert boolean values to string
                    if ( is_bool( $value ) ) {
                        $value = $value ? 'true' : 'false';
                    }
                    $parts[] = 'data-' . esc_attr( $data_key ) . '="' . esc_attr( $value ) . '"';
                }
            }
        } else {
            // Fallback to saved settings if API fails
            $fallback_settings = array(
                'button_text' => get_option( 'tryly_button_text', 'Try it on' ),
                'button_color' => get_option( 'tryly_button_color', '#8b5cf6' ),
                'button_style' => get_option( 'tryly_button_style', 'minimal' ),
                'gradient_type' => get_option( 'tryly_gradient_type', 'purple-pink' ),
                'text_align' => get_option( 'tryly_text_align', 'center' ),
                'button_shape' => get_option( 'tryly_button_shape', 'rounded' ),
                'button_size' => get_option( 'tryly_button_size', 'medium' ),
                'placement' => get_option( 'tryly_placement', 'smart' ),
                'placement_position' => get_option( 'tryly_placement_position', 'after-add-to-cart' ),
                'has_icon' => get_option( 'tryly_has_icon', 'true' ),
                'icon_type' => get_option( 'tryly_icon_type', 'sparkles' ),
                'show_badge' => get_option( 'tryly_show_badge', 'false' ),
                'badge_text' => get_option( 'tryly_badge_text', 'NEW' ),
                'badge_color' => get_option( 'tryly_badge_color', '#ef4444' ),
                'badge_type' => get_option( 'tryly_badge_type', 'preset' ),
            );

            foreach ( $fallback_settings as $key => $value ) {
                if ( ! empty( $value ) ) {
                    $data_key = str_replace( '_', '-', $key );
                    $parts[] = 'data-' . esc_attr( $data_key ) . '="' . esc_attr( $value ) . '"';
                }
            }
        }

        return implode( ' ', $parts );
    }


	/**
	 * Add inline configuration script.
	 *
	 * @since 1.0.0
	 */
    private function get_inline_config_js() {
        // Determine current product reliably.
        $product_id = function_exists( 'get_queried_object_id' ) ? get_queried_object_id() : 0;
        if ( ! $product_id && function_exists( 'get_the_ID' ) ) {
            $product_id = get_the_ID();
        }

        if ( ! $product_id || ! function_exists( 'wc_get_product' ) ) {
            return '';
        }

        $product = wc_get_product( $product_id );
        if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
            return '';
        }

        $config = array(
            'productId'    => $product->get_id(),
            'productName'  => $product->get_name(),
            'productPrice' => $product->get_price(),
            'currency'     => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : '',
            'productImage' => wp_get_attachment_url( $product->get_image_id() ),
        );

        // Allow filtering of product data.
        $config = apply_filters( 'tryly_product_data', $config, $product );

        return 'window.trylyProductData = ' . wp_json_encode( $config ) . ';';
    }
}
