<?php

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

class AIEO_SEO_Slug_Monitor {

	
	private static $old = array();

	public static function register() {
		add_action( 'pre_post_update', array( __CLASS__, 'capture' ), 10, 1 );
		add_action( 'post_updated', array( __CLASS__, 'maybe_create' ), 10, 3 );
	}

	
	public static function capture( $post_id ) {
		$post_id = (int) $post_id;
		$post    = get_post( $post_id );
		if ( ! $post instanceof WP_Post || 'publish' !== $post->post_status ) {
			return; 
		}
		if ( ! self::eligible( $post->post_type ) ) {
			return;
		}
		self::$old[ $post_id ] = self::path_of( get_permalink( $post_id ) );
	}

	
	public static function maybe_create( $post_id, $post_after, $post_before ) {
		$post_id = (int) $post_id;
		if ( ! isset( self::$old[ $post_id ] ) ) {
			return;
		}
		$old_path = self::$old[ $post_id ];
		unset( self::$old[ $post_id ] );

		if ( ! $post_after instanceof WP_Post || 'publish' !== $post_after->post_status || ! self::eligible( $post_after->post_type ) ) {
			return;
		}
		
		clean_post_cache( $post_id );
		$new_path = self::path_of( get_permalink( $post_id ) );

		if ( '' === $old_path || '' === $new_path || $old_path === $new_path ) {
			return; 
		}
		if ( class_exists( 'AIEO_SEO_Redirects' ) ) {
			$added = AIEO_SEO_Redirects::add( $old_path, $new_path, 301, array( 'source' => 'slug' ) );
			if ( ! $added && method_exists( 'AIEO_SEO_Redirects', 'delete_by_source' ) ) {
				
				
				
				AIEO_SEO_Redirects::delete_by_source( $new_path );
				$added = AIEO_SEO_Redirects::add( $old_path, $new_path, 301, array( 'source' => 'slug' ) );
			}
			if ( $added ) {
				
				
				
				
				AIEO_SEO_Redirects::repoint_targets( $old_path, $new_path );
			}
		}
	}

	private static function eligible( $post_type ) {
		
		
		
		$post_type = (string) $post_type;
		if ( in_array( $post_type, array( 'attachment', 'revision', 'nav_menu_item' ), true ) ) {
			return false;
		}
		$pto = get_post_type_object( $post_type );
		return $pto && ! empty( $pto->public );
	}

	private static function path_of( $url ) {
		return class_exists( 'AIEO_SEO_Redirects' ) ? AIEO_SEO_Redirects::normalize_path( (string) $url ) : '';
	}
}
