<?php
/**
 * Inbound Sync Handler.
 *
 * @package MOWCPS\Common\Handlers\SyncHandler
 */

namespace MOWCPS\Common\Handlers\SyncHandler;

use MOWCPS\Common\Handlers\SyncHandler\Abstract_Sync_Handler as Common_Abstract_Sync_Handler;
use MOWCPS\Common\Constants\Plugin_Filters;
use MOWCPS\Common\Utils\Sync_Utils;
use MOWCPS\Common\Services\Logging\Supplier_Logger;

/**
 * Inbound sync handler implementation.
 */
class Inbound_Sync_Handler extends Common_Abstract_Sync_Handler {

	/**
	 * Constructor.
	 *
	 * @param int    $supplier_id   The supplier ID.
	 * @param int    $connection_id The connection ID.
	 * @param object $sync_handler  The sync handler instance.
	 */
	public function __construct( $supplier_id, $connection_id, $schedule_id, $batch_number, $page_number, $sync_handler ) {
		parent::__construct( $supplier_id, $connection_id, $schedule_id, $batch_number, $page_number );
		$this->sync_handler = $sync_handler;
	}

	/**
	 * Handle the inbound sync.
	 *
	 * @return mixed Sync result.
	 */
	public function handle_sync() {
		return $this->sync_handler->handle_sync( $this );
	}

	/**
	 * Set product data for inbound sync.
	 *
	 * @return mixed Sync result.
	 */
	public function set_product_data() {

		if ( has_filter( Plugin_Filters::FILTER_SET_DISCARDING_PRODUCTS_FLAG ) ) {
			$discarding_products_flag = apply_filters(
				Plugin_Filters::FILTER_SET_DISCARDING_PRODUCTS_FLAG,
				array(
					'config'        => $this->config,
					'page_number'   => $this->page_number,
					'batch_number'  => $this->batch_number,
					'supplier_id'   => $this->supplier_id,
					'connection_id' => $this->connection_id,
				)
			);
		}

		return $this->get_inbound_sync_product_data();
	}

	/**
	 * Get incoming data (no details required from website) via API call from an external supplier, filter it, and prepare it for syncing.
	 *
	 * @return mixed Sync result.
	 */
	private function get_inbound_sync_product_data() {
		// retrieve product data.
		Supplier_Logger::debug( $this->supplier_id, 'Fetching product data from supplier...' );
		$api_response  = $this->retrieve_product_data();
		$product_count = is_array( $api_response ) ? count( $api_response ) : 0;
		Supplier_Logger::debug( $this->supplier_id, 'Retrieved ' . $product_count . ' products from supplier' );

		// sync products.
		if ( $product_count > 0 ) {
			Supplier_Logger::debug( $this->supplier_id, 'Processing and syncing ' . $product_count . ' products to your store...' );
		} else {
			Supplier_Logger::debug( $this->supplier_id, 'No products found to sync from supplier' );
		}

		$sync_end_status = $this->prepare_unsynced_data_and_sync_products( $api_response );

		if ( 'Sync Completed' === $sync_end_status ) {
			Supplier_Logger::debug( $this->supplier_id, 'Product sync completed successfully!' );
		} else {
			Supplier_Logger::debug( $this->supplier_id, 'Sync status: ' . $sync_end_status );
		}

		return $sync_end_status;
	}
}
