<?php
/**
 * Prepares response payload for the PromoTimeWidget main view endpoint.
 *
 * @package Ilabs\Firevert\Modules\PromoTimeWidget\Api
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\PromoTimeWidget\Api;

use Ilabs\Firevert\Core\Services\Helper\Integration\LanguageHelper;
use Ilabs\Firevert\Modules\PromoTimeWidget\Services\Helper\PromoTimeTextPreparer;
use Ilabs\Firevert\Modules\PromoTimeWidget\Services\Type\PositionType;
use WP_Post;

/**
 * Class ResponsePreparer
 *
 * Generates the structured data payload returned by the
 * /firevert/v1/promo-time-widget/main endpoint.
 */
class ResponsePreparer {
	/**
	 * Prepares the final frontend payload based on the widget data.
	 *
	 * @param int|null $product_id The product ID to check.
	 * @param WP_Post  $post Widget post instance.
	 * @param array    $data PromoTimeWidget data.
	 *
	 * @return array<string, mixed> Final response data structure for frontend rendering.
	 */
	public static function prepare_main_response( ?int $product_id, WP_Post $post, array $data ): array {
		$start_at = $data['firevert_promo_time_widget_display_start'] ?? '';
		$end_at   = $data['firevert_promo_time_widget_display_end'] ?? '';

		return array(
			'el'     => '#promo-time-widget-' . $post->ID,
			'locale' => LanguageHelper::get_active_region_code(),
			'config' => array(
				'couponCode'          => $data['firevert_promo_time_widget_coupon'] ?? '',
				'visibleForAdminOnly' => $data['firevert_promo_time_widget_visible_admin_only'] ?? false,
				'isAdmin'             => current_user_can( 'manage_options' ),
				'position'            => $data['firevert_promo_time_widget_display_position']
										?? PositionType::AFTER_ADD_TO_CART_BUTTON,
				'showCounter'         => $data['firevert_promo_time_widget_display_counter'] ?? true,
				'startAt'             => $start_at,
				'endAt'               => $end_at,
				'dayText'             => PromoTimeTextPreparer::get_day_label_from_range( $start_at, $end_at ),
				'promotionEndText'    => __( 'until the end of the promotion', 'firevert' ),
				'text'                => $data['firevert_promo_time_widget_text'] ?? '',
				'copyText'            => __( 'Copy code', 'firevert' ),
			),
			'theme'  => array(
				'backgroundColor'   => $data['firevert_promo_time_widget_background'] ?? '#ffffff',
				'accentColor'       => $data['firevert_promo_time_widget_accent_color'] ?? '#9900ff',
				'textColor'         => $data['firevert_promo_time_widget_primary_text'] ?? '#000000',
				'counterBackground' => $data['firevert_promo_time_widget_counter_background'] ?? '#000000',
				'counterText'       => $data['firevert_promo_time_widget_counter_text'] ?? '#ffffff',
				'shadow'            => $data['firevert_promo_time_widget_add_shadow'] ?? false,
				'borderRadius'      => $data['firevert_promo_time_widget_border_radius'] ?? '0',
			),
			'state'  => array(
				'productId' => $product_id,
			),
		);
	}
}
