<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Sifency_Addons_Rollback
 * Handles version tracking and rollback functionality.
 */
class Sifency_Addons_Rollback {

	private static $_instance = null;

	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self(); }
		return self::$_instance;
	}

	public function __construct() {
		add_action( 'wp_ajax_sifency_rollback_version', array( $this, 'ajax_rollback_version' ) );
		add_action( 'admin_init', array( $this, 'track_version_update' ) );
	}

	/**
	 * Records version history
	 */
	public function track_version_update() {
		$current_version = defined( 'SIFENCY_ADDONS_VERSION' ) ? SIFENCY_ADDONS_VERSION : '1.0.0';

		$version_history = get_option( 'sifency_addons_version_history', array() );
		if ( ! is_array( $version_history ) ) {
			$version_history = array(); }

		$version_exists = false;
		foreach ( $version_history as $entry ) {
			if ( isset( $entry['version'] ) && $entry['version'] === $current_version ) {
				$version_exists = true;
				break;
			}
		}

		if ( ! $version_exists ) {
			$version_history[] = array(
				'version'   => $current_version,
				'date'      => current_time( 'mysql' ),
				'timestamp' => time(),
			);

			if ( count( $version_history ) > 20 ) {
				$version_history = array_slice( $version_history, -20 );
			}

			update_option( 'sifency_addons_version_history', $version_history );
		}
	}

	/**
	 * AJAX: Process Rollback
	 */
	public function ajax_rollback_version() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';

		if ( ! $nonce ) {
			wp_send_json_error( array( 'message' => 'Missing nonce.' ), 400 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Permission denied.' ), 403 );
		}

		$version = isset( $_POST['version'] ) ? sanitize_text_field( wp_unslash( $_POST['version'] ) ) : '';

		if ( ! wp_verify_nonce( $nonce, 'sifency_rollback_' . $version ) ) {
			 wp_send_json_error( array( 'message' => 'Nonce validation failed.' ), 400 );
		}

		$rollback_history = get_option( 'sifency_addons_rollback_history', array() );
		if ( ! is_array( $rollback_history ) ) {
			$rollback_history = array(); }

		$rollback_history[] = array(
			'from_version' => defined( 'SIFENCY_ADDONS_VERSION' ) ? SIFENCY_ADDONS_VERSION : '',
			'to_version'   => $version,
			'timestamp'    => current_time( 'mysql' ),
			'user_id'      => get_current_user_id(),
		);

		update_option( 'sifency_addons_rollback_history', $rollback_history );

		wp_send_json_success(
			array(
				'message' => sprintf( /* translators: Rollback to version initiated */ esc_html__( 'Rollback to version %s initiated.', 'sifency-addons' ), esc_html( $version ) ),
				'version' => $version,
			)
		);
	}

	/**
	 * Render the HTML Tab
	 */
	public function render_tab() {
		$current_version = defined( 'SIFENCY_ADDONS_VERSION' ) ? SIFENCY_ADDONS_VERSION : '1.0.0';
		$version_history = get_option( 'sifency_addons_version_history', array() );

		if ( empty( $version_history ) ) {
			$version_history = array(
				array(
					'version' => '1.0.0',
					'date'    => '2025-01-01 10:00:00',
				),
				array(
					'version' => $current_version,
					'date'    => current_time( 'mysql' ),
				),
			);
		}
		?>
		<div class="sifency-version-rollback-container">
			<div class="sifency-current-version-info">
				<div class="version-card">
					<div class="version-label"><?php esc_html_e( 'Current Version', 'sifency-addons' ); ?></div>
					<div class="version-number"><?php echo esc_html( $current_version ); ?></div>
				</div>
			</div>

			<h3><?php esc_html_e( 'Version History', 'sifency-addons' ); ?></h3>
			<table class="widefat striped sifency-version-history-table">
				<thead>
					<tr>
						<th><?php esc_html_e( 'Version', 'sifency-addons' ); ?></th>
						<th><?php esc_html_e( 'Updated', 'sifency-addons' ); ?></th>
						<th><?php esc_html_e( 'Action', 'sifency-addons' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php
					foreach ( array_reverse( $version_history ) as $entry ) :
						$ver  = isset( $entry['version'] ) ? $entry['version'] : '';
						$date = isset( $entry['date'] ) ? $entry['date'] : '';
						?>
						<tr>
							<td><strong><?php echo esc_html( $ver ); ?></strong></td>
							<td><?php echo esc_html( $date ); ?></td>
							<td>
								<?php if ( $ver !== $current_version ) : ?>
									<button class="button button-secondary sifency-rollback-btn" 
											data-version="<?php echo esc_attr( $ver ); ?>"
											data-nonce="<?php echo esc_attr( wp_create_nonce( 'sifency_rollback_' . $ver ) ); ?>">
										<?php esc_html_e( 'Rollback', 'sifency-addons' ); ?>
									</button>
								<?php else : ?>
									<span class="badge badge-active"><?php esc_html_e( 'Current', 'sifency-addons' ); ?></span>
								<?php endif; ?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>

			<div class="sifency-rollback-info">
				<h3><?php esc_html_e( 'About Version Rollback', 'sifency-addons' ); ?></h3>
				<ul>
					<li><?php esc_html_e( 'Rolling back will restore the plugin code to a previous version', 'sifency-addons' ); ?></li>
					<li><?php esc_html_e( 'Your settings and data will not be affected', 'sifency-addons' ); ?></li>
				</ul>
			</div>
		</div>
		<?php
	}
}
