<?php

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

/**
 * Display / parse dates as dd/mm/yyyy across the plugin UI.
 * Storage and APIs stay ISO Y-m-d.
 */
final class IComm_SM_Dates {

	/** Display format for full calendar dates. */
	public const DISPLAY = 'd/m/Y';

	/** Display format for datetime. */
	public const DISPLAY_DT = 'd/m/Y H:i';

	/**
	 * Format Y-m-d (or timestamp) to dd/mm/yyyy.
	 *
	 * @param string|int|null $ymd_or_ts
	 */
	public static function format($ymd_or_ts): string {
		if ($ymd_or_ts === null || $ymd_or_ts === '') {
			return '';
		}
		if (is_int($ymd_or_ts) || (is_string($ymd_or_ts) && ctype_digit($ymd_or_ts))) {
			$ts = (int) $ymd_or_ts;
			return $ts > 0 ? wp_date(self::DISPLAY, $ts) : '';
		}
		$ymd = self::parse_to_ymd((string) $ymd_or_ts);
		if ($ymd === '') {
			return '';
		}
		$p = explode('-', $ymd);
		return sprintf('%02d/%02d/%04d', (int) $p[2], (int) $p[1], (int) $p[0]);
	}

	/**
	 * Short chart label from Y-m-d → dd/mm.
	 */
	public static function format_short(string $ymd): string {
		$ymd = self::parse_to_ymd($ymd);
		if ($ymd === '') {
			return '';
		}
		$p = explode('-', $ymd);
		return sprintf('%02d/%02d', (int) $p[2], (int) $p[1]);
	}

	/**
	 * Parse user/API date to Y-m-d. Accepts Y-m-d, dd/mm/yyyy, d/m/yyyy, dd.mm.yyyy.
	 */
	public static function parse_to_ymd(string $raw): string {
		$raw = trim($raw);
		if ($raw === '') {
			return '';
		}
		if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $raw, $m)) {
			return self::valid_ymd((int) $m[1], (int) $m[2], (int) $m[3]);
		}
		if (preg_match('/^(\d{1,2})[\/.\-](\d{1,2})[\/.\-](\d{4})$/', $raw, $m)) {
			return self::valid_ymd((int) $m[3], (int) $m[2], (int) $m[1]);
		}
		return '';
	}

	private static function valid_ymd(int $y, int $m, int $d): string {
		if ($y < 2000 || $y > 2100 || $m < 1 || $m > 12 || $d < 1 || $d > 31) {
			return '';
		}
		if (!checkdate($m, $d, $y)) {
			return '';
		}
		return sprintf('%04d-%02d-%02d', $y, $m, $d);
	}
}
