<?php
/**
 * Postmeta track date initializer.
 *
 * @package Ealab\Deployer
 */

namespace EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\ItemTracker\TrackDateInitializer;

use DateTime;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\ItemTracker\ItemTrackerBase;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\SqlChangesTracker;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\Database;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\Date;

/**
 * Postmeta track date initializer.
 */
class PostmetaTrackDateInitializer extends TrackDateInitializerBase {
	/**
	 * {@inheritDoc}
	 */
	public static function getId(): string {
		return 'postmeta';
	}

	/**
	 * {@inheritDoc}
	 */
	public function getInitialTrackDate( ItemTrackerBase $item_tracker, $local_id ): DateTime {
		// Use the special tracking database handle for safety.
		$db = Database::getTrackingDatabaseHandle();

		// We use the related post as the date source.
		$prepared = $db->prepare(
			'SELECT %i.`post_modified_gmt` FROM %i LEFT JOIN %i ON %i.`post_id` = %i.`ID` WHERE %i.`meta_id` = %s;' . SqlChangesTracker::IGNORE_TRACKING,
			array(
				$db->prefix . 'posts',
				$db->prefix . 'posts',
				$db->prefix . 'postmeta',
				$db->prefix . 'postmeta',
				$db->prefix . 'posts',
				$db->prefix . 'postmeta',
				$local_id,
			)
		);

		$date = $db->get_var( $prepared );

		// post_modified_gmt does not have the milliseconds part.
		$final_date = ! empty( $date )
			? Date::toDateTimeWithFormat( 'Y-m-d H:i:s', $date, Date::getUtcTimeZone() )
			: null;

		if ( empty( $final_date ) ) {
			// Use the base implementation as fallback.
			return TrackDateInitializerBase::getInitialTrackDate( $item_tracker, $local_id );
		}

		return $final_date;
	}
}
