<?php

namespace CommerceBird\Admin\Actions\Sync;

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

/**
 * Handles synchronization of products between WooCommerce and Zoho Inventory.
 */
class ZohoInventorySync {

	/**
	 * Sync data from Zoho Inventory.
	 *
	 * @param string $type product.
	 * @param array  $data to sync from Zoho Inventory.
	 * @param bool   $import import or update.
	 * @return mixed
	 */
	public static function sync( string $type, array $data, bool $import = false ) {
		if ( empty( $type ) ) {
			return false;
		}
		if ( $import ) {
			self::import( $type, $data );
		} else {
			self::import( $type, $data, true );
		}
	}

	/**
	 * Import data from Zoho Inventory using WooCommerce REST API batch endpoint.
	 *
	 * For product data will be like:
	 * {
	 * "item_id": string,
	 * "sku": string,
	 * "name": string,
	 * "description": string,
	 * "rate": float,
	 * "status": string,
	 * "category_name": string,
	 * "brand": string,
	 * "image_document_id": string,
	 * "image_name": string
	 * }
	 *
	 * @param string $type of provided data.
	 * @param array  $data of import.
	 * @param bool   $update whether to update existing items.
	 * @param string $endpoint API endpoint to use for import.
	 * @return mixed
	 */
	public static function import( string $type, array $data, bool $update = false, $endpoint = '' ) {
		$payload = array();
		// if $update is true, we will use update action.
		$action = $update ? 'update' : 'create';

		switch ( $type ) {
			case 'product':
				$endpoint = ! empty( $endpoint ) ? $endpoint : '/wc/v3/products/batch';
				$payload  = array(
					$action => $data,
				);
				break;
			case 'variations':
				// if endpoint is not provided, then return false as we don't know which product to update.
				$endpoint = ! empty( $endpoint ) ? $endpoint : '';
				$payload  = $data;
				break;
			default:
				return false;
		}

		if ( empty( $payload[ $action ] ) ) {
			return false;
		}

		add_filter( 'woocommerce_rest_check_permissions', '__return_true' );
		add_filter( 'wc_product_has_unique_sku', '__return_false' );
		$request = new \WP_REST_Request( 'POST', $endpoint );
		$request->set_body_params( $payload );
		$response = rest_do_request( $request );
		remove_filter( 'woocommerce_rest_check_permissions', '__return_true' );
		remove_filter( 'wc_product_has_unique_sku', '__return_false' );

		if ( 200 !== $response->get_status() ) {
			$logger = wc_get_logger();
			$logger->error(
				sprintf(
					'WC REST Batch Response - Status: %d, Message: %s',
					$response->get_status(),
					$response->get_data()['message'] ?? wp_json_encode( $response->get_data() )
				),
				array( 'source' => 'cmbird-zoho-inventory-items-sync' )
			);
		}

		return $response;
	}
}
