<?php
namespace TeknoTok\AiTranslator\Integrations;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use TeknoTok\AiTranslator\Database\MemoryRepository;

/**
 * WooCommerce translation integration logic.
 */
class WooCommerceIntegration {
	/**
	 * Constructor. Registers hooks if WooCommerce is active.
	 */
	public function __construct() {
		if ( is_admin() ) {
			return;
		}

		add_action( 'woocommerce_init', array( $this, 'register_frontend_hooks' ) );
	}

	/**
	 * Register WooCommerce frontend hooks once WC is loaded.
	 *
	 * @return void
	 */
	public function register_frontend_hooks() {
		if ( ! \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active() ) {
			return;
		}

		$active_lang = \TeknoTok\AiTranslator\Plugin::get_active_language();
		$settings = get_option( 'teknotok_ait_settings', array() );
		$source_lang = $settings['source_language'] ?? 'en';

		if ( $active_lang === $source_lang ) {
			return;
		}

		add_filter( 'woocommerce_attribute_label', array( $this, 'translate_attribute_label' ), 10, 3 );
		add_filter( 'woocommerce_cart_item_name', array( $this, 'translate_cart_item_name' ), 10, 3 );
		add_filter( 'load_script_translations', array( $this, 'merge_woocommerce_block_translations' ), 10, 4 );
	}

	/**
	 * Translate custom product attribute labels.
	 *
	 * @param string $label        Attribute label.
	 * @param string $name         Attribute name.
	 * @param object $product      WC Product object.
	 * @return string Translated label.
	 */
	public function translate_attribute_label( $label, $name, $product ) {
		$active_lang = \TeknoTok\AiTranslator\Plugin::get_active_language();
		$cached = MemoryRepository::get_translation( $label, $active_lang );
		return ( false !== $cached ) ? $cached : $label;
	}

	/**
	 * Translate product names in cart layouts.
	 *
	 * @param string $name          Item name wrapper.
	 * @param array  $cart_item     Cart item details.
	 * @param string $cart_item_key Cart item unique key.
	 * @return string Translated link HTML.
	 */
	public function translate_cart_item_name( $name, $cart_item, $cart_item_key ) {
		$active_lang = \TeknoTok\AiTranslator\Plugin::get_active_language();
		
		$product = $cart_item['data'];
		$title = $product->get_name();
		
		$cached = MemoryRepository::get_translation( $title, $active_lang );
		if ( false !== $cached ) {
			$permalink = $product->get_permalink( $cart_item );
			if ( $permalink ) {
				return sprintf( '<a href="%s">%s</a>', esc_url( $permalink ), esc_html( $cached ) );
			}
			return esc_html( $cached );
		}

		// Queue product for translation on cache miss
		$product_id = $product->get_id();
		if ( $product_id && \TeknoTok\AiTranslator\Plugin::is_ready_for_translations() ) {
			\TeknoTok\AiTranslator\Database\JobRepository::add_job( 'post', $product_id, $active_lang );
		}
		
		return $name;
	}

	/**
	 * Dynamically merge WooCommerce block script translation JSON files for Gutenberg interactivity.
	 *
	 * @param string|false $translations JSON string of translations.
	 * @param string       $file         Path to the translation file.
	 * @param string       $handle       Script handle.
	 * @param string       $domain       Textdomain.
	 * @return string JSON translation data.
	 */
	public function merge_woocommerce_block_translations( $translations, $file, $handle, $domain ) {
		if ( 'woocommerce' !== $domain ) {
			return $translations;
		}

		// Only target WooCommerce block-related scripts
		if ( 0 !== strpos( $handle, 'wc-cart-checkout' ) && 0 !== strpos( $handle, 'wc-block' ) ) {
			return $translations;
		}

		$locale = determine_locale();
		$transient_key = 'teknotok_ait_wc_js_' . $locale;
		$cached_json = get_transient( $transient_key );

		if ( false !== $cached_json ) {
			return $cached_json;
		}

		$languages_dir = defined( 'WP_LANG_DIR' ) ? WP_LANG_DIR . '/plugins/' : WP_CONTENT_DIR . '/languages/plugins/';
		$pattern = $languages_dir . 'woocommerce-' . $locale . '-*.json';
		$files = glob( $pattern );

		if ( empty( $files ) ) {
			return $translations;
		}

		$merged_data = array();
		if ( ! empty( $translations ) ) {
			$decoded = json_decode( $translations, true );
			if ( is_array( $decoded ) ) {
				$merged_data = $decoded;
			}
		}

		if ( empty( $merged_data ) ) {
			$merged_data = array(
				'domain'      => 'messages',
				'locale_data' => array(
					'messages' => array(
						'' => array(
							'domain'       => 'messages',
							'plural-forms' => 'nplurals=2; plural=n > 1;',
							'lang'         => substr( $locale, 0, 2 ),
						),
					),
				),
			);
		}

		if ( ! isset( $merged_data['locale_data']['messages'] ) ) {
			$merged_data['locale_data']['messages'] = array();
		}

		foreach ( $files as $json_file ) {
			if ( ! is_file( $json_file ) || ! is_readable( $json_file ) ) {
				continue;
			}
			$content = file_get_contents( $json_file );
			if ( ! $content ) {
				continue;
			}
			$decoded = json_decode( $content, true );
			if ( ! is_array( $decoded ) || ! isset( $decoded['locale_data'] ) ) {
				continue;
			}

			foreach ( $decoded['locale_data'] as $sub_domain => $data ) {
				if ( ! is_array( $data ) ) {
					continue;
				}
				foreach ( $data as $key => $val ) {
					if ( '' === $key ) {
						continue;
					}
					$merged_data['locale_data']['messages'][ $key ] = $val;
				}
			}
		}

		$output_json = json_encode( $merged_data );
		// Cache the merged translation payload for 1 day
		set_transient( $transient_key, $output_json, DAY_IN_SECONDS );

		return $output_json;
	}
}
