<?php
/**
 * Post 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;

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

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

		$prepared = $db->prepare(
			'SELECT `post_modified_gmt` FROM %i WHERE `ID` = %s;' . SqlChangesTracker::IGNORE_TRACKING,
			array(
				$db->prefix . 'posts',
				$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;
	}
}
