<?php
/**
 * Date utility.
 *
 * @package EaLab\WP_Deployer
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\Date;

/**
 * Get date from a URL parameter.
 *
 * @param string $date_field_id The date field ID.
 *
 * @return DateTimeInterface|null The date or null if the date is invalid.
 */
function deploy_sync_content__get_datetime_from_url_param( string $date_field_id ): ?DateTimeInterface {
	$date_field_value = esc_attr( sanitize_text_field( wp_unslash( $_GET[ $date_field_id ] ?? '' ) ) );

	if ( empty( $date_field_value ) ) {
		return null;
	}

	if ( ! is_string( $date_field_value ) ) {
		return null;
	}

	// ISO_COMPACT is always UTC in WP_Deployer.
	$datetime = Date::toDateTimeWithFormat( Date::ISO_COMPACT, $date_field_value );

	if ( $datetime instanceof DateTimeInterface ) {
		return $datetime;
	}

	// Try with another format.
	// Expected to come from an <input> field, so this time with the WP timezone.
	return Date::toDateTime( $date_field_value, wp_timezone() );
}
