<?php
/**
 * WooCommerce catalog sync to backend.
 *
 * @package BOOSAIAS_For_WooCommerce
 */

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

class BOOSAIAS_Catalog_Sync {

	public function init() {
		add_action( 'save_post_product', array( $this, 'on_product_save' ), 10, 1 );
		add_action( 'woocommerce_update_product', array( $this, 'on_product_save' ), 10, 1 );
		add_action( 'wp_trash_post', array( $this, 'on_product_trash' ), 10, 1 );
		add_action( 'boosaias_full_sync', array( $this, 'run_full_sync' ) );
	}

	public function on_product_save( $product_id ) {
		if ( 'product' !== get_post_type( $product_id ) ) {
			return;
		}

		$transient_key = 'boosaias_debounce_' . $product_id;
		if ( get_transient( $transient_key ) ) {
			return;
		}
		set_transient( $transient_key, 1, 10 );

		$product = wc_get_product( $product_id );
		if ( ! $product ) {
			return;
		}

		$this->sync_products( array( $this->prepare_product( $product, 'upsert' ) ) );
	}

	public function on_product_trash( $post_id ) {
		if ( 'product' !== get_post_type( $post_id ) ) {
			return;
		}
		$this->sync_products( array( array( 'wc_id' => $post_id, 'action' => 'delete' ) ) );
	}

	public function run_full_sync() {
		$page     = 1;
		$per_page = 50;

		do {
			$products = wc_get_products( array(
				'status'  => 'publish',
				'limit'   => $per_page,
				'page'    => $page,
				'return'  => 'objects',
			) );

			if ( empty( $products ) ) {
				break;
			}

			$batch = array();
			foreach ( $products as $product ) {
				$batch[] = $this->prepare_product( $product, 'upsert' );
			}
			$this->sync_products( $batch );

			$page++;
		} while ( count( $products ) === $per_page );
	}

	private function prepare_product( WC_Product $product, $action ) {
		$description       = wp_strip_all_tags( $product->get_description() );
		$short_description = wp_strip_all_tags( $product->get_short_description() );

		if ( mb_strlen( $description ) > 4000 ) {
			$description = mb_substr( $description, 0, 4000 );
		}

		$categories = array();
		foreach ( $product->get_category_ids() as $cat_id ) {
			$term = get_term( $cat_id, 'product_cat' );
			if ( $term && ! is_wp_error( $term ) ) {
				$categories[] = $term->name;
			}
		}

		$attributes = array();
		foreach ( $product->get_attributes() as $attribute ) {
			if ( $attribute->is_taxonomy() ) {
				$terms = wc_get_product_terms( $product->get_id(), $attribute->get_name(), array( 'fields' => 'names' ) );
				$attributes[ wc_attribute_label( $attribute->get_name() ) ] = $terms;
			} else {
				$attributes[ $attribute->get_name() ] = explode( '|', $attribute->get_options()[0] ?? '' );
			}
		}

		$content_hash = md5( $product->get_name() . $description . $product->get_price() . wp_json_encode( $attributes ) );

		$image_url = '';
		$image_id  = $product->get_image_id();
		if ( $image_id ) {
			$image_url = (string) wp_get_attachment_url( $image_id );
		}

		return array(
			'wc_id'             => $product->get_id(),
			'action'            => $action,
			'title'             => $product->get_name(),
			'description'       => $description,
			'short_description' => $short_description,
			'sku'               => $product->get_sku(),
			'price'             => $product->get_price(),
			'regular_price'     => $product->get_regular_price(),
			'currency'          => get_woocommerce_currency(),
			'stock_status'      => $product->get_stock_status(),
			'categories'        => $categories,
			'attributes'        => $attributes,
			'url'               => get_permalink( $product->get_id() ),
			'image_url'         => $image_url,
			'content_hash'      => $content_hash,
		);
	}

	private function sync_products( $products ) {
		if ( empty( $products ) ) {
			return;
		}
		$client = new BOOSAIAS_Api_Client();
		$client->post( '/api/sync', array( 'products' => $products ), 30 );
	}
}
