<?php

class polylai_ACF
{
	const META_KEY = '_polylai_acf_fields';

	public static function translate_meta($id, $current_locale_name, $locale_name, $translator)
	{
		$meta = [];
		
		// Check if ACF is active
		if (!function_exists('get_field_objects') && !function_exists('get_fields')) {
			return $meta;
		}
		
		// Get all ACF fields for the post
		$acf_fields = function_exists('get_field_objects') ? get_field_objects($id, false, true) : get_fields($id);
		
		if (!$acf_fields || !is_array($acf_fields)) {
			return $meta;
		}

		$translated_fields = [];
		
		foreach ($acf_fields as $field_name => $field_data) {
			try {
				// Get the field value - handle both get_field_objects() and get_fields() return formats
				$field_value = is_array($field_data) && isset($field_data['value']) ? $field_data['value'] : $field_data;
				$field_type = is_array($field_data) && isset($field_data['type']) ? $field_data['type'] : null;
				$field_key = is_array($field_data) && isset($field_data['key']) ? $field_data['key'] : null;
				$field_name = is_array($field_data) && isset($field_data['name']) ? $field_data['name'] : $field_name;
				
				// Skip empty values
				if (self::is_empty_value($field_value)) {
					continue;
				}
				
				// Handle different ACF field types
				$translated_value = self::translate_field_value($field_value, $field_type, $current_locale_name, $locale_name, $translator, $id, $field_data, true);
				
				if ($translated_value !== null) {
					$translated_fields[] = [
						'selector' => $field_key ? $field_key : $field_name,
						'name' => $field_name,
						'value' => $translated_value,
					];
				}
				
			} catch (Exception $e) {
				polylai_Utils::db_log('error', 'ACF translate', 'Error translating ACF field ' . $field_name . ': ' . $e->getMessage());
			}
		}

		if (count($translated_fields) > 0) {
			$meta[self::META_KEY] = $translated_fields;
		}
		
		return $meta;
	}

	public static function copy_meta($id)
	{
		$meta = [];

		if (!function_exists('get_field_objects') && !function_exists('get_fields')) {
			return $meta;
		}

		$acf_fields = function_exists('get_field_objects') ? get_field_objects($id, false, true) : get_fields($id);

		if (!$acf_fields || !is_array($acf_fields)) {
			return $meta;
		}

		$copied_fields = [];
		foreach ($acf_fields as $field_name => $field_data) {
			$field_value = is_array($field_data) && isset($field_data['value']) ? $field_data['value'] : $field_data;

			if (self::is_empty_value($field_value)) {
				continue;
			}

			$field_key = is_array($field_data) && isset($field_data['key']) ? $field_data['key'] : null;
			$field_name = is_array($field_data) && isset($field_data['name']) ? $field_data['name'] : $field_name;

			$copied_fields[] = [
				'selector' => $field_key ? $field_key : $field_name,
				'name' => $field_name,
				'value' => $field_value,
			];
		}

		if (count($copied_fields) > 0) {
			$meta[self::META_KEY] = $copied_fields;
		}

		return $meta;
	}
	
	/**
	 * Translate ACF field value based on field type
	 */
	private static function translate_field_value($value, $field_type, $current_locale_name, $locale_name, $translator, $post_id, $field = null, $translate_unknown_strings = false)
	{
		// Handle different field types
		switch ($field_type) {
			case 'text':
			case 'textarea':
				return self::translate_text_field($value, $current_locale_name, $locale_name, $translator, $post_id);

			case 'email':
			case 'url':
				return $value;
				
			case 'wysiwyg':
				return self::translate_wysiwyg_field($value, $current_locale_name, $locale_name, $translator, $post_id);
				
			//case 'select':
			//case 'checkbox':
			//case 'radio':
			//	return self::translate_choice_field($value, $current_locale_name, $locale_name, $translator, $post_id);
				
			case 'repeater':
				return self::translate_repeater_field($value, $current_locale_name, $locale_name, $translator, $post_id, $field);
				
			case 'flexible_content':
				return self::translate_flexible_content_field($value, $current_locale_name, $locale_name, $translator, $post_id, $field);
				
			case 'group':
				return self::translate_group_field($value, $current_locale_name, $locale_name, $translator, $post_id, $field);
				
			case 'number':
			case 'range':
			case 'date_picker':
			case 'date_time_picker':
			case 'time_picker':
			case 'color_picker':
			case 'image':
			case 'file':
			case 'gallery':
			case 'true_false':
			case 'select':
			case 'checkbox':
			case 'radio':
				// These field types don't need translation
				return $value;
				
			default:
				// For unknown field types, try to translate if it's a string
				if ($translate_unknown_strings && is_string($value) && !empty(trim($value))) {
					return self::translate_text_field($value, $current_locale_name, $locale_name, $translator, $post_id);
				}
				return $value;
		}
	}
	
	/**
	 * Translate simple text fields
	 */
	private static function translate_text_field($value, $current_locale_name, $locale_name, $translator, $post_id)
	{
		if (!is_string($value) || empty(trim($value))) {
			return $value;
		}
		
		$response = $translator->translate($value, $current_locale_name, $locale_name, $post_id, true);
		return $response['content'];
	}
	
	/**
	 * Translate WYSIWYG fields (rich text)
	 */
	private static function translate_wysiwyg_field($value, $current_locale_name, $locale_name, $translator, $post_id)
	{
		if (!is_string($value) || empty(trim($value))) {
			return $value;
		}
		
		$request = new polylai_TranslationRequest();
		$request->text = $value;
		$request->locale_from = $current_locale_name;
		$request->locale_to = $locale_name;
		$request->post_id = $post_id;
		$request->custom_prompt = "You are a professional translator. Translate the following HTML content from $current_locale_name to $locale_name. " .
			"Preserve all HTML tags, attributes, and structure. Only translate the text content within the tags. " .
			"Do not add any comments or explanations. Here is the content:\n\n$value";
		
		$response = $translator->translateRequest($request);
		return $response['content'];
	}

	private static function is_empty_value($value)
	{
		return $value === null || $value === false || $value === '' || $value === [];
	}

	private static function find_sub_field($field, $name)
	{
		if (!is_array($field) || !isset($field['sub_fields']) || !is_array($field['sub_fields'])) {
			return null;
		}

		foreach ($field['sub_fields'] as $sub_field) {
			if (!is_array($sub_field)) {
				continue;
			}
			if ((isset($sub_field['name']) && $sub_field['name'] === $name) || (isset($sub_field['key']) && $sub_field['key'] === $name)) {
				return $sub_field;
			}
		}

		return null;
	}

	private static function find_layout($field, $layout_name)
	{
		if (!is_array($field) || !isset($field['layouts']) || !is_array($field['layouts'])) {
			return null;
		}

		foreach ($field['layouts'] as $layout) {
			if (!is_array($layout)) {
				continue;
			}
			if ((isset($layout['name']) && $layout['name'] === $layout_name) || (isset($layout['key']) && $layout['key'] === $layout_name)) {
				return $layout;
			}
		}

		return null;
	}
	
	/**
	 * Translate choice fields (select, checkbox, radio)
	 */
	/*private static function translate_choice_field($value, $current_locale_name, $locale_name, $translator, $post_id)
	{
		if (is_array($value)) {
			$translated_array = [];
			foreach ($value as $item) {
				if (is_string($item) && !empty(trim($item))) {
					$response = $translator->translate($item, $current_locale_name, $locale_name, $post_id, true);
					$translated_array[] = $response['content'];
				} else {
					$translated_array[] = $item;
				}
			}
			return $translated_array;
		} elseif (is_string($value) && !empty(trim($value))) {
			$response = $translator->translate($value, $current_locale_name, $locale_name, $post_id, true);
			return $response['content'];
		}
		
		return $value;
	}*/
	
	/**
	 * Translate repeater fields
	 */
	private static function translate_repeater_field($value, $current_locale_name, $locale_name, $translator, $post_id, $field = null)
	{
		if (!is_array($value)) {
			return $value;
		}
		
		$translated_repeater = [];
		foreach ($value as $row) {
			if (is_array($row)) {
				$translated_row = [];
				foreach ($row as $sub_field_name => $sub_field_value) {
					$sub_field = self::find_sub_field($field, $sub_field_name);
					$sub_field_type = is_array($sub_field) && isset($sub_field['type']) ? $sub_field['type'] : null;

					// Recursively translate sub-fields
					$translated_row[$sub_field_name] = self::translate_field_value(
						$sub_field_value, 
						$sub_field_type,
						$current_locale_name, 
						$locale_name, 
						$translator, 
						$post_id,
						$sub_field,
						false
					);
				}
				$translated_repeater[] = $translated_row;
			} else {
				$translated_repeater[] = $row;
			}
		}
		
		return $translated_repeater;
	}
	
	/**
	 * Translate flexible content fields
	 */
	private static function translate_flexible_content_field($value, $current_locale_name, $locale_name, $translator, $post_id, $field = null)
	{
		if (!is_array($value)) {
			return $value;
		}
		
		$translated_flexible = [];
		foreach ($value as $layout) {
			if (is_array($layout)) {
				$translated_layout = [];
				$layout_name = isset($layout['acf_fc_layout']) ? $layout['acf_fc_layout'] : null;
				$layout_definition = $layout_name ? self::find_layout($field, $layout_name) : null;

				foreach ($layout as $field_name => $field_value) {
					if ($field_name === 'acf_fc_layout') {
						$translated_layout[$field_name] = $field_value;
						continue;
					}

					$sub_field = self::find_sub_field($layout_definition, $field_name);
					$sub_field_type = is_array($sub_field) && isset($sub_field['type']) ? $sub_field['type'] : null;

					// Recursively translate layout fields
					$translated_layout[$field_name] = self::translate_field_value(
						$field_value, 
						$sub_field_type,
						$current_locale_name, 
						$locale_name, 
						$translator, 
						$post_id,
						$sub_field,
						false
					);
				}
				$translated_flexible[] = $translated_layout;
			} else {
				$translated_flexible[] = $layout;
			}
		}
		
		return $translated_flexible;
	}
	
	/**
	 * Translate group fields
	 */
	private static function translate_group_field($value, $current_locale_name, $locale_name, $translator, $post_id, $field = null)
	{
		if (!is_array($value)) {
			return $value;
		}
		
		$translated_group = [];
		foreach ($value as $sub_field_name => $sub_field_value) {
			$sub_field = self::find_sub_field($field, $sub_field_name);
			$sub_field_type = is_array($sub_field) && isset($sub_field['type']) ? $sub_field['type'] : null;

			// Recursively translate sub-fields
			$translated_group[$sub_field_name] = self::translate_field_value(
				$sub_field_value, 
				$sub_field_type,
				$current_locale_name, 
				$locale_name, 
				$translator, 
				$post_id,
				$sub_field,
				false
			);
		}
		
		return $translated_group;
	}
}
