<?php

namespace HulkPlugins\Woo\ProductConditionManager\Controllers;

use HulkPlugins\Woo\ProductConditionManager\Services\FrontendService;
use HulkPlugins\Woo\ProductConditionManager\Traits\SingletonTrait;
use WC_Product;
use WP_REST_Response;

defined( 'ABSPATH' ) || exit;

class RestController {
	use SingletonTrait;

	public function init_hooks(): void {
		add_filter( 'woocommerce_rest_prepare_product_object', [ $this, 'prepare_product_object' ], 10, 2 );
	}

	/**
	 * Prepare product condition in product response.
	 * @param WP_REST_Response $response
	 * @param WC_Product $post
	 *
	 * @return WP_REST_Response
	 */
	public function prepare_product_object( WP_REST_Response $response, WC_Product $post ): WP_REST_Response {

		$frontendService = FrontendService::getInstance();

		// Label
		$productConditionLabel = $frontendService->getProductConditionLabel( $post->get_id(), false );

		// Condition
		$productCondition = $frontendService->getProductCondition( $post->get_id() );

		$response->data['hulk_woo_pcm_product_condition_label'] = $productConditionLabel;
		$response->data['hulk_woo_pcm_product_condition_slug'] = (string) get_post_meta( $post->get_id(), 'hulk_woo_pcm_productCondition', true );
		$response->data['hulk_woo_pcm_product_condition_group'] = $productCondition['group'] ?? '';
		$response->data['hulk_woo_pcm_product_condition'] = $productCondition['condition'] ?? '';

		return $response;
	}
}
