<?php
/**
 * Abstract base class for Smart Post Show Blocks.
 *
 * @package Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/blocks/includes
 */

namespace SmartPostShow\Blocks;

use SmartPostShow\Blocks\Block_Base;
use SmartPostShow\Blocks\Helper;

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

/**
 * Post_Date_Meta block class.
 *
 * Handles rendering of post date and meta information for Smart Post Show blocks.
 *
 * @package Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/blocks/includes
 */
class Post_Date_Meta extends Block_Base {


	/**
	 * Set_block_properties
	 *
	 * @return void
	 */
	protected function set_block_properties() {
		$this->block_name     = 'post-date-meta';
		$this->scripts        = array( 'sp_smart_post_blocks_script_js' );
		$this->styles         = array( 'sp_smart_post_blocks_css', 'sp_smart_post_blocks_social_icons_style', 'sp_smart_post_blocks_google_fonts', 'sp_smart_post_blocks_style' );
		$this->editor_scripts = array( 'sp_smart_post_blocks_index_js' );
		$this->editor_styles  = array( 'sp_smart_post_blocks_editor_style' );
	}


	/**
	 * Render the block output on the frontend.
	 *
	 * @param array  $attributes Block attributes.
	 * @param string $content    Block content.
	 * @param array  $blocks     Inner blocks.
	 *
	 * @return string            Rendered HTML.
	 */
	public function render_block( $attributes, $content = '', $blocks = array() ) {
		if ( \SmartPostShow\Blocks\Helper::is_editor_page() ) {
			return $content;
		}
		$is_license_activated = $this->is_license_activated();
		if ( 'valid' !== $is_license_activated ) {
			return $is_license_activated;
		}

		// Extract attributes with defaults.
		$unique_id                  = $attributes['uniqueId'] ?? '';
		$additional_css_class       = $attributes['advancedAdditionalClass'] ?? '';
		$advanced_additional_id     = $attributes['advancedAdditionalID'] ?? '';
		$date_icon_style            = $attributes['dateIconStyle'] ?? 'classic';
		$date_time_display          = $attributes['dateTimeDisplay'] ?? 'auto-date-display';
		$enable_publish_date_prefix = $attributes['enablePublishDatePrefix'] ?? true;
		$published_prefix_label     = $attributes['publishedPrefixLabel'] ?? 'Published on';
		$enable_update_date_prefix  = $attributes['enableUpdateDatePrefix'] ?? true;
		$update_prefix_label        = $attributes['updatePrefixLabel'] ?? 'Updated on';
		$show_icon                  = $attributes['showIcon'] ?? true;
		$date_time_format           = $attributes['dateTimeFormat'] ?? 'default';
		$date_global_typography     = $attributes['dateGlobalTypography'] ?? '';
		$date_global_class          = $date_global_typography['class'] ?? '';

		$post_id            = get_the_ID();
		$publish_timestamp  = get_post_timestamp( $post_id, 'date' );
		$modified_timestamp = get_post_timestamp( $post_id, 'modified' );

		$publish_date  = gmdate( 'c', $publish_timestamp );
		$modified_date = gmdate( 'c', $modified_timestamp );

		$date_label = '';
		if ( 'auto-date-display' === $date_time_display && $publish_date !== $modified_date ) {
			if ( $enable_update_date_prefix ) {
				$date_label = $update_prefix_label;
			}
		} elseif ( $enable_publish_date_prefix ) {
			$date_label = $published_prefix_label;
		}

		$selected_date = $publish_date;
		if ( 'update-date' === $date_time_display ) {
			$selected_date = $modified_date;
		}
		if ( 'auto-date-display' === $date_time_display ) {
			if ( $publish_date === $modified_date ) {
				$selected_date = $publish_date;
			} else {
				$selected_date = $modified_date;
			}
		}

		unset(
			$attributes['dynamicCss'],
			$attributes['fontListsEditPage'],
			$attributes['fontLists']
		);

		$post_id        = get_the_ID();
		$formatted_date = $this->get_formatted_post_date( $date_time_format, $selected_date );

		$icon = Helper::get_icon_list( $date_icon_style );

		$additional_id_attr = $advanced_additional_id ? 'id="' . $advanced_additional_id . '"' : '';

		ob_start();
		?>

		<div class="sp-smart-post-date-meta-container sp-smart-post-wrapper <?php echo esc_attr( $additional_css_class ); ?>" id="<?php echo esc_attr( $unique_id ); ?>">

			<div class="sp-smart-post-date-meta-wrapper <?php echo esc_attr( $date_global_class ); ?>" <?php echo esc_attr( $additional_id_attr ); ?>>

				<?php if ( $show_icon ) : ?>
					<span class="sp-smart-post-date-meta-icon">
						<?php if ( ! empty( $icon ) ) { ?>
							<svg width="24" height="24" viewBox="<?php echo esc_attr( $icon['viewBox'] ); ?>" fill="none" xmlns="http://www.w3.org/2000/svg">
								<path d="<?php echo esc_attr( $icon['path'] ); ?>" fill="currentColor"></path>
							</svg>
						<?php } ?>
					</span>
				<?php endif; ?>

				<?php if ( 'publish-date' === $date_time_display && $enable_publish_date_prefix ) : ?>
					<span class="sp-smart-post-date-meta-prefix">
						<?php echo esc_html( $published_prefix_label ); ?>
					</span>
				<?php endif; ?>

				<?php if ( 'update-date' === $date_time_display && $enable_update_date_prefix ) : ?>
					<span class="sp-smart-post-date-meta-prefix">
						<?php echo esc_html( $update_prefix_label ); ?>
					</span>
				<?php endif; ?>

				<?php if ( 'auto-date-display' === $date_time_display && $date_label !== '' ) : ?>
					<span class="sp-smart-post-date-meta-prefix">
						<?php echo esc_html( $date_label ); ?>
					</span>
				<?php endif; ?>

				<span class="sp-smart-post-date-meta-date-time">
					<?php echo wp_kses_post( $formatted_date ); ?>
				</span>
			</div>
		</div>


		<?php
		return ob_get_clean();
	}

	/**
	 * Get the formatted post date based on the specified format.
	 *
	 * @param string $format      The format type for the date.
	 * @param string $date_to_use The date string to format.
	 * @return string             The formatted date string.
	 */
	private function get_formatted_post_date( $format, $date_to_use ) {

		$wp_date_format = get_option( 'date_format' );
		$wp_time_format = get_option( 'time_format' );

		switch ( $format ) {
			case 'publish-date':
				return date_i18n( 'M j, Y', strtotime( $date_to_use ) );

			case 'time-only':
				return date_i18n( 'g:i A', strtotime( $date_to_use ) );

			case 'full-date':
				return date_i18n( 'F j, Y', strtotime( $date_to_use ) );

			case 'date-time-short':
				return date_i18n( 'M j, Y g:i A', strtotime( $date_to_use ) );

			case 'date-time-long':
				return date_i18n( 'F j, Y g:i A', strtotime( $date_to_use ) );

			case 'day-month-year':
				return date_i18n( 'j M Y', strtotime( $date_to_use ) );

			case 'day-month-year-time':
				return date_i18n( 'j M Y g:i A', strtotime( $date_to_use ) );

			case 'time-ago':
				return $this->get_time_ago_string( $date_to_use );

			case 'wp-default-date':
				return date_i18n( $wp_date_format, strtotime( $date_to_use ) );

			case 'wp-default-datetime':
				return date_i18n( $wp_date_format . ' ' . $wp_time_format, strtotime( $date_to_use ) );

			default:
				return date_i18n( 'F j, Y', strtotime( $date_to_use ) );
		}
	}

	/**
	 * Get a human-readable "time ago" string for a given date.
	 *
	 * @param string $date_string The date string to compare.
	 * @return string             The formatted "time ago" string.
	 */
	private function get_time_ago_string( $date_string ) {
		$seconds = strtotime( 'now' ) - strtotime( $date_string );

		if ( $seconds < 0 ) {
			return 'Just now';
		}

		$intervals = array(
			'year'   => 31536000,
			'month'  => 2592000,
			'day'    => 86400,
			'hour'   => 3600,
			'minute' => 60,
		);

		foreach ( $intervals as $name => $secs ) {
			$interval = floor( $seconds / $secs );
			if ( $interval > 0 ) {
				if ( 1 === $interval ) {
					return "1 {$name} ago";
				} else {
					return "$interval {$name}s ago";
				}
			}
		}

		return 'Just now';
	}
}
