<?php
/**
 * Date parsing and display helpers.
 *
 * @package TradeSchoolManager
 */

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

class TSM_Date_Utils {

	public static function normalize( $value ) {
		$value = trim( sanitize_text_field( (string) $value ) );
		if ( '' === $value ) { return ''; }

		if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $value ) ) {
			$dt = DateTime::createFromFormat( '!Y-m-d', $value );
			return $dt && $dt->format( 'Y-m-d' ) === $value ? $value : '';
		}

		$formats = array( '!n/j/Y', '!m/d/Y', '!n-j-Y', '!m-d-Y', '!n/j/y', '!m/d/y', '!n-j-y', '!m-d-y' );
		foreach ( $formats as $format ) {
			$dt = DateTime::createFromFormat( $format, $value );
			if ( $dt instanceof DateTime ) {
				return $dt->format( 'Y-m-d' );
			}
		}

		$timestamp = strtotime( $value );
		return $timestamp ? gmdate( 'Y-m-d', $timestamp ) : '';
	}

	public static function display( $value, $empty = ' - ' ) {
		$value = self::normalize( $value );
		if ( '' === $value ) { return $empty; }
		$dt = DateTime::createFromFormat( '!Y-m-d', $value );
		return $dt ? $dt->format( 'm/d/Y' ) : $empty;
	}

	public static function csv( $value ) {
		return self::display( $value, '' );
	}
}
