<?php
/**
 * Plugin Name: Auto Flush Rewrites
 * Description: Permalinks after deploy: Apache (.htaccess) and Nginx (rules in DB).
 * Version: 1.0
 */

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

/**
 * @return bool Apache — also update .htaccess; Nginx — DB rules only.
 */
function blog_auto_flush_uses_htaccess(): bool {
	$software = (string) ( $_SERVER['SERVER_SOFTWARE'] ?? '' );
	if ( $software !== '' && stripos( $software, 'apache' ) !== false ) {
		return true;
	}

	return function_exists( 'apache_get_modules' );
}

/**
 * After deploy to a new domain home_url() changes — rebuild rewrite rules
 * (same as Settings → Permalinks → Save).
 */
add_action(
	'init',
	static function (): void {
		if ( ! function_exists( 'home_url' ) || ! function_exists( 'flush_rewrite_rules' ) ) {
			return;
		}

		$currentHome = home_url( '/' );
		$stored      = get_option( 'blog_last_flushed_home', '' );

		if ( is_string( $stored ) && $stored === $currentHome ) {
			return;
		}

		global $wp_rewrite;
		if ( $wp_rewrite instanceof WP_Rewrite ) {
			$wp_rewrite->set_permalink_structure( '/%postname%/' );
		}

		flush_rewrite_rules( blog_auto_flush_uses_htaccess() );
		update_option( 'blog_last_flushed_home', $currentHome, true );
	},
	1
);
