<?php
/**
 * Order meta datetime helpers (display-only). Backend values are treated as UTC instants.
 *
 * @package BWDK
 */

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

if ( ! function_exists( 'dx_parse_order_meta_datetime_utc_to_timestamp' ) ) {
	/**
	 * Parse stored meta datetime to Unix timestamp. ISO-8601 strings are parsed in UTC.
	 *
	 * @param string $raw Raw meta value (Unix string, ISO-8601 with optional Z/offset, etc.).
	 * @return int|null Unix timestamp or null if not parseable.
	 */
	function dx_parse_order_meta_datetime_utc_to_timestamp( string $raw ): ?int {
		$raw = trim( str_replace( "\xE2\x88\x92", '-', $raw ) );
		if ( strncmp( $raw, "\xEF\xBB\xBF", 3 ) === 0 ) {
			$raw = substr( $raw, 3 );
		}
		if ( $raw === '' ) {
			return null;
		}
		if ( ctype_digit( $raw ) ) {
			$n = (int) $raw;
			return $n === 0 ? null : $n;
		}

		$utc = new \DateTimeZone( 'UTC' );

		try {
			return ( new \DateTimeImmutable( $raw, $utc ) )->getTimestamp();
		} catch ( \Throwable $e ) {
			// Fractional seconds or odd spacing: normalize once.
			$stripped = $raw;
			if ( strpos( $stripped, '.' ) !== false ) {
				$stripped = (string) preg_replace( '/\.\d+/', '', $stripped, 1 );
			}
			try {
				return ( new \DateTimeImmutable( $stripped, $utc ) )->getTimestamp();
			} catch ( \Throwable $e2 ) {
				return null;
			}
		}
	}
}

if ( ! function_exists( 'dx_format_jalali_datetime' ) ) {
	/**
	 * Format a single instant for admin UI — same path as history after normalization: timestamp → bwdk_dx_format_datetime_for_ui().
	 *
	 * Accepts int timestamp or numeric string (Unix). Non-numeric strings are parsed via
	 * dx_parse_order_meta_datetime_utc_to_timestamp() then formatted; no direct string formatting and no date()/gmdate().
	 *
	 * @param mixed $value Unix timestamp (int|string digits) or parseable UTC datetime string.
	 * @return string Formatted datetime or '-'.
	 */
	function dx_format_jalali_datetime( $value ): string {
		if ( $value === null || $value === '' ) {
			return '-';
		}

		if ( is_numeric( $value ) ) {
			$ts = (int) $value;
			if ( $ts === 0 ) {
				return '-';
			}
			return function_exists( 'bwdk_dx_format_datetime_for_ui' )
				? bwdk_dx_format_datetime_for_ui( $ts )
				: '-';
		}

		$ts = dx_parse_order_meta_datetime_utc_to_timestamp( trim( (string) $value ) );
		if ( $ts === null ) {
			return '-';
		}

		return function_exists( 'bwdk_dx_format_datetime_for_ui' )
			? bwdk_dx_format_datetime_for_ui( $ts )
			: '-';
	}
}
