<?php
/**
 * Date/Time Helper
 *
 * Shared timezone-aware datetime conversion utilities for use across all admin
 * meta boxes that deal with date/time inputs.
 *
 * @package AmbassadorHub\Admin
 */

namespace AmbassadorHub\Admin;

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

/**
 * Timezone-aware datetime conversion helpers.
 *
 * All methods convert between the WordPress site timezone (used in HTML
 * datetime-local inputs) and UTC (used for database storage).
 */
final class DateTimeHelper {

	/**
	 * Format a GMT datetime string for use in an HTML datetime-local input.
	 *
	 * Converts the stored UTC value to the site's local timezone so the
	 * admin sees a time relative to their configured timezone.
	 *
	 * @param string $gmt_date GMT date string (Y-m-d or Y-m-d H:i:s).
	 *
	 * @return string Formatted datetime string (Y-m-d\TH:i in site-local time), or empty string on failure.
	 */
	public static function format_datetime_for_input( string $gmt_date ): string {
		if ( empty( $gmt_date ) ) {
			return '';
		}

		try {
			$date = new \DateTime( $gmt_date, new \DateTimeZone( 'UTC' ) );
			$date->setTimezone( wp_timezone() );
			return $date->format( 'Y-m-d\TH:i' );
		} catch ( \Exception $e ) {
			return '';
		}
	}

	/**
	 * Convert a datetime-local string (site-local time) to a GMT datetime string.
	 *
	 * @param string $local_datetime Local datetime string in Y-m-d\TH:i format.
	 *
	 * @return string GMT datetime string (Y-m-d H:i:s), or empty string on failure.
	 */
	public static function convert_datetime_to_gmt( string $local_datetime ): string {
		if ( empty( $local_datetime ) ) {
			return '';
		}

		try {
			$date = \DateTime::createFromFormat( 'Y-m-d\TH:i', $local_datetime, wp_timezone() );
			if ( ! $date ) {
				return '';
			}
			$date->setTimezone( new \DateTimeZone( 'UTC' ) );
			return $date->format( 'Y-m-d H:i:s' );
		} catch ( \Exception $e ) {
			return '';
		}
	}

	/**
	 * Convert a GMT datetime string to the site's local timezone.
	 *
	 * @param string $gmt_datetime GMT datetime string (Y-m-d H:i:s).
	 *
	 * @return string Local datetime string (Y-m-d H:i:s), or empty string on failure.
	 */
	public static function convert_gmt_to_local( string $gmt_datetime ): string {
		if ( empty( $gmt_datetime ) ) {
			return '';
		}

		try {
			$date = new \DateTime( $gmt_datetime, new \DateTimeZone( 'UTC' ) );
			$date->setTimezone( wp_timezone() );
			return $date->format( 'Y-m-d H:i:s' );
		} catch ( \Exception $e ) {
			return '';
		}
	}
}
