<?php

/**
 * All WooCommerce related functions.
 *
 * @category WooCommerce
 * @package  CommerceBird
 * @author   Fawad Tiemoerie <info@roadmapstudios.com>
 * @license  GNU General Public License v3.0
 * @link     https://commercebird.com
 */

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

/**
 * Helper functions to ensure correct handling of Data being transferred via rest api.
 *
 * @param WC_Product      $product The product object.
 * @param WP_REST_Request $request The request object.
 * @param boolean         $is_creating True if the product is being created, false if it is being updated.
 */
function cmbird_clear_product_cache( $product, $request, $is_creating ) {
	if ( $is_creating ) {
		$product_id                  = $product->get_id();
		$zoho_inventory_access_token = get_option( 'cmbird_zoho_inventory_access_token' );
		$cmbird_zi_product_sync      = get_option( 'cmbird_zoho_disable_product_sync_status' );
		if ( ! empty( $zoho_inventory_access_token ) && ! $cmbird_zi_product_sync ) {
			// if request contain meta zi_item_id, then return.
			if ( isset( $request['meta']['zi_item_id'] ) ) {
				return;
			}
			$product_handler = new CMBIRD_Products_ZI_Export();
			$product_handler->cmbird_zi_product_sync( $product_id );
		}

		// Sync to Zoho CRM as well.
		$zoho_crm_access_token = get_option( 'cmbird_zoho_crm_access_token' );
		if ( ! empty( $zoho_crm_access_token ) ) {
			$cmbird_zcrm_product_sync = get_option( 'cmbird_zoho_crm_disable_product_sync_status' );
			if ( ! $cmbird_zcrm_product_sync ) {
				$product = wc_get_product( $product_id );
				if ( $product ) {
					$zcrm_product_handler = new CMBIRD_ZCRM_Product();
					$zcrm_product_handler->cmbird_sync_product_to_zoho( $product );
				}
			}
		}

		wc_delete_product_transients( $product_id );
	}
}
add_action( 'woocommerce_rest_insert_product_object', 'cmbird_clear_product_cache', 10, 3 );



/**
 * Function to update the Contact in Zoho when customer updates address on frontend
 *
 * @param int $user_id - User ID.
 */
function cmbird_update_contact_via_accountpage( $user_id ) {
	// Return if this change is not made from the my account page.
	if ( ! is_user_logged_in() ) {
		return;
	}
	$zoho_inventory_access_token = get_option( 'cmbird_zoho_inventory_access_token' );
	if ( ! empty( $zoho_inventory_access_token ) ) {
		$contact_class_handle = new CMBIRD_Contact_ZI();
		$contact_class_handle->cmbird_contact_update_function( $user_id );

		global $wpdb;
		$meta_key_search = 'zi_contact_person_id%';
		$query           = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT meta_key, meta_value
			FROM {$wpdb->usermeta}
     			WHERE user_id = %d
       			AND meta_key LIKE %s",
				$user_id,
				$meta_key_search
			)
		); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- User-specific meta query, not suitable for caching.
		if ( ! empty( $query ) ) {
			// Usermeta keys containing 'zi_contact_person_id' exist.
			foreach ( $query as $row ) {
				$contact_class_handle->cmbird_update_contact_person( $user_id, $row->meta_value );
			}
		} else {
			return;
		}
	} else {
		return;
	}
}
add_action( 'profile_update', 'cmbird_update_contact_via_accountpage' );

add_action( 'wp_ajax_zoho_admin_product_sync', 'cmbird_zi_product_sync_class' );
/**
 * Sync a product to Zoho Inventory and Zoho CRM.
 *
 * If the product is a variable product, it will sync all variations to Zoho Inventory and Zoho CRM.
 * If the product is a simple product or variation, it will sync the product to Zoho Inventory and Zoho CRM.
 *
 * @param int $product_id The ID of the product to sync.
 *
 * @return void
 */
function cmbird_zi_product_sync_class( $product_id ) {
	if ( ! is_admin() ) {
		return;
	}

	if ( ! $product_id ) {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'zoho_admin_product_sync' ) ) {
			wp_send_json_error( 'Nonce verification failed' );
		} else {
			$product_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;
			if ( ! $product_id ) {
				wp_send_json_error( 'Invalid Product ID' );
			}
		}
	}
	$zoho_inventory_access_token = get_option( 'cmbird_zoho_inventory_access_token' );
	$cmbird_zi_product_sync      = get_option( 'cmbird_zoho_disable_product_sync_status' );
	if ( ! $cmbird_zi_product_sync && $zoho_inventory_access_token ) {
		$product_handler = new CMBIRD_Products_ZI_Export();
		$product_handler->cmbird_zi_product_sync( $product_id );
	}

	// Sync to Zoho CRM as well.
	$zoho_crm_access_token = get_option( 'cmbird_zoho_crm_access_token' );
	if ( ! empty( $zoho_crm_access_token ) ) {
		$cmbird_zcrm_product_sync = get_option( 'cmbird_zoho_crm_disable_product_sync_status' );
		if ( ! $cmbird_zcrm_product_sync ) {
			$product = wc_get_product( $product_id );
			if ( $product ) {
				$zcrm_product_handler = new CMBIRD_ZCRM_Product();
				$sync_result          = $zcrm_product_handler->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.
					$success_count = $sync_result['success_count'];
					$failed_count  = $sync_result['failed_count'];
					$parent_id     = $sync_result['parent_product_id'];

					// If parent_id is not in result, get it from post meta (for existing products).
					if ( ! $parent_id ) {
						$parent_id = get_post_meta( $product_id, 'zcrm_product_id', true );
					}

					if ( $success_count > 0 ) {
						update_post_meta( $product_id, 'zcrm_product_sync_status', 'success' );
						$message = sprintf(
							'Variable product synced: %d successful, %d failed. Parent ID: %s',
							$success_count,
							$failed_count,
							$parent_id ? $parent_id : 'N/A'
						);
						update_post_meta( $product_id, 'zcrm_product_sync_message', $message );
					} else {
						update_post_meta( $product_id, 'zcrm_product_sync_status', 'failed' );
						update_post_meta( $product_id, 'zcrm_product_sync_message', 'Failed to sync variable product and variations to Zoho CRM' );
					}
				} elseif ( $sync_result ) {
					// Simple product or variation returns single ID.
					update_post_meta( $product_id, 'zcrm_product_sync_status', 'success' );
					update_post_meta( $product_id, 'zcrm_product_sync_message', 'Product synced successfully to Zoho CRM with ID: ' . $sync_result );
				} else {
					update_post_meta( $product_id, 'zcrm_product_sync_status', 'failed' );
					update_post_meta( $product_id, 'zcrm_product_sync_message', 'Failed to sync product to Zoho CRM' );
				}
			}
		}
	}

	// if its variable product but without variations, then sync it.
	$product = wc_get_product( $product_id );
	if ( $product->is_type( 'variable' ) ) {
		$variations = $product->get_children();
		if ( isset( $variations ) && count( $variations ) === 0 ) {
			$zi_product_id = get_post_meta( $product_id, 'zi_item_id', true );
			if ( ! empty( $zi_product_id ) ) {
				// First get the item_group from Zoho Inventory using the zi_item_id and then sync the variations of that item group.
				$get_call           = new CMBIRD_API_Handler_Zoho();
				$zoho_inventory_oid = get_option( 'cmbird_zoho_inventory_oid' );
				if ( ! empty( $zoho_inventory_oid ) ) {
					$zoho_inventory_url = get_option( 'cmbird_zoho_inventory_url' );
					$url_item           = "{$zoho_inventory_url}inventory/v1/itemgroups/{$zi_product_id}?organization_id=$zoho_inventory_oid";
					$json               = $get_call->execute_curl_call_get( $url_item );
					$code               = $json->code;
					if ( is_wp_error( $json ) ) {
						update_post_meta( $product_id, 'zi_product_errmsg', 'Error fetching item group from Zoho Inventory: ' . $json->get_error_message() );
						return;
					}
					if ( 0 === $code || '0' === $code ) {
						if ( isset( $json->item_group ) ) {
							$product_handler = new CMBIRD_Products_ZI();
							$product_handler->import_variable_product_variations( $json->item_group, $product_id );
						}
					}
				}
			}
		}
	}
}

/**
 * Bulk-action to sync products from WooCommerce to Zoho
 *
 * @param array $bulk_array - array of bulk actions.
 * @return array $bulk_array - array of bulk actions.
 */
function cmbird_zi_sync_all_items_to_zoho( $bulk_array ) {
	$bulk_array['sync_item_to_zoho'] = 'Sync to Zoho';
	// add option to unmap items from zoho.
	$bulk_array['unmap_item_to_zoho'] = 'Unmap from Zoho';
	return $bulk_array;
}
add_filter( 'bulk_actions-edit-product', 'cmbird_zi_sync_all_items_to_zoho' );

add_filter( 'handle_bulk_actions-edit-product', 'cmbird_zi_sync_all_items_to_zoho_handler', 10, 3 );
function cmbird_zi_sync_all_items_to_zoho_handler( $redirect, $action, $object_ids ) {
	// let's remove query args first.
	$redirect = remove_query_arg( 'sync_item_to_zoho_done', $redirect );
	$redirect = remove_query_arg( 'unmap_item_to_zoho_done', $redirect );

	// do something for "Make Draft" bulk action.
	if ( 'sync_item_to_zoho' === $action ) {

		foreach ( $object_ids as $post_id ) {
			// Sync to Zoho Inventory.
			$product_handler = new CMBIRD_Products_ZI_Export();
			$product_handler->cmbird_zi_product_sync( $post_id );

			// Sync to Zoho CRM as well.
			$zoho_crm_access_token = get_option( 'cmbird_zoho_crm_access_token' );
			if ( ! empty( $zoho_crm_access_token ) ) {
				$cmbird_zcrm_product_sync = get_option( 'cmbird_zoho_crm_disable_product_sync_status' );
				if ( ! $cmbird_zcrm_product_sync ) {
					$product = wc_get_product( $post_id );
					if ( $product ) {
						$zcrm_product_handler = new CMBIRD_ZCRM_Product();
						$zcrm_product_handler->cmbird_sync_product_to_zoho( $product );
					}
				}
			}
		}

		// do not forget to add query args to URL because we will show notices later.
		$redirect = add_query_arg( 'sync_item_to_zoho_done', count( $object_ids ), $redirect );

	} elseif ( 'unmap_item_to_zoho' === $action ) {
		foreach ( $object_ids as $post_id ) {
			$nonce = wp_create_nonce( 'zi_product_unmap_hook' );
			cmbird_zi_product_unmap_hook( $post_id, $nonce );
		}
		// do not forget to add query args to URL because we will show notices later.
		$redirect = add_query_arg( 'unmap_item_to_zoho_done', count( $object_ids ), $redirect );
	}

	return $redirect;
}

// output the message of bulk action.
add_action( 'admin_notices', 'cmbird_sync_item_to_zoho_notices' );
function cmbird_sync_item_to_zoho_notices() {
	// verify nonce.
	if ( ! isset( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) ), 'bulk-edit-products' ) ) {
		return;
	}
	if ( ! empty( $_REQUEST['sync_item_to_zoho_done'] ) ) {
		echo '<div id="message" class="updated notice is-dismissible">
			<p>Products Synced. If product is not synced, please click on Edit Product to see the API response.</p>
		</div>';
	}
	if ( ! empty( $_REQUEST['unmap_item_to_zoho_done'] ) ) {
		echo '<div id="message" class="updated notice is-dismissible">
			<p>Products Unmapped from Zoho.</p>
		</div>';
	}
}

/**
 * Function to be called by ajax hook when unmap button called.
 * This function remove zoho mapped id.
 */
add_action( 'wp_ajax_zi_product_unmap_hook', 'cmbird_zi_product_unmap_hook' );
function cmbird_zi_product_unmap_hook( $product_id, $nonce = '' ) {
	// if nonce is not there in the request, then check if it is passed as parameter.
	if ( ! $nonce ) {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
	}
	// verify nonce.
	if ( ! $nonce || ! wp_verify_nonce( $nonce, 'zi_product_unmap_hook' ) ) {
		wp_send_json_error( 'Nonce verification failed' );
	}
	if ( ! $product_id && isset( $_POST['product_id'] ) ) {
		$product_id = sanitize_text_field( wp_unslash( $_POST['product_id'] ) );
	}

	if ( $product_id ) {
		$product = wc_get_product( $product_id );
		// If this is variable items then unmap all of it's variations.
		if ( $product->is_type( 'variable' ) ) {
			$variations = $product->get_children();
			if ( isset( $variations ) && count( $variations ) > 0 ) {
				foreach ( $variations as $child ) {
					delete_post_meta( $child['variation_id'], 'zi_item_id' );
					delete_post_meta( $child['variation_id'], 'zi_account_id' );
					delete_post_meta( $child['variation_id'], 'zi_account_name' );
					delete_post_meta( $child['variation_id'], 'zi_category_id' );
					delete_post_meta( $child['variation_id'], 'zi_inventory_account_id' );
					delete_post_meta( $child['variation_id'], 'zi_purchase_account_id' );
				}
			}
		}
		delete_post_meta( $product_id, 'zi_item_id' );
		delete_post_meta( $product_id, 'zi_account_id' );
		delete_post_meta( $product_id, 'zi_account_name' );
		delete_post_meta( $product_id, 'zi_category_id' );
		delete_post_meta( $product_id, 'zi_inventory_account_id' );
		delete_post_meta( $product_id, 'zi_purchase_account_id' );

		// Also unmap from Zoho CRM.
		delete_post_meta( $product_id, 'zcrm_product_id' );
		delete_post_meta( $product_id, 'zcrm_product_sync_status' );
		delete_post_meta( $product_id, 'zcrm_product_sync_message' );

		// update message.
		update_post_meta( $product_id, 'zi_product_errmsg', 'Product is Unmapped from Zoho Inventory and CRM' );
	}
}

/**
 * Function to be called by ajax hook when unmap button called.
 * This function remove zoho mapped id.
 */
add_action( 'wp_ajax_zi_customer_unmap_hook', 'cmbird_zi_customer_unmap_hook' );
function cmbird_zi_customer_unmap_hook( $order_id ) {
	// verify Nonce.
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'zi_customer_unmap_hook' ) ) {
		wp_send_json_error( 'Nonce verification failed' );
	}
	if ( ! $order_id && isset( $_POST['order_id'] ) ) {
		$order_id = sanitize_text_field( wp_unslash( $_POST['order_id'] ) );
	}

	$order       = wc_get_order( $order_id );
	$customer_id = $order->get_user_id();

	if ( $customer_id ) {
		delete_user_meta( $customer_id, 'zi_contact_id' );
		delete_user_meta( $customer_id, 'zi_contact_persons_id' );
		delete_user_meta( $customer_id, 'zi_contactperson_id_0' );
		delete_user_meta( $customer_id, 'zi_contactperson_id_1' );
		delete_user_meta( $customer_id, 'zi_currency_code' );
		delete_user_meta( $customer_id, 'zi_currency_id' );
		delete_user_meta( $customer_id, 'zi_created_time' );
		delete_user_meta( $customer_id, 'zi_last_modified_time' );
		delete_user_meta( $customer_id, 'zi_primary_contact_id' );
		delete_user_meta( $customer_id, 'zi_billing_address_id' );
		delete_user_meta( $customer_id, 'zi_shipping_address_id' );

		$order->add_order_note( 'Zoho Sync: Customer is now unmapped. Please try syncing the order again' );
		$order->save();
	}
}

/**
 * Add WordPress Meta box to show sync response
 */
function cmbird_product_metabox() {
	$zoho_inventory_access_token = get_option( 'cmbird_zoho_inventory_access_token' );
	$zoho_crm_access_token       = get_option( 'cmbird_zoho_crm_access_token' );
	if ( ! $zoho_inventory_access_token && ! $zoho_crm_access_token ) {
		return;
	}
	add_meta_box(
		'zoho-product-sync',
		__( 'Zoho Inventory', 'commercebird' ),
		'cmbird_product_metabox_callback',
		'product',
		'side',
		'high'
	);
	// normal metabox for zoho inventory body request.
	add_meta_box(
		'zoho-product-sync-normal',
		__( 'Zoho Inventory - Full Details', 'commercebird' ),
		'cmbird_product_metabox_body_request',
		'product',
		'normal',
		'high'
	);
}

/**
 * Shows the full API request body when syncing the product to Zoho Inventory.
 *
 * @param WP_Post $post The current post object.
 */
function cmbird_product_metabox_body_request( $post ) {
	$body_request = get_post_meta( $post->ID, 'zi_product_body_request', true );

	if ( empty( $body_request ) ) {
		echo '<p>No API request body available. Try syncing the product first.</p>';
		return;
	}

	// Format the JSON for better readability if it's valid JSON.
	$formatted_json = $body_request;
	$decoded        = json_decode( $body_request, true );
	if ( json_last_error() === JSON_ERROR_NONE ) {
		$formatted_json = wp_json_encode( $decoded, JSON_PRETTY_PRINT );
	}

	echo '<h4>API Request Body (JSON):</h4>';
	echo '<textarea readonly style="width:100%; height:400px; font-family:monospace; font-size:12px; border:1px solid # ccc; padding:10px;">' . esc_textarea( $formatted_json ) . '</textarea>';
	echo '<p><small>This is the actual JSON data that was sent to Zoho Inventory API. You can copy this content.</small></p>';

	// Add a copy button for convenience.
	echo '<button type="button" onclick="copyBodyRequest()" style="margin-top:5px;" class="button">Copy to Clipboard</button>';
	echo '<script>
	function copyBodyRequest() {
		const textarea = document.querySelector(\'textarea[readonly]\');
		textarea.select();
		document.execCommand(\'copy\');
		alert(\'Request body copied to clipboard!\');
	}
	</script>';
}
/**
 * Callback for product metabox to show sync response.
 *
 * @param WP_Post $post The current post object.
 */
function cmbird_product_metabox_callback( $post ) {
	$response = get_post_meta( $post->ID, 'zi_product_errmsg' );
	echo 'API Response: ' . esc_html( implode( $response ) ) . '<br>';

	// Show CRM sync status.
	$zcrm_sync_status  = get_post_meta( $post->ID, 'zcrm_product_sync_status', true );
	$zcrm_sync_message = get_post_meta( $post->ID, 'zcrm_product_sync_message', true );
	if ( $zcrm_sync_status ) {
		$status_color = 'success' === $zcrm_sync_status ? 'green' : 'red';
		echo '<p style="color:' . esc_attr( $status_color ) . ';"><strong>CRM Sync:</strong> ' . esc_html( $zcrm_sync_message ) . '</p>';
	}

	// Generate nonce.
	$nonce       = wp_create_nonce( 'zoho_admin_product_sync' );
	$nonce_unmap = wp_create_nonce( 'zi_product_unmap_hook' );
	$post_id     = $post->ID;
	echo '<br><a href="javascript:void(0)" style="width:100%; text-align: center;" class="button button-primary" onclick="zoho_admin_product_ajax(' . esc_attr( $post_id ) . ', \'' . esc_attr( $nonce ) . '\')">Sync Product</a>';
	echo '<br><a href="javascript:void(0)" style="margin-top:10px; background:#b32d2e; border-color: # b32d2e; width:100%; text-align: center;" class="button button-primary" onclick="zoho_admin_unmap_product_ajax(' . esc_attr( $post_id ) . ', \'' . esc_attr( $nonce_unmap ) . '\')">Unmap this Product</a>';
	$product      = wc_get_product( $post->ID );
	$product_type = $product->get_type();
	if ( 'variable' === $product_type || 'variable-subscription' === $product_type ) {
		echo '<p class="howto" style="color:#b32d2e;"><strong>Important : </strong> Please ensure all variations have price and SKU</p>';
	}
	// echo the zi_category_id.
	$zi_category_id = get_post_meta( $post->ID, 'zi_category_id', true );
	if ( $zi_category_id ) {
		echo '<p class="howto"><strong>Zoho Category: </strong>' . esc_html( $zi_category_id ) . '</p>';
	}
	// make api call to get the zoho item details.
	$zi_item_id = get_post_meta( $post->ID, 'zi_item_id', true );
	if ( $zi_item_id && is_admin() ) {
		$zoho_inventory_oid = get_option( 'cmbird_zoho_inventory_oid' );
		$zoho_inventory_url = get_option( 'cmbird_zoho_inventory_url' );
		$urlitem            = "{$zoho_inventory_url}inventory/v1/items/{$zi_item_id}?organization_id=$zoho_inventory_oid";
		// fwrite( $fd, PHP_EOL . 'URL : ' . $urlitem );

		sleep( 1 ); // to avoid 429 error.
		$execute_curl_call = new CMBIRD_API_Handler_Zoho();
		$json              = $execute_curl_call->execute_curl_call_get( $urlitem );
		$code              = (int) property_exists( $json, 'code' ) ? $json->code : '0';
		if ( '0' === $code || 0 === $code ) {
			// echo the item details here that are in array called "item".
			$item                   = $json->item;
			$actual_available_stock = (int) property_exists( $item, 'actual_available_stock' ) ? $item->actual_available_stock : '0';
			$rate                   = (int) property_exists( $item, 'rate' ) ? $item->rate : '0';
			echo '<p class="howto"><strong>Rate: </strong>' . esc_html( $rate ) . '</p>';
			// echo the actual_available_stock.
			echo '<p class="howto"><strong>Available Stock: </strong>' . esc_html( $actual_available_stock ) . '</p>';
			// echo the zoho category name from the item.
			$category_name = (string) property_exists( $item, 'category_name' ) ? $item->category_name : '';
			if ( ! empty( $category_name ) || 'variable' === $product_type || 'variable-subscription' === $product_type ) {
				echo '<p class="howto"><strong>Category Name: </strong>' . esc_html( $category_name ) . '</p>';
			}
			// echo all properties from item except description.
			echo '<details><summary>More Details</summary>';
			echo '<ul>';
			foreach ( $item as $key => $value ) {
				if ( 'description' === $key ) {
					continue;   // skip description.
				}
				// Skip empty arrays.
				if ( is_array( $value ) && empty( $value ) ) {
					continue;
				}
				echo '<li><strong>' . esc_html( $key ) . ': </strong>';
				if ( is_array( $value ) || is_object( $value ) ) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Debug display, output is escaped.
					echo '<pre>' . esc_html( print_r( $value, true ) ) . '</pre>';
				} else {
					echo esc_html( $value );
				}
				echo '</li>';
			}
			echo '</ul>';
			echo '</details>';
			echo '<br>';
		}
	}
}
add_action( 'add_meta_boxes', 'cmbird_product_metabox' );


/**
 * Add Zoho and Exact Item IDs to Product and Variations
 *
 * @return void
 */
add_action( 'woocommerce_product_options_pricing', 'cmbird_item_id_field' );
add_action( 'woocommerce_variation_options_pricing', 'cmbird_item_id_variation_field', 10, 3 );
function cmbird_item_id_field() {
	woocommerce_wp_text_input(
		array(
			'id'          => 'eo_item_id',
			'label'       => esc_html__( 'Exact Item ID', 'commercebird' ),
			'class'       => 'readonly',
			'desc_tip'    => true,
			'description' => esc_html__( 'This is the Exact Item ID of this product. You cannot change this', 'commercebird' ),
		)
	);
	woocommerce_wp_text_input(
		array(
			'id'          => 'zi_item_id',
			'label'       => esc_html__( 'Zoho Item ID', 'commercebird' ),
			'class'       => 'readonly',
			'desc_tip'    => true,
			'description' => esc_html__( 'This is the Zoho Item ID of this product. You cannot change this', 'commercebird' ),
		)
	);
}
function cmbird_item_id_variation_field( $loop, $variation_data, $variation ) {
	woocommerce_wp_text_input(
		array(
			'id'          => 'eo_item_id[' . $loop . ']',
			'class'       => 'readonly',
			'label'       => esc_html__( 'Exact Item ID', 'commercebird' ),
			'value'       => get_post_meta( $variation->ID, 'eo_item_id', true ),
			'desc_tip'    => true,
			'description' => esc_html__( 'This is the Exact Item ID of this product. You cannot change this', 'commercebird' ),
		)
	);
	woocommerce_wp_text_input(
		array(
			'id'          => 'zi_item_id[' . $loop . ']',
			'class'       => 'readonly',
			'label'       => esc_html__( 'Zoho Item ID', 'commercebird' ),
			'value'       => get_post_meta( $variation->ID, 'zi_item_id', true ),
			'desc_tip'    => true,
			'description' => esc_html__( 'This is the Zoho Item ID of this product. You cannot change this', 'commercebird' ),
		)
	);
}

/**
 * Adds 'Zoho Sync' column header to 'Orders' page immediately after 'Total' column.
 *
 * @param string[] $columns
 * @return string[] $new_columns
 */
function cmbird_zi_sync_column_orders_overview( $columns ) {
	$zoho_inventory_access_token = get_option( 'cmbird_zoho_inventory_access_token' );
	$zoho_crm_access_token       = get_option( 'cmbird_zoho_crm_access_token' );
	if ( empty( $zoho_inventory_access_token ) && empty( $zoho_crm_access_token ) ) {
		return $columns;
	}
	$new_columns = array();
	foreach ( $columns as $column_name => $column_info ) {

		$new_columns[ $column_name ] = $column_info;

		if ( 'order_total' === $column_name ) {
			$new_columns['zoho_sync'] = __( 'Zoho Sync', 'commercebird' );
		}
	}
	return $new_columns;
}
add_filter( 'manage_woocommerce_page_wc-orders_columns', 'cmbird_zi_sync_column_orders_overview', 20 );

/**
 * Adding Sync Status for Orders Column
 *
 * @param string $column Column name.
 * @param int    $order_id $order id.
 * @return void
 */
function cmbird_zi_add_zoho_orders_content( $column, $order_id ) {
	$zi_url       = get_option( 'cmbird_zoho_inventory_url' );
	$zi_visit_url = str_replace( 'www.zohoapis', 'inventory.zoho', $zi_url );
	switch ( $column ) {
		case 'zoho_sync':
			// Get custom order meta data.
			$order         = wc_get_order( $order_id );
			$zi_order_id   = $order->get_meta( 'zi_salesorder_id', true, 'edit' );
			$zcrm_order_id = $order->get_meta( 'zcrm_sales_order_id', true, 'edit' );

			if ( $zi_order_id || $zcrm_order_id ) {
				echo '<span class="dashicons dashicons-yes-alt" style="color:green;"></span>';

				// Only show the external link if we have a ZI order ID for the URL.
				if ( $zi_order_id ) {
					$url = $zi_visit_url . 'app#/salesorders/' . $zi_order_id;
					echo '<a href="' . esc_url( $url ) . '" target="_blank"> <span class="dashicons dashicons-external" style="color:green;"></span> </a>';
				}
			} else {
				echo '<span class="dashicons dashicons-dismiss" style="color:red;"></span>';
			}
			unset( $order );
			break;
	}
}
add_action( 'manage_woocommerce_page_wc-orders_custom_column', 'cmbird_zi_add_zoho_orders_content', 20, 2 );

/**
 * Adds 'Zoho Sync' column content.
 *
 * @param string[] $column name of column being displayed
 */
function cmbird_zi_add_zoho_column_content( $column ) {
	global $post;
	$post_type = get_post_type( $post );

	if ( 'zoho_sync' === $column && 'product' === $post_type ) {
		$product_id    = $post->ID;
		$zi_product_id = get_post_meta( $product_id, 'zi_item_id' );
		if ( $zi_product_id ) {
			echo '<span class="dashicons dashicons-yes-alt" style="color:green;"></span>';
		} else {
			echo '<span class="dashicons dashicons-dismiss" style="color:red;"></span>';
		}
	}
}
add_action( 'manage_product_posts_custom_column', 'cmbird_zi_add_zoho_column_content' );

/**
 * Adds 'Zoho Sync' column header to 'Products' page.
 *
 * @param string[] $columns
 * @return string[] $new_columns
 */
function cmbird_zi_sync_column_products_overview( $columns ) {
	$zoho_inventory_access_token = get_option( 'cmbird_zoho_inventory_access_token' );
	if ( empty( $zoho_inventory_access_token ) ) {
		return $columns;
	}
	$new_columns = array();

	foreach ( $columns as $column_name => $column_info ) {

		$new_columns[ $column_name ] = $column_info;

		if ( 'product_cat' === $column_name ) {
			$new_columns['zoho_sync'] = __( 'Zoho Sync', 'commercebird' );
		}
	}

	return $new_columns;
}
add_filter( 'manage_edit-product_columns', 'cmbird_zi_sync_column_products_overview', 20 );

/**
 * Make 'Zoho Sync' column filterable.
 */
function cmbird_zi_sync_column_filterable() {
	global $typenow;

	if ( 'product' === $typenow ) {
		// code here.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin product filter, no data modification.
		$value = isset( $_GET['zoho_sync_filter'] ) ? sanitize_text_field( wp_unslash( $_GET['zoho_sync_filter'] ) ) : '';

		echo '<select name="zoho_sync_filter">';
		echo '<option value="">Zoho Sync Filter</option>';

		// Count synced products.
		$synced_count = new WP_Query(
			array(
				'post_type'  => 'product',
				'meta_query' => array(
					array(
						'key'     => 'zi_item_id',
						'compare' => 'EXISTS',
					),
				),
				'fields'     => 'ids',
			)
		);
		$synced_count = $synced_count->found_posts;
		$synced_label = 'Synced';
		if ( $synced_count > 0 ) {
			$synced_label .= ' (' . $synced_count . ')';
		}
		echo '<option value="synced" ' . selected( $value, 'synced', false ) . '>' . esc_html( $synced_label ) . '</option>';

		// Count not synced products.
		$not_synced_count = new WP_Query(
			array(
				'post_type'  => 'product',
				'meta_query' => array(
					array(
						'key'     => 'zi_item_id',
						'compare' => 'NOT EXISTS',
					),
				),
				'fields'     => 'ids',
			)
		);
		$not_synced_count = $not_synced_count->found_posts;
		$not_synced_label = 'Not Synced';
		if ( $not_synced_count > 0 ) {
			$not_synced_label .= ' (' . $not_synced_count . ')';
		}
		echo '<option value="not_synced" ' . selected( $value, 'not_synced', false ) . '>' . esc_html( $not_synced_label ) . '</option>';

		echo '</select>';
	}
}
add_action( 'restrict_manage_posts', 'cmbird_zi_sync_column_filterable' );

/**
 * Modify the product query based on the filter.
 *
 * @param WP_Query $query The query object.
 */
function cmbird_zi_sync_column_filter_query( $query ) {
	global $typenow, $pagenow;

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin product filter query, no data modification.
	if ( 'product' === $typenow && 'edit.php' === $pagenow && isset( $_GET['zoho_sync_filter'] ) && $_GET['zoho_sync_filter'] !== '' ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin product filter query, no data modification.
		$value = sanitize_text_field( wp_unslash( $_GET['zoho_sync_filter'] ) );

		$meta_query = array();

		if ( 'synced' === $value ) {
			$meta_query[] = array(
				'key'     => 'zi_item_id',
				'compare' => 'EXISTS',
			);
		} elseif ( 'not_synced' === $value ) {
			$meta_query[] = array(
				'relation' => 'OR',
				array(
					'key'     => 'zi_item_id',
					'compare' => 'NOT EXISTS',
				),
				array(
					'key'     => 'zi_item_id',
					'value'   => '',
					'compare' => '=',
				),
			);
		}

		$query->set( 'meta_query', $meta_query );
	}
}
add_action( 'pre_get_posts', 'cmbird_zi_sync_column_filter_query' );

/**
 * Change Action Scheduler default purge to 1 week
 *
 * @return int
 */
function cmbird_action_scheduler_purge() {
	return WEEK_IN_SECONDS;
}
add_filter( 'action_scheduler_retention_period', 'cmbird_action_scheduler_purge' );

add_filter(
	'action_scheduler_default_cleaner_statuses',
	function ( $statuses ) {
		$statuses[] = ActionScheduler_Store::STATUS_FAILED;
		return $statuses;
	}
);

/**
 * Register the custom order statuses "shipped" and "fulfilled"
 *
 * @return void
 */
function cmbird_register_custom_order_statuses() {
	register_post_status(
		'wc-shipped',
		array(
			'label'                     => _x( 'Shipped', 'Order status', 'commercebird' ),
			'public'                    => true,
			'exclude_from_search'       => false,
			'show_in_admin_all_list'    => true,
			'show_in_admin_status_list' => true,
			// translators: %s is the number of shipped orders.
			'label_count'               => _n_noop( 'Shipped <span class="count">(%s)</span>', 'Shipped <span class="count">(%s)</span>', 'commercebird' ),
		)
	);
	register_post_status(
		'wc-fulfilled',
		array(
			'label'                     => _x( 'Fulfilled', 'Order status', 'commercebird' ),
			'public'                    => true,
			'exclude_from_search'       => false,
			'show_in_admin_all_list'    => true,
			'show_in_admin_status_list' => true,
			// translators: %s is the number of fulfilled orders.
			'label_count'               => _n_noop( 'Fulfilled <span class="count">(%s)</span>', 'Fulfilled <span class="count">(%s)</span>', 'commercebird' ),
		)
	);
}
add_action( 'init', 'cmbird_register_custom_order_statuses' );
/**
 * Add custom order statuses to list of WC Order statuses
 *
 * @param array $order_statuses Existing order statuses.
 * @return array Modified order statuses.
 */
function cmbird_add_custom_order_statuses( $order_statuses ) {
	$order_statuses['wc-shipped']   = _x( 'Shipped', 'Order status', 'commercebird' );
	$order_statuses['wc-fulfilled'] = _x( 'Fulfilled', 'Order status', 'commercebird' );
	return $order_statuses;
}
add_filter( 'wc_order_statuses', 'cmbird_add_custom_order_statuses' );

/**
 * Modify the Products API to include brands.
 *
 * TODO: This is a temporary solution. We need to find a better way to include brands in the API response.
 *
 * @param $response The response object.
 * @param $post The post object.
 * @param $request The request object.
 * @return mixed
 */
// add_filter( 'woocommerce_rest_prepare_product_object', 'cmbird_rest_api_prepare_brands_tax', 10, 3 );
// function cmbird_rest_api_prepare_brands_tax( $response, $object, $request ) {.
// $product_id = $object->get_id();
// if ( empty( $response->data['product_brands'] ) ) {.
// $terms = array();
// foreach ( wp_get_post_terms( $product_id, 'product_brands' ) as $term ) {.
// $terms[] = array(
// 'id'   => $term->term_id,.
// 'name' => $term->name,.
// 'slug' => $term->slug,.
// );
// }.
// $response->data['product_brands'] = $terms;
// }.
// return $response;
// }.

// function cmbird_prepare_insert_product( $product, $request ) {.
// if ( isset( $request['product_brands'] ) ) {.
// wp_set_post_terms( $request['id'], $request['product_brands'], 'product_brands', false );
// }.
// return $product;
// }.
// add_filter( 'woocommerce_rest_pre_insert_product_object', 'cmbird_prepare_insert_product', 10, 2 );
