<?php
/**
 * SpectatorViewsRepository class.
 *
 * Provides access to SpectatorViews CPT instances.
 *
 * @package Ilabs\Firevert\Modules\SpectatorViews\Services\Repository
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\SpectatorViews\Services\Repository;

use Ilabs\Firevert\Core\Repository\AbstractWidgetRepository;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Form\ProductsFormHandler;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Type\ModuleType;
use WP_Post;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Form\AppearanceFormHandler;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Form\SettingsFormHandler;

/**
 * Class SpectatorViewsRepository
 */
final class SpectatorViewsRepository extends AbstractWidgetRepository {

	/**
	 * Returns the custom post type used by the widget.
	 *
	 * This defines the post_type for queries and creation.
	 *
	 * @return string Widget custom post type name.
	 */
	protected function get_post_type(): string {
		return ModuleType::MODULE_CPT;
	}

	/**
	 * Returns the default post title used when creating the widget.
	 *
	 * Used when no SpectatorViews instance exists.
	 *
	 * @return string Default title for the widget post.
	 */
	protected function get_default_post_title(): string {
		return 'Main Spectator Views';
	}

	/**
	 * Returns all widget settings and appearance data.
	 *
	 * @param WP_Post     $post SpectatorViews CPT post.
	 * @param string|null $lang Passed lang value ('pl', 'en', 'fr' format).
	 *
	 * @return array<string, mixed> Widget data array.
	 */
	public function get_widget_data( WP_Post $post, ?string $lang = null ): array {
		$settings   = new SettingsFormHandler( $post );
		$appearance = new AppearanceFormHandler( $post );
		$products   = new ProductsFormHandler( $post );

		if ( null === $lang ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$lang = sanitize_key( wp_unslash( $_GET['lang'] ?? '' ) );
			if ( '' === $lang ) {
				$lang = null;
			}
		}

		$settings_data   = $this->extract_fields( $post, $settings, $lang );
		$appearance_data = $this->extract_fields( $post, $appearance, $lang );
		$products_data   = $this->extract_fields( $post, $products, $lang );

		$image_id = (int) ( $appearance_data['firevert_spectator_views_image'] ?? 0 );

		$appearance_data['firevert_spectator_views_image_id']  = $image_id;
		$appearance_data['firevert_spectator_views_image_url'] = $image_id
			? wp_get_attachment_image_url( $image_id, 'medium' )
			: '';

		return array_merge(
			$settings_data,
			$appearance_data,
			$products_data
		);
	}

	/**
	 * Returns the display position setting for the main widget.
	 *
	 * @return string|null
	 */
	public function get_display_position(): ?string {
		$post = $this->get_or_create_main();

		$value = get_post_meta( $post->ID, 'firevert_spectator_views_display_position', true );

		return is_string( $value ) && '' !== $value ? $value : null;
	}
}
