<?php
/**
 * SpectatorViews class.
 *
 * Renders the front-end view of a SpectatorViews instance.
 *
 * @package Ilabs\Firevert\Modules\SpectatorViews\Widget
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\SpectatorViews\Widget;

use Ilabs\Firevert\Core\Services\Resolver\PathResolver;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Form\ProductsFormHandler;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Form\SettingsFormHandler;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Helper\ProductVisibilityChecker;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Repository\SpectatorViewsRepository;

/**
 * Class SpectatorViews
 */
final class SpectatorViews {

	/**
	 * Repository service for retrieving widget data.
	 *
	 * @var SpectatorViewsRepository
	 */
	private SpectatorViewsRepository $repository;

	/**
	 * PathResolver service for resolving view paths.
	 *
	 * @var PathResolver
	 */
	private PathResolver $path_resolver;

	/**
	 * Constructor.
	 *
	 * @param SpectatorViewsRepository $repository Repository instance.
	 * @param PathResolver             $path_resolver PathResolver instance.
	 */
	public function __construct(
		SpectatorViewsRepository $repository,
		PathResolver $path_resolver
	) {
		$this->repository    = $repository;
		$this->path_resolver = $path_resolver;
	}

	/**
	 * Renders the widget HTML for a given SpectatorViews post.
	 *
	 * @return string The rendered HTML.
	 */
	public function render(): string {
		$post = $this->repository->get_or_create_main();

		$settings_handler = new SettingsFormHandler( $post );
		$products_handler = new ProductsFormHandler( $post );
		$settings         = $settings_handler->get_data();
		$products         = $products_handler->get_data();

		if (
			! empty( $settings['firevert_spectator_views_visible_admin_only'] )
			&& ! current_user_can( 'manage_options' )
		) {
			return '<!-- SpectatorViews visible only for admin -->';
		}

		$product_id = get_the_ID();
		$checker    = new ProductVisibilityChecker( $product_id, $products );

		if ( ! $checker->should_display() ) {
			return '<!-- SpectatorViews hidden: targeting rules -->';
		}

		$view_path = $this->path_resolver->get_module_view_path(
			'SpectatorViews',
			'widget-placeholder.view.php'
		);

		if ( ! file_exists( $view_path ) ) {
			return '<!-- SpectatorViews view not found -->';
		}

		ob_start();
		include $view_path;
		return (string) ob_get_clean();
	}

	/**
	 * Returns the widget display position setting.
	 *
	 * @return string|null
	 */
	public function get_display_position(): ?string {
		return $this->repository->get_display_position();
	}
}
