<?php

namespace NixfilePlugin\Helper;

use Morilog\Jalali\Jalalian;
use NixfilePlugin\Plugin;

class Jalali {

	public static function register() {
		$options = Plugin::getOptions();

		if ( ! isset( $options['jalali_dates'] ) || $options['jalali_dates'] != 1 ) {
			return;
		}

		add_filter( 'date_i18n', [ self::class, 'filterDateI18n' ], 10, 4 );
		add_filter( 'get_the_date', [ self::class, 'filterDate' ], 10, 3 );
		add_filter( 'get_the_time', [ self::class, 'filterDate' ], 10, 3 );
		add_filter( 'get_comment_date', [ self::class, 'filterDate' ], 10, 3 );
		add_filter( 'get_comment_time', [ self::class, 'filterDate' ], 10, 3 );
		add_filter( 'get_post_time', [ self::class, 'filterDate' ], 10, 3 );
	}

	public static function formatTimestamp( $timestamp, $format = 'Y/m/d H:i' ): string {
		if ( ! $timestamp ) {
			return '';
		}

		return Jalalian::fromDateTime( $timestamp )->format( $format );
	}

	/**
	 * Convert Gregorian date string → Jalali
	 */
	public static function formatDateString( $dateString, $format = 'Y/m/d H:i' ) {
		if ( empty( $dateString ) ) {
			return $dateString;
		}
		$persian_months = [
			'ژانویه' => 'January',
			'فوریه' => 'February',
			'مارس' => 'March',
			'آوریل' => 'April',
			'مه' => 'May',
			'می' => 'May',
			'ژوئن' => 'June',
			'ژوئیه' => 'July',
			'جولای' => 'July',
			'اوت' => 'August',
			'سپتامبر' => 'September',
			'اکتبر' => 'October',
			'نوامبر' => 'November',
			'دسامبر' => 'December',
		];

		foreach ($persian_months as $fa => $en) {
			if ( str_contains( $dateString, $fa ) ) {
				$dateString = str_replace($fa, $en, $dateString);
				break;
			}
		}
		$timestamp = strtotime( $dateString );

		if ( ! $timestamp ) {
			return $dateString;
		}

		return self::formatTimestamp( $timestamp, $format );
	}

	public static function filterDate( $date, $format = '', $post = null ) {
		return Jalali::formatDateString( $date, get_option( 'date_format' ) );
	}

	public static function filterDateI18n( $date, $format, $timestamp, $gmt ): string {
		return Jalali::formatTimestamp( $timestamp, $format );
	}

}