<?php
/**
 * Omnibus provider for WC Price History plugin.
 *
 * @package Ilabs\Firevert\Core\Integration\Omnibus
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Integration\Omnibus;

use PriorPrice\HistoryStorage;

/**
 * Class OmnibusByPriceHistoryProvider
 */
final class OmnibusByPriceHistoryProvider extends AbstractOmnibusProvider {

	/**
	 * Returns the readable name of the source plugin.
	 *
	 * @return string Plugin name.
	 */
	public function get_plugin_name(): string {
		return 'WC Price History';
	}

	/**
	 * Returns the readable name of the source plugin creator.
	 *
	 * @return string Plugin creator.
	 */
	public function get_plugin_creator(): string {
		return 'Konrad Karpieszuk';
	}

	/**
	 * Checks whether the WC Price History plugin is active.
	 *
	 * @return bool True if plugin is active.
	 */
	public function is_active(): bool {
		return defined( 'WC_PRICE_HISTORY_VERSION' ) && function_exists( 'get_wc_price_history_version' );
	}

	/**
	 * Returns the lowest price for the given product.
	 *
	 * @param int $product_id WooCommerce product ID.
	 *
	 * @return float|null Lowest price or null.
	 */
	public function get_lowest_price( int $product_id ): ?float {
		if ( ! class_exists( \PriorPrice\HistoryStorage::class ) || ! $this->is_active() ) {
			return null;
		}

		$storage = new HistoryStorage();
		$price   = $storage->get_minimal( $product_id );

		if ( $price > 0 ) {
			return $price;
		}

		return null;
	}

	/**
	 * Returns the approximate date of the lowest price (30 days ago).
	 *
	 * @param int $product_id WooCommerce product ID.
	 *
	 * @return string|null Date in 'Y-m-d' format or null if price not available.
	 */
	public function get_lowest_price_date( int $product_id ): ?string {
		if ( null === $this->get_lowest_price( $product_id ) ) {
			return null;
		}

		$timestamp = time() - ( DAY_IN_SECONDS * $this->get_lowest_price_days_ago( $product_id ) );

		return gmdate( 'Y-m-d', $timestamp );
	}

	/**
	 * Returns the number of days since the lowest price date.
	 *
	 * @param int $product_id WooCommerce product ID.
	 *
	 * @return int|null Number of days or null if price not available.
	 */
	public function get_lowest_price_days_ago( int $product_id ): ?int {
		if ( null === $this->get_lowest_price( $product_id ) ) {
			return null;
		}

		return 30;
	}
}
