<?php
/**
 * Omnibus by iLabs provider
 *
 * @package Ilabs\Firevert\Core\Integration\Omnibus
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Integration\Omnibus;

use Ilabs\Omnibus_By_Ilabs\Lowest_Price_Cache_Post_Meta_Repository;
use Ilabs\Omnibus_By_Ilabs\Price_Model;

/**
 * Omnibus by iLabs integration provider.
 */
final class OmnibusByIlabsProvider extends AbstractOmnibusProvider {

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

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

	/**
	 * Checks if the Omnibus plugin is active.
	 *
	 * @return bool True if a plugin is active, false otherwise.
	 */
	public function is_active(): bool {
		return is_plugin_active( 'omnibus-by-ilabs/omnibus-by-ilabs.php' );
	}

	/**
	 * Retrieves the lowest price for a product (if not outdated).
	 *
	 * @param int $product_id WooCommerce product ID.
	 *
	 * @return float|null Lowest price or null if not found or outdated.
	 */
	public function get_lowest_price( int $product_id ): ?float {
		$model = $this->get_price_model( $product_id );

		return $model ? (float) $model->get_price() : null;
	}

	/**
	 * Retrieves the date of the lowest price for a product (if not outdated).
	 *
	 * @param int $product_id WooCommerce product ID.
	 *
	 * @return string|null Date in 'Y-m-d' format, or null if not found or outdated.
	 */
	public function get_lowest_price_date( int $product_id ): ?string {
		$model = $this->get_price_model( $product_id );

		return $model ? $model->get_date_time()->format( 'Y-m-d' ) : null;
	}


	/**
	 * Fetches the Price_Model object from Omnibus by iLabs if available and not outdated.
	 *
	 * @param int $product_id WooCommerce product ID.
	 *
	 * @return Price_Model|null Price_Model object or null if unavailable or outdated.
	 */
	private function get_price_model( int $product_id ): ?Price_Model {
		if (
			! class_exists( \Ilabs\Omnibus_By_Ilabs\Lowest_Price_Cache_Post_Meta_Repository::class )
			|| ! class_exists( Price_Model::class )
		) {
			return null;
		}

		$repo  = new Lowest_Price_Cache_Post_Meta_Repository();
		$model = $repo->get( $product_id );

		if ( ! $model instanceof Price_Model ) {
			return null;
		}

		if ( $repo->is_price_outdated( $model ) ) {
			return null;
		}

		return $model;
	}
}
