<?php

// If this file is called directly, abort.
if (!defined('WPINC')) {
	die;
}

// Includes
if (!class_exists('ProductFormatter')) {
	require_once ASWP_ATHENA_CORE_INC . 'Controller/ProductFormatter.php';
}

if (!function_exists('authorized_fetch')) {
	require_once __DIR__ . '/../Helpers/authorization.php';
}
// END Includes

class ProductPartialReindexController {
	public function reindexProductUpdate($product_id) {
		$product = wc_get_product($product_id);
		if (!$product) return;

		$productData = ProductFormatter::format($product);

		$body = [
			'token' => $this->getToken(),
			'data' => [
				'update' => [$productData],
				'delete' => []
			]
		];

		$this->sendRequest($body);
	}

	public function reindexProductDelete($product_id) {
		$body = [
			'token' => $this->getToken(),
			'data' => [
				'update' => [],
				'delete' => [
					['entity_id' => (int) $product_id]
				]
			]
		];

		$this->sendRequest($body);
	}

	private function getToken() {
		$options = get_option('athena_options');
		return $options['dashboard_website_token'] ?? '';
	}

	private function sendRequest($body) {
		$response = authorized_fetch('open-api/reindex/partial/async', $body);

		if (is_wp_error($response)) {
			AthenaLogger::error('Request error: ' . $response->get_error_message());
		} else {
			AthenaLogger::debug(function() use ($response) {
				return 'Response: ' . print_r($response, true);
			});
		}
	}
}