<?php

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

class CMBIRD_ZCRM_Product {

	protected $zcrm_modules;
	protected $zoho_crm_url;
	protected $zcrm_custom_fields;

	public function __construct() {
		$this->zcrm_modules = new CMBIRD_ZCRM_Modules();
		$this->zoho_crm_url = rtrim( get_option( 'cmbird_zoho_crm_url' ), '/' ) . '/';
		// get the option for custom fields.
		$this->zcrm_custom_fields = get_option( 'zcrm_products_fields', array() );
	}

	/**
	 * Log messages using WooCommerce logger if available
	 *
	 * @param string $message The message to log
	 * @param string $level Log level: debug, info, notice, warning, error, critical, alert, emergency
	 */
	private function log( $message, $level = 'info' ) {
		if ( function_exists( 'wc_get_logger' ) ) {
			$logger = wc_get_logger();
			$logger->log( $level, $message, array( 'source' => 'commercebird' ) );
		}
	}

	/**
	 * Main product sync function - handles create/update to avoid duplication
	 * Supports variable products and their variations
	 *
	 * @param WC_Product $product WooCommerce product object
	 * @return string|array|null Zoho product ID(s) on success, null on failure
	 */
	public function cmbird_sync_product_to_zoho( $product ) {
		if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
			return null;
		}

		// Handle variable products differently.
		if ( $product->is_type( 'variable' ) ) {
			return $this->sync_variable_product_to_zoho( $product );
		}

		// Handle simple products and variations.
		return $this->sync_single_product_to_zoho( $product );
	}

	/**
	 * Sync a single product (simple product or variation) to Zoho
	 *
	 * @param WC_Product $product WooCommerce product object
	 * @return string|null Zoho product ID on success, null on failure
	 */
	protected function sync_single_product_to_zoho( $product ) {
		// First, try to get existing Zoho product ID.
		$zoho_product_id = $this->cmbird_get_zoho_product_id( $product );

		if ( $zoho_product_id ) {
			// Update existing product.
			$result = $this->update_zoho_product( $product, $zoho_product_id );
			return $result ? $zoho_product_id : null;
		} else {
			// Create new product.
			return $this->create_zoho_product( $product );
		}
	}

	/**
	 * Sync a variable product and all its variations to Zoho
	 *
	 * @param WC_Product_Variable $product Variable product object
	 * @return array Array of results with parent and variation sync results
	 */
	protected function sync_variable_product_to_zoho( $product ) {
		$results = array(
			'parent_product_id' => null,
			'variations'        => array(),
			'success_count'     => 0,
			'failed_count'      => 0,
		);

		// First sync the parent variable product.
		$parent_zoho_id               = $this->sync_single_product_to_zoho( $product );
		$results['parent_product_id'] = $parent_zoho_id;

		if ( $parent_zoho_id ) {
			++$results['success_count'];
		} else {
			++$results['failed_count'];
		}

		// Get all variations.
		$variation_ids = $product->get_children();

		if ( ! empty( $variation_ids ) ) {
			foreach ( $variation_ids as $variation_id ) {
				$variation = wc_get_product( $variation_id );

				if ( ! $variation || ! $variation->is_type( 'variation' ) ) {
					$results['variations'][ $variation_id ] = array(
						'status'          => 'error',
						'message'         => 'Invalid variation product',
						'zoho_product_id' => null,
						'action'          => 'skipped',
					);
					++$results['failed_count'];
					continue;
				}

				// Check if variation already has Zoho ID (for better reporting).
				$existing_zoho_id = get_post_meta( $variation_id, 'zcrm_product_id', true );
				$action           = empty( $existing_zoho_id ) ? 'created' : 'updated';

				// Sync the variation (handles duplication check and meta update automatically).
				$variation_zoho_id = $this->sync_single_product_to_zoho( $variation );

				if ( $variation_zoho_id ) {
					$results['variations'][ $variation_id ] = array(
						'status'          => 'success',
						'message'         => sprintf( 'Variation %s successfully', $action ),
						'zoho_product_id' => $variation_zoho_id,
						'action'          => $action,
					);
					++$results['success_count'];

					// Store parent-child relationship in meta (always update this).
					if ( $parent_zoho_id ) {
						update_post_meta( $variation_id, 'zcrm_parent_product_id', $parent_zoho_id );
					}
				} else {
					$results['variations'][ $variation_id ] = array(
						'status'          => 'error',
						'message'         => sprintf( 'Failed to %s variation', 'created' === $action ? 'create' : 'update' ),
						'zoho_product_id' => null,
						'action'          => 'failed',
					);
					++$results['failed_count'];
				}

				// Add delay to avoid rate limiting.
				usleep( 200000 ); // 0.2 seconds.
			}
		}

		return $results;
	}

	/**
	 * Get Zoho product ID for a WooCommerce product
	 * First checks local meta, then searches Zoho by SKU, then by name
	 *
	 * @param WC_Product $product WooCommerce product object
	 * @return string|null Zoho product ID if found, null otherwise
	 */
	public function cmbird_get_zoho_product_id( $product ) {
		$woo_product_id  = $product->get_id();
		$zcrm_product_id = get_post_meta( $woo_product_id, 'zcrm_product_id', true );

		if ( ! empty( $zcrm_product_id ) ) {
			// Verify the product still exists in Zoho.
			if ( $this->verify_zoho_product_exists( $zcrm_product_id ) ) {
				return $zcrm_product_id;
			} else {
				// Clean up invalid meta.
				delete_post_meta( $woo_product_id, 'zcrm_product_id' );
			}
		}

		// Try to find product by SKU first (more reliable).
		if ( $product->get_sku() ) {
			$zcrm_product_id = $this->find_zoho_product_by_sku( $product->get_sku() );
			if ( $zcrm_product_id ) {
				// Save to WooCommerce meta for future lookups.
				update_post_meta( $woo_product_id, 'zcrm_product_id', $zcrm_product_id );
				return $zcrm_product_id;
			}
		}

		// Fallback: Try to find product by name.
		$zcrm_product_id = $this->find_zoho_product_by_name( $product->get_name() );
		if ( $zcrm_product_id ) {
			// Save to WooCommerce meta for future lookups.
			update_post_meta( $woo_product_id, 'zcrm_product_id', $zcrm_product_id );
			return $zcrm_product_id;
		}

		return null;
	}

	/**
	 * Get Zoho product by ID
	 *
	 * @param string $zoho_product_id Zoho product ID
	 * @return object|WP_Error Zoho product data or error
	 */
	public function cmbird_get_zoho_product_by_id( $zoho_product_id ) {
		if ( empty( $zoho_product_id ) ) {
			return new WP_Error( 'invalid_id', 'Product ID is required' );
		}

		$response = $this->zcrm_modules->cmbird_get_record( 'Products', $zoho_product_id );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		if ( empty( $response->data[0] ) ) {
			return new WP_Error( 'product_not_found', 'Product not found in Zoho CRM' );
		}

		return $response->data[0];
	}

	/**
	 * Find Zoho product by SKU (Product_Code)
	 *
	 * @param string $sku Product SKU
	 * @return string|null Zoho product ID if found, null otherwise
	 */
	protected function find_zoho_product_by_sku( $sku ) {
		if ( empty( $sku ) ) {
			return null;
		}

		$search_url = $this->zoho_crm_url . 'crm/v7/Products/search?criteria=Product_Code:equals:' . rawurlencode( $sku );
		$api        = new CMBIRD_API_Handler_Zoho();
		$response   = $api->execute_curl_call_get( $search_url );

		if ( is_wp_error( $response ) || empty( $response->data[0]->id ) ) {
			return null;
		}

		return $response->data[0]->id;
	}

	/**
	 * Find Zoho product by name
	 *
	 * @param string $name Product name
	 * @return string|null Zoho product ID if found, null otherwise
	 */
	protected function find_zoho_product_by_name( $name ) {
		if ( empty( $name ) ) {
			return null;
		}

		$search_url = $this->zoho_crm_url . 'crm/v7/Products/search?word=' . rawurlencode( $name );
		$api        = new CMBIRD_API_Handler_Zoho();
		$response   = $api->execute_curl_call_get( $search_url );

		if ( is_wp_error( $response ) || empty( $response->data[0]->id ) ) {
			return null;
		}

		return $response->data[0]->id;
	}

	/**
	 * Verify that a Zoho product exists
	 *
	 * @param string $zoho_product_id Zoho product ID
	 * @return bool True if product exists, false otherwise
	 */
	protected function verify_zoho_product_exists( $zoho_product_id ) {
		$response = $this->cmbird_get_zoho_product_by_id( $zoho_product_id );
		return ! is_wp_error( $response );
	}

	/**
	 * Create a new product in Zoho CRM
	 *
	 * @param WC_Product $product WooCommerce product object
	 * @return string|null Zoho product ID on success, null on failure
	 */
	protected function create_zoho_product( $product ) {
		$product_payload = $this->format_product_for_zoho( $product );

		$response = $this->zcrm_modules->cmbird_create_record( 'Products', $product_payload );

		if ( is_wp_error( $response ) || empty( $response->data[0]->details->id ) ) {
			// Log error for debugging but remove for production.
			return null;
		}

		$zoho_product_id = $response->data[0]->details->id;

		// Save to WooCommerce meta.
		update_post_meta( $product->get_id(), 'zcrm_product_id', $zoho_product_id );

		return $zoho_product_id;
	}

	/**
	 * Update an existing product in Zoho CRM
	 *
	 * @param WC_Product $product WooCommerce product object
	 * @param string     $zoho_product_id Zoho product ID
	 * @return bool True on success, false on failure
	 */
	protected function update_zoho_product( $product, $zoho_product_id ) {
		$product_payload = $this->format_product_for_zoho( $product, true );

		$response = $this->zcrm_modules->cmbird_update_record( 'Products', $zoho_product_id, $product_payload );

		if ( is_wp_error( $response ) || empty( $response->data[0]->details->id ) ) {
			// Log error for debugging but remove for production.
			return false;
		}

		return true;
	}

	/**
	 * Format WooCommerce product data for Zoho CRM
	 * Enhanced to handle variable products and variations
	 *
	 * @param WC_Product $product WooCommerce product object
	 * @param bool       $update Whether this is an update operation
	 * @return array Formatted product data for Zoho API
	 */
	protected function format_product_for_zoho( $product, $update = false ) {
		// Get product categories as comma-separated string.
		$category_names = array();
		$category_ids   = $product->get_category_ids();

		if ( ! empty( $category_ids ) ) {
			foreach ( $category_ids as $cat_id ) {
				$term = get_term( $cat_id, 'product_cat' );
				if ( $term && ! is_wp_error( $term ) ) {
					$category_names[] = $term->name;
				}
			}
		}

		// Get product description.
		$description = $product->get_description();
		if ( empty( $description ) ) {
			$description = $product->get_short_description();
		}

		// Get product SKU - handle variations differently.
		$product_code = $product->get_sku();
		if ( empty( $product_code ) ) {
			$product_code = $product->get_id();
		}

		// Get stock quantity.
		$stock_quantity = $product->get_stock_quantity();
		if ( empty( $stock_quantity ) ) {
			$stock_quantity = 0;
		}

		// Get product name - enhance for variations.
		$product_name = $this->get_formatted_product_name( $product );

		// Core product data.
		$product_data = array(
			'Product_Name'     => $product_name,
			'Product_Code'     => $product_code,
			'Unit_Price'       => floatval( $product->get_price() ),
			'Description'      => $description,
			'Product_Category' => ! empty( $category_names ) ? implode( ', ', $category_names ) : '',
			'Product_Active'   => 'publish' === $product->get_status(),
			'Qty_in_Stock'     => $stock_quantity,
			'Handler'          => get_option( 'cmbird_zoho_crm_owner_id', '' ),
		);

		// Add variation-specific data if this is a variation.
		if ( $product->is_type( 'variation' ) ) {
			$product_data = $this->add_variation_specific_data( $product, $product_data );
		}

		// Add variable product specific data if this is a variable product.
		if ( $product->is_type( 'variable' ) ) {
			$product_data = $this->add_variable_product_specific_data( $product, $product_data );
		}

		// Add custom mapped fields.
		$custom_fields = $this->get_custom_mapped_fields_from_product( $product );
		$product_data  = array_merge( $product_data, $custom_fields );

		// Remove empty values to avoid overwriting existing data in updates.
		if ( $update ) {
			$product_data = array_filter(
				$product_data,
				function ( $value ) {
					return ! empty( $value ) || 0 === $value || false === $value;
				}
			);
		}

		return array( 'data' => array( $product_data ) );
	}

	/**
	 * Get formatted product name for Zoho (enhanced for variations)
	 *
	 * @param WC_Product $product WooCommerce product object
	 * @return string Formatted product name
	 */
	protected function get_formatted_product_name( $product ) {
		$name = $product->get_name();

		// For variations, include attributes in the name.
		if ( $product->is_type( 'variation' ) ) {
			$parent_product = wc_get_product( $product->get_parent_id() );
			if ( $parent_product ) {
				$parent_name = $parent_product->get_name();
				$attributes  = $product->get_variation_attributes();

				if ( ! empty( $attributes ) ) {
					$attribute_parts = array();
					foreach ( $attributes as $attribute_name => $attribute_value ) {
						// Clean up attribute name (remove 'attribute_' prefix if present).
						$clean_name = str_replace( 'attribute_', '', $attribute_name );
						$clean_name = str_replace( 'pa_', '', $clean_name ); // Remove taxonomy prefix.
						$clean_name = ucfirst( str_replace( array( '-', '_' ), ' ', $clean_name ) );

						if ( ! empty( $attribute_value ) ) {
							$attribute_parts[] = $clean_name . ': ' . $attribute_value;
						}
					}

					if ( ! empty( $attribute_parts ) ) {
						$name = $parent_name . ' - ' . implode( ', ', $attribute_parts );
					}
				}
			}
		}

		return $name;
	}

	/**
	 * Add variation-specific data to product payload
	 *
	 * @param WC_Product_Variation $product Variation product object
	 * @param array                $product_data Existing product data
	 * @return array Enhanced product data with variation info
	 */
	protected function add_variation_specific_data( $product, $product_data ) {
		// Get parent product ID for reference.
		$parent_id = $product->get_parent_id();
		if ( $parent_id ) {
			$parent_zoho_id = get_post_meta( $parent_id, 'zcrm_product_id', true );
			if ( $parent_zoho_id ) {
				$product_data['Parent_Product_ID'] = $parent_zoho_id;
			}
		}

		// Add variation attributes as additional fields.
		$attributes = $product->get_variation_attributes();
		if ( ! empty( $attributes ) ) {
			$attribute_description = array();
			foreach ( $attributes as $attribute_name => $attribute_value ) {
				$clean_name              = str_replace( array( 'attribute_', 'pa_' ), '', $attribute_name );
				$clean_name              = ucfirst( str_replace( array( '-', '_' ), ' ', $clean_name ) );
				$attribute_description[] = $clean_name . ': ' . $attribute_value;
			}

			// Append to description.
			if ( ! empty( $attribute_description ) ) {
				$variation_info              = 'Variation: ' . implode( ', ', $attribute_description );
				$product_data['Description'] = ! empty( $product_data['Description'] )
					? $product_data['Description'] . "\n\n" . $variation_info
					: $variation_info;
			}
		}

		// Mark as variation.
		$product_data['Product_Type'] = 'Variation';

		return $product_data;
	}

	/**
	 * Add variable product specific data to product payload
	 *
	 * @param WC_Product_Variable $product Variable product object
	 * @param array               $product_data Existing product data
	 * @return array Enhanced product data with variable product info
	 */
	protected function add_variable_product_specific_data( $product, $product_data ) {
		// Mark as variable product.
		$product_data['Product_Type'] = 'Variable';

		// Get variation count.
		$variation_ids                   = $product->get_children();
		$product_data['Variation_Count'] = count( $variation_ids );

		// Get price range for variable products.
		$min_price = $product->get_variation_price( 'min' );
		$max_price = $product->get_variation_price( 'max' );

		if ( $min_price !== $max_price ) {
			$product_data['Price_Range'] = 'From ' . wc_price( $min_price ) . ' to ' . wc_price( $max_price );
			$product_data['Min_Price']   = floatval( $min_price );
			$product_data['Max_Price']   = floatval( $max_price );
		}

		// Add available attributes info to description.
		$attributes = $product->get_variation_attributes();
		if ( ! empty( $attributes ) ) {
			$attribute_info = array();
			foreach ( $attributes as $attribute_name => $attribute_values ) {
				$clean_name       = str_replace( array( 'attribute_', 'pa_' ), '', $attribute_name );
				$clean_name       = ucfirst( str_replace( array( '-', '_' ), ' ', $clean_name ) );
				$attribute_info[] = $clean_name . ': ' . implode( ', ', $attribute_values );
			}

			if ( ! empty( $attribute_info ) ) {
				$variation_info              = 'Available Variations: ' . implode( '; ', $attribute_info );
				$product_data['Description'] = ! empty( $product_data['Description'] )
					? $product_data['Description'] . "\n\n" . $variation_info
					: $variation_info;
			}
		}

		return $product_data;
	}

	/**
	 * Get custom mapped fields from product meta
	 *
	 * @param WC_Product $product WooCommerce product object
	 * @return array Custom field mappings
	 */
	protected function get_custom_mapped_fields_from_product( $product ) {
		$mapped_fields_json = get_option( 'zcrm_products_custom_fields' );
		if ( empty( $mapped_fields_json ) ) {
			return array();
		}

		$mapped_fields = json_decode( $mapped_fields_json, true );
		if ( ! is_array( $mapped_fields ) ) {
			return array();
		}

		$zoho_fields = array();

		foreach ( $mapped_fields as $woo_meta_key => $zoho_field_api_name ) {
			$value = get_post_meta( $product->get_id(), $woo_meta_key, true );

			if ( ! empty( $value ) ) {
				// Use Zoho CRM field api name as key in payload.
				$zoho_fields[ $zoho_field_api_name ] = $value;
			}
		}

		return $zoho_fields;
	}

	/**
	 * Bulk sync multiple products to Zoho CRM
	 * Enhanced to handle variable products and their variations
	 *
	 * @param array $product_ids Array of WooCommerce product IDs
	 * @return array Results with success/failure counts and details
	 */
	public function cmbird_bulk_sync_products( $product_ids ) {
		$results = array(
			'success'           => 0,
			'failed'            => 0,
			'details'           => array(),
			'variable_products' => array(),
		);

		if ( empty( $product_ids ) || ! is_array( $product_ids ) ) {
			return $results;
		}

		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product( $product_id );

			if ( ! $product ) {
				++$results['failed'];
				$results['details'][] = array(
					'product_id' => $product_id,
					'status'     => 'error',
					'message'    => 'Product not found',
				);
				continue;
			}

			$sync_result = $this->cmbird_sync_product_to_zoho( $product );

			// Handle different response types based on product type.
			if ( $product->is_type( 'variable' ) && is_array( $sync_result ) ) {
				// Variable product returns array with details.
				$results['variable_products'][ $product_id ] = $sync_result;
				$results['success']                         += $sync_result['success_count'];
				$results['failed']                          += $sync_result['failed_count'];

				$results['details'][] = array(
					'product_id'        => $product_id,
					'product_type'      => 'variable',
					'parent_zoho_id'    => $sync_result['parent_product_id'],
					'variations_synced' => $sync_result['success_count'] - ( $sync_result['parent_product_id'] ? 1 : 0 ),
					'variations_failed' => $sync_result['failed_count'] - ( $sync_result['parent_product_id'] ? 0 : 1 ),
					'status'            => $sync_result['success_count'] > 0 ? 'success' : 'error',
					'message'           => sprintf(
						'Variable product sync: %d successful, %d failed',
						$sync_result['success_count'],
						$sync_result['failed_count']
					),
				);
			} elseif ( $sync_result ) {
				// Simple product or variation returns single ID.
				++$results['success'];
				$results['details'][] = array(
					'product_id'      => $product_id,
					'product_type'    => $product->get_type(),
					'zoho_product_id' => $sync_result,
					'status'          => 'success',
					'message'         => 'Product synced successfully',
				);
			} else {
				++$results['failed'];
				$results['details'][] = array(
					'product_id'   => $product_id,
					'product_type' => $product->get_type(),
					'status'       => 'error',
					'message'      => 'Failed to sync product to Zoho CRM',
				);
			}

			// Add a small delay to avoid rate limiting.
			usleep( 200000 ); // 0.2 seconds.
		}

		return $results;
	}

	/**
	 * Get all products from Zoho CRM with pagination support
	 *
	 * @param int $page Page number (1-based)
	 * @param int $per_page Products per page (max 200)
	 * @return array|WP_Error Array of products or error
	 */
	public function cmbird_get_all_zoho_products( $page = 1, $per_page = 200 ) {
		$per_page = min( $per_page, 200 ); // Zoho limit.
		$page     = max( $page, 1 );

		$url      = $this->zoho_crm_url . 'crm/v7/Products?page=' . $page . '&per_page=' . $per_page;
		$api      = new CMBIRD_API_Handler_Zoho();
		$response = $api->execute_curl_call_get( $url );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		return isset( $response->data ) ? $response->data : array();
	}

	/**
	 * Search products in Zoho CRM
	 *
	 * @param string $search_term Search term
	 * @param string $search_field Field to search in (optional)
	 * @return array|WP_Error Array of products or error
	 */
	public function cmbird_search_zoho_products( $search_term, $search_field = null ) {
		if ( empty( $search_term ) ) {
			return new WP_Error( 'empty_search', 'Search term is required' );
		}

		if ( $search_field ) {
			// Search in specific field.
			$search_url = $this->zoho_crm_url . 'crm/v7/Products/search?criteria=' . rawurlencode( $search_field . ':contains:' . $search_term );
		} else {
			// General search.
			$search_url = $this->zoho_crm_url . 'crm/v7/Products/search?word=' . rawurlencode( $search_term );
		}

		$api      = new CMBIRD_API_Handler_Zoho();
		$response = $api->execute_curl_call_get( $search_url );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		return isset( $response->data ) ? $response->data : array();
	}

	/**
	 * Get all available Zoho tax rates for a product
	 *
	 * @param WC_Product $product
	 * @return array
	 */
	public function get_all_zoho_tax_rates_for_product( $product ) {
		$tax_rates = array();

		// Get all tax classes that apply to this product.
		$tax_class      = $product->get_tax_class();
		$tax_rates_data = WC_Tax::get_rates_for_tax_class( $tax_class );

		foreach ( $tax_rates_data as $rate_id => $rate_data ) {
			$rate_code  = WC_Tax::get_rate_code( $rate_id );
			$mapped_tax = $this->get_zoho_tax_by_woo_tax_code( $rate_code );

			if ( $mapped_tax && isset( $mapped_tax['id'] ) ) {
				$tax_rates[] = array( 'id' => $mapped_tax['id'] ); // Array with id key and Zoho tax ID as value.
			}
		}

		return $tax_rates;
	}

	/**
	 * Get Zoho product ID, creating if necessary (enhanced version from sales order class)
	 *
	 * @param WC_Product $product
	 * @param WC_Order   $order Optional order for error notes
	 * @return string|null
	 */
	public function get_zoho_product_id( $product, $order = null ) {
		$woo_product_id  = $product->get_id();
		$zcrm_product_id = get_post_meta( $woo_product_id, 'zcrm_product_id', true );

		if ( ! empty( $zcrm_product_id ) ) {
			return $zcrm_product_id;
		}

		// Step 1: Try to find product in Zoho by name.
		$search_url = $this->zoho_crm_url . 'crm/v7/Products/search?word=' . rawurlencode( $product->get_name() );
		$api        = new \CMBIRD_API_Handler_Zoho();
		$response   = $api->execute_curl_call_get( $search_url );

		if ( ! is_wp_error( $response ) && ! empty( $response->data[0]->id ) ) {
			$zcrm_product_id = $response->data[0]->id;
			// Save to Woo meta.
			update_post_meta( $woo_product_id, 'zcrm_product_id', $zcrm_product_id );
			return $zcrm_product_id;
		} else {
			// Get all available tax rates for this product.
			$tax_rates = $this->get_all_zoho_tax_rates_for_product( $product );

			// Step 2: Create new product.
			$product_payload = array(
				'data' => array(
					array(
						'Product_Name' => $product->get_name(),
						'Unit_Price'   => round( floatval( $product->get_price() ), 2 ),
						'Description'  => wp_strip_all_tags( $product->get_description() ),
						'Product_Code' => $product->get_sku() ?: $product->get_id(),
						'Tax'          => $tax_rates, // Include all available tax rates.
					),
				),
			);

			$this->log( 'CommerceBird Debug - Creating new product in Zoho: ' . $product->get_name() . ' (SKU: ' . ( $product->get_sku() ?: $product->get_id() ) . ')', 'debug' );
			$this->log( 'CommerceBird Debug - Product Payload: ' . wp_json_encode( $product_payload ), 'debug' );

			$create_response = $this->zcrm_modules->cmbird_create_record( 'Products', $product_payload );

			// Log the full response for debugging.
			$this->log( 'CommerceBird Debug - Zoho Product Creation Response: ' . wp_json_encode( $create_response ), 'debug' );

			if ( is_wp_error( $create_response ) ) {
				$error_message = 'Failed to create product in Zoho: ' . $product->get_name() . ' - ' . $create_response->get_error_message();
				$this->log( 'CommerceBird Error - ' . $error_message, 'error' );

				// Save error as order note if order is provided.
				if ( $order ) {
					$order->add_order_note( 'Zoho Product Creation Error: ' . $error_message );
				}

				return null;
			}

			// Check for empty response or missing ID.
			if ( empty( $create_response->data[0]->details->id ) ) {
				$error_message = 'Product creation returned empty ID for: ' . $product->get_name();

				// Check if there are any error details in the response.
				if ( isset( $create_response->data[0] ) ) {
					$response_data = $create_response->data[0];

					// Check for status error.
					if ( isset( $response_data->status ) && $response_data->status === 'error' ) {
						$zoho_error     = isset( $response_data->message ) ? $response_data->message : 'Unknown Zoho error';
						$error_message .= ' - Zoho Error: ' . $zoho_error;

						// Check for detailed error information.
						if ( isset( $response_data->details ) && is_object( $response_data->details ) ) {
							if ( isset( $response_data->details->api_name ) ) {
								$error_message .= ' (Field: ' . $response_data->details->api_name . ')';
							}
						}
					}

					// Check for code-based errors.
					if ( isset( $response_data->code ) ) {
						$error_message .= ' - Error Code: ' . $response_data->code;
					}
				}

				$this->log( 'CommerceBird Error - ' . $error_message, 'error' );

				// Save error as order note if order is provided.
				if ( $order ) {
					$order->add_order_note( 'Zoho Product Creation Error: ' . $error_message );
				}

				return null;
			}

			$zcrm_product_id = $create_response->data[0]->details->id;
		}

		// Save to Woo meta.
		update_post_meta( $woo_product_id, 'zcrm_product_id', $zcrm_product_id );

		return $zcrm_product_id;
	}

	/**
	 * Update Zoho product with all available tax rates
	 *
	 * @param WC_Product $product
	 * @param string     $zcrm_product_id
	 * @param WC_Order   $order Optional order for error notes
	 * @return void
	 */
	public function update_zoho_product_with_tax_rates( $product, $zcrm_product_id, $order = null ) {
		// Get all available tax rates for this product.
		$tax_rates = $this->get_all_zoho_tax_rates_for_product( $product );

		if ( empty( $tax_rates ) ) {
			return; // No tax rates to update.
		}

		// Update the product in Zoho with tax rates.
		$product_payload = array(
			'data' => array(
				array(
					'id'               => $zcrm_product_id,
					'Product_Name'     => $product->get_name(),
					'Unit_Price'       => round( floatval( $product->get_price() ), 2 ),
					'Description'      => wp_strip_all_tags( $product->get_description() ),
					'Product_Code'     => $product->get_sku() ?: $product->get_id(),
					'Product_Category' => $product->get_category_ids() ? implode( ',', $product->get_category_ids() ) : '',
					'Tax'              => $tax_rates, // Include all available tax rates.
				),
			),
		);

		$update_response = $this->zcrm_modules->cmbird_update_record( 'Products', $zcrm_product_id, $product_payload );

		// Log any errors but don't fail the order sync.
		if ( is_wp_error( $update_response ) ) {
			$error_message = 'Failed to update Zoho product with tax rates: ' . $update_response->get_error_message();
			$this->log( $error_message, 'error' );

			// Save error as order note if order is provided.
			if ( $order ) {
				$order->add_order_note( 'Zoho Product Update Error: ' . $error_message );
			}
		}
	}

	/**
	 * Get Zoho tax mapping by WooCommerce tax code
	 *
	 * @param string $woo_tax_code
	 * @return array|null
	 */
	public function get_zoho_tax_by_woo_tax_code( $woo_tax_code ) {
		if ( ! $woo_tax_code ) {
			return null;
		}
		// get the rate code from the woo_tax_id last integer value after the last dash.
		$woo_tax_id = intval( preg_replace( '/.*-(\d+)$/', '$1', $woo_tax_code ) );
		if ( ! $woo_tax_id ) {
			return null;
		}

		$option = get_option( 'cmbird_zoho_crm_tax_rate_' . $woo_tax_id );
		if ( ! $option ) {
			return null;
		}

		$parts = explode( '|', $option );
		if ( count( $parts ) < 1 ) {
			return null;
		}
		// format the name by replacing the @@ with a space.
		$name = isset( $parts[1] ) ? str_replace( '@@', ' ', $parts[1] ) : '';

		return array(
			'id'    => $parts[0],
			'name'  => $name,
			'value' => isset( $parts[2] ) ? $parts[2] : '',
		);
	}
}

// Initialize the class.
$cmbird_zcrm_product = new CMBIRD_ZCRM_Product();
