<?php
/**
 * Simple Product object for sync.
 *
 * @package    Common
 * @subpackage Services\Product_Sync\SyncProducts\Simple
 * @author     miniOrange <info@miniorange.com>
 * @link       https://miniorange.com
 */

namespace MOWCPS\Common\Services\Product_Sync\SyncProducts\Simple;

use MOWCPS\Common\Handlers\SyncHandler\Abstract_Sync_Handler;
use MOWCPS\Common\Models\Attribute_Mapping_Model;
use MOWCPS\Common\Services\Product_Sync\SyncProducts\MO_Product;
use MOWCPS\Common\Models\Sync_Queue_Model;
use MOWCPS\Common\Constants\Constants;

/**
 * Class for MO Simple Product.
 */
class MO_Simple_Product extends Abstract_Sync_Handler {
	use MO_Product;

	/**
	 * API Product data for the current product.
	 *
	 * @var mixed
	 */
	public $product_data;

	/**
	 * Config data for the current External Supplier.
	 *
	 * @var array
	 */
	public $config = array();

	/**
	 * Supplier ID of the current sync process.
	 *
	 * @var int
	 */
	public $supplier_id;

	/**
	 * Schedule ID of the current sync process.
	 *
	 * @var int
	 */
	public $schedule_id;

	/**
	 * Connection ID of the current sync process.
	 *
	 * @var int
	 */
	public $connection_id;

	/**
	 * Constructor.
	 *
	 * @param int $supplier_id   The supplier ID.
	 * @param int $schedule_id   The schedule ID.
	 * @param int $connection_id The connection ID.
	 */
	public function __construct( $supplier_id, $schedule_id, $connection_id ) {
		$this->supplier_id   = $supplier_id;
		$this->schedule_id   = $schedule_id;
		$this->connection_id = $connection_id;
		$this->structure     = Constants::SIMPLE;
		$attribute_mapping_ids = Sync_Queue_Model::get_attribute_mapping_ids_from_queue( $supplier_id, $connection_id, $schedule_id );
		$this->config          = Attribute_Mapping_Model::get_all(
			array(
				'ids'          => $attribute_mapping_ids,
				'product_type' => 'parent',
				'type'         => 'core',
			)
		);
		$this->config          = $this->group_config( $this->config );
	}

	/**
	 * Set the fields of the Simple product.
	 *
	 * @param  mixed  $product_data API Product data for the current product.
	 * @param  string $operation    Operation to be performed. Can be 'add' or 'update'. Default empty string processes all fields.
	 * @return void
	 */
	public function set_fields( $product_data, $operation = '' ): void {
		foreach ( $this->config as $field ) {
			if ( ! empty( $operation ) && ! $this->should_process_field( $field, $operation ) ) {
				continue;
			}
			$this->attr_config     = $field;
			$this->advanced_config = $field['advanced_configuration'] ?? array();
			$wc_attribute          = $field['wc_attribute'];
			$supplier_attribute    = $field['supplier_attribute'];
			$method                = 'get_' . $wc_attribute;

			if ( method_exists( $this, $method ) ) {
				$this->product_data  = $product_data;
				$this->$wc_attribute = $this->$method( $supplier_attribute );
			}
		}
	}
}
