<?php

namespace MediaRenameManager;

use WP_PowerSuite\Core\AbstractModule;

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

class Module extends AbstractModule {

	private const MODULE_ID      = 'media-rename-manager';
	private const MODULE_VERSION = '1.0.0';

	private ?array $settings_cache = null;

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Media Rename Manager', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Rename existing media files in your library with full control. Update SEO-unfriendly camera names, bulk rename product images, and automatically update all references throughout your site.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin', 'ajax', 'rest' ];
	}

	private function isLicenseActive(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

	protected function registerHooks(): void {
		if ( ! $this->isLicenseActive() ) {
			return;
		}

		add_filter( 'wp_handle_upload_prefilter', [ $this, 'renameUploadedFile' ] );
		add_action( 'add_meta_boxes_attachment', [ $this, 'addRenameMetaBox' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueueAssets' ] );
		add_action( 'load-upload.php', [ $this, 'registerUploadPageHooks' ] );

		if ( is_admin() || wp_doing_ajax() ) {
			add_filter( 'attachment_fields_to_edit', [ $this, 'addRenameFieldToAttachmentModal' ], 10, 2 );
		}

		add_action( 'wp_ajax_wpps_media_rename_rename', [ $this, 'ajaxRename' ] );
		add_action( 'wp_ajax_wpps_media_rename_scan', [ $this, 'ajaxScanReferences' ] );
		add_action( 'wp_ajax_wpps_media_rename_bulk', [ $this, 'ajaxBulkRename' ] );
		add_action( 'wp_ajax_wpps_media_rename_panel', [ $this, 'ajaxRenamePanel' ] );
	}

	public function registerUploadPageHooks(): void {
		if ( ! current_user_can( 'upload_files' ) ) {
			return;
		}

		add_filter( 'bulk_actions-upload', [ $this, 'addBulkRenameAction' ] );
		add_filter( 'handle_bulk_actions-upload', [ $this, 'handleBulkRenameAction' ], 10, 3 );

		if ( ! isset( $_GET['wpps_bulk_rename'], $_GET['media'] ) ) {
			return;
		}

		add_action( 'admin_notices', [ $this, 'bulkRenameNotice' ] );
		add_action( 'admin_footer-upload.php', [ $this, 'outputBulkRenameModal' ] );
	}

	private function getSettings(): array {
		if ( $this->settings_cache !== null ) {
			return $this->settings_cache;
		}

		$saved    = $this->moduleSettings()->all( [] );
		$defaults = [
			'default_pattern'      => '{title}',
			'case_transformation'  => 'lowercase',
			'max_filename_length'  => 50,
			'excluded_file_types'  => '',
			'add_unique_id_suffix' => false,
			'create_redirects'     => false,
			'preserve_accents'     => false,
		];

		$this->settings_cache = self::sanitizeSettings(
			array_merge( $defaults, is_array( $saved ) ? $saved : [] )
		);
		return $this->settings_cache;
	}

	public static function sanitizeSettings( array $settings ): array {
		$allowed_case = [ 'lowercase', 'uppercase', 'titlecase', 'nochange' ];
		$case         = isset( $settings['case_transformation'] ) ? (string) $settings['case_transformation'] : 'lowercase';

		return [
			'default_pattern'      => isset( $settings['default_pattern'] ) ? sanitize_text_field( (string) $settings['default_pattern'] ) : '{title}',
			'case_transformation'  => in_array( $case, $allowed_case, true ) ? $case : 'lowercase',
			'max_filename_length'  => max( 10, min( 200, (int) ( $settings['max_filename_length'] ?? 50 ) ) ),
			'excluded_file_types'  => isset( $settings['excluded_file_types'] ) ? sanitize_text_field( (string) $settings['excluded_file_types'] ) : '',
			'add_unique_id_suffix' => self::settingEnabled( $settings, 'add_unique_id_suffix' ),
			'preserve_accents'     => self::settingEnabled( $settings, 'preserve_accents' ),
			'create_redirects'       => \WP_PowerSuite\Core\OptionStoreModuleSettingsRepository::isModuleEnabled( 'redirect-manager' )
				&& self::settingEnabled( $settings, 'create_redirects' ),
		];
	}

	public function renameUploadedFile( array $file ): array {
		if ( isset( $file['error'] ) && UPLOAD_ERR_OK !== (int) $file['error'] ) {
			return $file;
		}

		$original = basename( str_replace( "\0", '', (string) ( $file['name'] ?? '' ) ) );
		if ( $original === '' ) {
			return $file;
		}

		$ext = strtolower( pathinfo( $original, PATHINFO_EXTENSION ) );
		if ( $this->isExcludedExtension( $ext ) ) {
			return $file;
		}

		$base = pathinfo( $original, PATHINFO_FILENAME );
		$base = $this->slugify( (string) $base ) ?: 'file';
		$new_name = $this->formatFilename( $base, $ext );

		if ( $new_name !== '' && $new_name !== $original ) {
			$file['name'] = $new_name;
		}

		return $file;
	}

	public function addRenameMetaBox(): void {
		if ( ! current_user_can( 'upload_files' ) ) {
			return;
		}

		$post = get_post();
		if ( ! $post || $post->post_type !== 'attachment' || ! current_user_can( 'edit_post', $post->ID ) ) {
			return;
		}

		add_meta_box(
			'wpps-media-rename',
			__( 'Rename File', 'wp-powersuite' ),
			[ $this, 'renderRenameMetaBox' ],
			'attachment',
			'side'
		);
	}

	public function renderRenameMetaBox( \WP_Post $post ): void {
		$this->renderRenamePanel( $post );
	}

	public function addRenameFieldToAttachmentModal( array $form_fields, \WP_Post $post ): array {
		if ( ! $this->canRenameAttachment( $post->ID ) ) {
			return $form_fields;
		}

		ob_start();
		$this->renderRenamePanel( $post );
		$html = ob_get_clean();
		if ( ! is_string( $html ) || $html === '' ) {
			return $form_fields;
		}

		$form_fields['wpps_media_rename'] = [
			'label' => __( 'Rename File', 'wp-powersuite' ),
			'input' => 'html',
			'html'  => $html,
		];

		return $form_fields;
	}

	private function renderRenamePanel( \WP_Post $post ): void {
		$file = get_attached_file( $post->ID, true );
		if ( ! $file || ! is_file( $file ) ) {
			echo '<p>' . esc_html__( 'No file found.', 'wp-powersuite' ) . '</p>';
			return;
		}

		$current      = basename( $file );
		$default_name = $this->getDefaultRename( $post, $current );
		include __DIR__ . '/views/rename-meta-box.php';
	}

	private function getDefaultRename( \WP_Post $post, string $current_basename ): string {
		$base = $post->post_title ?? '';
		if ( trim( $base ) === '' ) {
			$base = pathinfo( $current_basename, PATHINFO_FILENAME );
		}
		return $this->slugify( $base ) ?: 'image';
	}

	public function addBulkRenameAction( array $actions ): array {
		$actions['wpps_rename_files'] = __( 'Rename Files', 'wp-powersuite' );
		return $actions;
	}

	public function handleBulkRenameAction( string $redirect, string $action, array $post_ids ): string {
		if ( $action !== 'wpps_rename_files' || empty( $post_ids ) ) {
			return $redirect;
		}

		$editable = array_values( array_filter( array_map( 'absint', $post_ids ), [ $this, 'canRenameAttachment' ] ) );
		if ( empty( $editable ) ) {
			return $redirect;
		}

		return add_query_arg(
			[
				'wpps_bulk_rename' => '1',
				'media'            => implode( ',', $editable ),
				'mode'             => 'list',
			],
			admin_url( 'upload.php' )
		);
	}

	public function bulkRenameNotice(): void {
		$ids = $this->getBulkRenameIdsFromRequest();
		if ( empty( $ids ) ) {
			return;
		}

		$count = count( $ids );
		?>
		<div class="notice notice-info wpps-bulk-rename-notice">
			<p>
				<?php
				printf(
					esc_html( _n( '%d file selected for renaming. Open the bulk rename modal below.', '%d files selected for renaming. Open the bulk rename modal below.', $count, 'wp-powersuite' ) ),
					$count
				);
				?>
			</p>
			<p>
				<button type="button" class="button button-primary"><?php esc_html_e( 'Open Bulk Rename Modal', 'wp-powersuite' ); ?></button>
			</p>
		</div>
		<?php
	}

	public function outputBulkRenameModal(): void {
		$ids = $this->getBulkRenameIdsFromRequest();
		if ( empty( $ids ) ) {
			return;
		}

		$settings = $this->getSettings();
		include __DIR__ . '/views/bulk-rename-modal.php';
	}

	public function enqueueAssets(): void {
		if ( ! current_user_can( 'upload_files' ) ) {
			return;
		}

		global $pagenow;

		if ( $pagenow === 'post.php' && ! empty( $_GET['post'] ) ) {
			$post_id = absint( $_GET['post'] );
			if ( get_post_type( $post_id ) === 'attachment' && current_user_can( 'edit_post', $post_id ) ) {
				$this->enqueueRenameAssets();
			}
			return;
		}

		if ( $pagenow === 'upload.php' ) {
			$this->enqueueRenameAssets();
		}
	}

	private function enqueueRenameAssets(): void {
		global $pagenow;

		$base = WP_POWERSUITE_PLUGIN_URL . 'modules/' . self::MODULE_ID . '/assets/';
		wp_enqueue_style( 'wp-powersuite-media-rename', $base . 'media-rename.css', [], self::MODULE_VERSION );
		wp_enqueue_script(
			'wp-powersuite-media-rename',
			$base . 'media-rename.js',
			$pagenow === 'upload.php' ? [ 'jquery', 'media' ] : [ 'jquery' ],
			self::MODULE_VERSION,
			true
		);
		wp_localize_script(
			'wp-powersuite-media-rename',
			'wppsMediaRename',
			[
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'wpps_media_rename' ),
				'strings' => [
					'error'           => __( 'An error occurred.', 'wp-powersuite' ),
					'emptyFilename'   => __( 'Please enter a new filename.', 'wp-powersuite' ),
					'bulkComplete'    => __( 'Complete', 'wp-powersuite' ),
					'bulkSkipped'     => __( 'Skipped', 'wp-powersuite' ),
					'bulkFailed'      => __( 'Failed', 'wp-powersuite' ),
					'bulkSuccess'     => __( 'Success', 'wp-powersuite' ),
					'featuredIn'      => __( 'Featured image in', 'wp-powersuite' ),
					'postCount'       => __( '%d post', 'wp-powersuite' ),
					'postsCount'      => __( '%d posts', 'wp-powersuite' ),
					'postsInContent'  => __( 'Posts (in content)', 'wp-powersuite' ),
					'meta'            => __( 'Meta', 'wp-powersuite' ),
					'options'         => __( 'Options', 'wp-powersuite' ),
					'noReferences'    => __( 'No references found.', 'wp-powersuite' ),
					'dismiss'         => __( 'Dismiss', 'wp-powersuite' ),
					'noFilesSelected' => __( 'No files selected.', 'wp-powersuite' ),
				'renamedTo'       => __( 'Renamed to: %s', 'wp-powersuite' ),
				'renameLabel'     => __( 'Rename File', 'wp-powersuite' ),
				'loading'         => __( 'Loading…', 'wp-powersuite' ),
			],
			]
		);
	}

	public function ajaxRename(): void {
		$this->verifyAjaxNonce();

		$attachment_id = isset( $_POST['attachment_id'] ) ? absint( $_POST['attachment_id'] ) : 0;
		$new_name      = isset( $_POST['new_name'] ) ? sanitize_file_name( wp_unslash( (string) $_POST['new_name'] ) ) : '';
		$update_title  = ! empty( $_POST['update_title'] );

		if ( ! $this->canRenameAttachment( $attachment_id ) || $new_name === '' ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}

		$result = $this->renameAttachment( $attachment_id, $new_name, $update_title );
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		wp_send_json_success( $result );
	}

	public function ajaxScanReferences(): void {
		$this->verifyAjaxNonce();

		$attachment_id = isset( $_POST['attachment_id'] ) ? absint( $_POST['attachment_id'] ) : 0;
		if ( ! $this->canRenameAttachment( $attachment_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}

		wp_send_json_success( $this->scanReferences( $attachment_id ) );
	}

	public function ajaxRenamePanel(): void {
		$this->verifyAjaxNonce();

		$attachment_id = isset( $_POST['attachment_id'] ) ? absint( $_POST['attachment_id'] ) : 0;
		if ( ! $this->canRenameAttachment( $attachment_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}

		$post = get_post( $attachment_id );
		if ( ! $post instanceof \WP_Post ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}

		ob_start();
		$this->renderRenamePanel( $post );
		$html = ob_get_clean();

		wp_send_json_success(
			[
				'html' => is_string( $html ) ? $html : '',
			]
		);
	}

	public function ajaxBulkRename(): void {
		$this->verifyAjaxNonce();

		$ids          = isset( $_POST['ids'] ) && is_array( $_POST['ids'] ) ? array_map( 'absint', $_POST['ids'] ) : [];
		$pattern      = isset( $_POST['pattern'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['pattern'] ) ) : '';
		$prefix       = isset( $_POST['prefix'] ) ? sanitize_file_name( wp_unslash( (string) $_POST['prefix'] ) ) : '';
		$suffix       = isset( $_POST['suffix'] ) ? sanitize_file_name( wp_unslash( (string) $_POST['suffix'] ) ) : '';
		$update_title = ! empty( $_POST['update_title'] );
		$counter      = isset( $_POST['counter'] ) ? max( 1, absint( $_POST['counter'] ) ) : 1;

		$ids = array_values( array_filter( $ids ) );
		if ( empty( $ids ) ) {
			wp_send_json_error( [ 'message' => __( 'No files selected.', 'wp-powersuite' ) ] );
		}

		$settings = $this->getSettings();
		$pattern  = $pattern !== '' ? $pattern : (string) ( $settings['default_pattern'] ?? '{title}' );
		$results  = [];

		foreach ( $ids as $id ) {
			if ( ! $this->canRenameAttachment( $id ) ) {
				$results[] = [
					'id'      => $id,
					'success' => false,
					'message' => __( 'Permission denied.', 'wp-powersuite' ),
				];
				continue;
			}

			$new_name = sanitize_file_name( $prefix . $this->resolvePattern( $pattern, $id, $counter ) . $suffix );
			$result   = $this->renameAttachment( $id, $new_name, $update_title );

			if ( is_wp_error( $result ) ) {
				$results[] = [
					'id'      => $id,
					'success' => false,
					'message' => $result->get_error_message(),
				];
			} else {
				$results[] = [
					'id'       => $id,
					'success'  => true,
					'new_name' => $result['new_name'] ?? '',
				];
			}

			++$counter;
		}

		wp_send_json_success(
			[
				'results' => $results,
				'counter' => $counter,
			]
		);
	}

	private function verifyAjaxNonce(): void {
		if ( ! check_ajax_referer( 'wpps_media_rename', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid security token.', 'wp-powersuite' ) ] );
		}

		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}
	}

	private function canRenameAttachment( int $attachment_id ): bool {
		return $attachment_id > 0
			&& get_post_type( $attachment_id ) === 'attachment'
			&& current_user_can( 'edit_post', $attachment_id );
	}

	private function getBulkRenameIdsFromRequest(): array {
		if ( ! current_user_can( 'upload_files' ) || ! isset( $_GET['media'] ) ) {
			return [];
		}

		$raw = sanitize_text_field( wp_unslash( (string) $_GET['media'] ) );
		$ids = array_values( array_filter( array_map( 'absint', explode( ',', $raw ) ) ) );

		return array_values( array_filter( $ids, [ $this, 'canRenameAttachment' ] ) );
	}

	public function renameAttachment( int $attachment_id, string $new_name, bool $update_title = false ): array|\WP_Error {
		$file = get_attached_file( $attachment_id, true );
		if ( ! $file || ! is_file( $file ) ) {
			return new \WP_Error( 'no_file', __( 'File not found.', 'wp-powersuite' ) );
		}

		$settings = $this->getSettings();
		$ext      = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );

		if ( $this->isExcludedExtension( $ext, $settings ) ) {
			return new \WP_Error( 'excluded', __( 'This file type is excluded from renaming', 'wp-powersuite' ) );
		}

		$path_info = pathinfo( $file );
		$dir       = $path_info['dirname'] ?? '';
		$old_ext   = $path_info['extension'] ?? '';

		if ( pathinfo( $new_name, PATHINFO_EXTENSION ) === '' && $old_ext !== '' ) {
			$new_name .= '.' . $old_ext;
		}
		$new_name = basename( $new_name );

		$new_base = pathinfo( $new_name, PATHINFO_FILENAME );
		$new_ext  = pathinfo( $new_name, PATHINFO_EXTENSION ) ?: $old_ext;
		$new_name = $this->formatFilename( $new_base, $new_ext, $settings );
		$new_file = $dir . DIRECTORY_SEPARATOR . $new_name;

		if ( $file === $new_file ) {
			return new \WP_Error( 'unchanged', __( 'Filename is unchanged.', 'wp-powersuite' ) );
		}
		if ( file_exists( $new_file ) ) {
			return new \WP_Error( 'exists', __( 'A file with that name already exists.', 'wp-powersuite' ) );
		}

		$old_url = wp_get_attachment_url( $attachment_id );
		if ( ! $old_url ) {
			return new \WP_Error( 'no_url', __( 'Could not get attachment URL.', 'wp-powersuite' ) );
		}

		$old_meta = wp_get_attachment_metadata( $attachment_id );

		if ( ! rename( $file, $new_file ) ) {
			return new \WP_Error( 'rename_failed', __( 'Failed to rename file on disk.', 'wp-powersuite' ) );
		}

		$upload_dir = wp_upload_dir();
		if ( ! empty( $upload_dir['error'] ) ) {
			rename( $new_file, $file );
			return new \WP_Error( 'upload_dir', __( 'Upload directory error.', 'wp-powersuite' ) );
		}

		$new_rel = ltrim( str_replace( $upload_dir['basedir'], '', $new_file ), DIRECTORY_SEPARATOR . '/' );
		$new_rel = str_replace( DIRECTORY_SEPARATOR, '/', $new_rel );

		update_post_meta( $attachment_id, '_wp_attached_file', $new_rel );

		$new_url = $upload_dir['baseurl'] . '/' . $new_rel;
		wp_update_post(
			[
				'ID'   => $attachment_id,
				'guid' => $new_url,
			]
		);

		if ( $update_title ) {
			$title_from_name = pathinfo( $new_name, PATHINFO_FILENAME );
			$title_from_name = str_replace( [ '-', '_' ], ' ', $title_from_name );
			wp_update_post(
				[
					'ID'         => $attachment_id,
					'post_title' => $title_from_name,
				]
			);
		}

		if ( is_array( $old_meta ) && ! empty( $old_meta['sizes'] ) ) {
			foreach ( $old_meta['sizes'] as $size_data ) {
				if ( empty( $size_data['file'] ) ) {
					continue;
				}
				$old_thumb = $dir . DIRECTORY_SEPARATOR . $size_data['file'];
				if ( is_file( $old_thumb ) ) {
					wp_delete_file( $old_thumb );
				}
			}
		}

		$meta = wp_generate_attachment_metadata( $attachment_id, $new_file );
		if ( ! is_wp_error( $meta ) ) {
			wp_update_attachment_metadata( $attachment_id, $meta );
		}

		$this->updateReferences( $old_url, $new_url, basename( $file ), $new_name );

		if ( ! empty( $settings['create_redirects'] ) ) {
			$this->createRedirect( $old_url, $new_url );
		}

		return [
			'new_name' => $new_name,
			'new_url'  => $new_url,
			'old_url'  => $old_url,
		];
	}

	private function resolvePattern( string $pattern, int $attachment_id, int $counter ): string {
		$post = get_post( $attachment_id );
		if ( ! $post || $post->post_type !== 'attachment' ) {
			return sanitize_file_name( $pattern );
		}

		$title = $this->slugify( (string) ( $post->post_title ?? '' ) );

		$date = '';
		if ( $post->post_date ) {
			$date = gmdate( 'Y-m-d', strtotime( $post->post_date ) );
		}

		$post_title = '';
		$parent_id  = (int) $post->post_parent;
		if ( $parent_id > 0 ) {
			$parent = get_post( $parent_id );
			if ( $parent ) {
				$post_title = $this->slugify( (string) ( $parent->post_title ?? '' ) );
			}
		}

		$result = str_replace(
			[ '{title}', '{post-title}', '{id}', '{date}', '{counter}' ],
			[
				$title ?: 'image',
				$post_title ?: 'attachment',
				(string) $attachment_id,
				$date,
				sprintf( '%03d', $counter ),
			],
			$pattern
		);

		return sanitize_file_name( $result );
	}

	private function formatFilename( string $base, string $ext, ?array $settings = null ): string {
		$settings = $settings ?? $this->getSettings();
		$base     = $this->applyCaseTransformation( $base, (string) ( $settings['case_transformation'] ?? 'lowercase' ) );

		if ( ! self::settingEnabled( $settings, 'preserve_accents' ) ) {
			$base = $this->asciify( $base );
		}

		$max_len = (int) ( $settings['max_filename_length'] ?? 50 );
		if ( $max_len > 0 && strlen( $base ) > $max_len ) {
			$base = substr( $base, 0, $max_len );
		}

		if ( self::settingEnabled( $settings, 'add_unique_id_suffix' ) ) {
			$base .= '-' . $this->generateUniqueId();
		}

		$ext = strtolower( $ext );
		return $base . ( $ext !== '' ? '.' . $ext : '' );
	}

	private function isExcludedExtension( string $ext, ?array $settings = null ): bool {
		$ext = strtolower( $ext );
		if ( $ext === '' ) {
			return false;
		}

		$settings = $settings ?? $this->getSettings();
		$excluded = array_filter(
			array_map(
				'trim',
				array_map( 'strtolower', explode( ',', (string) ( $settings['excluded_file_types'] ?? '' ) ) )
			)
		);

		return $excluded !== [] && in_array( $ext, $excluded, true );
	}

	private static function settingEnabled( array $settings, string $key ): bool {
		if ( ! array_key_exists( $key, $settings ) ) {
			return false;
		}

		return filter_var( $settings[ $key ], FILTER_VALIDATE_BOOLEAN );
	}

	private function slugify( string $s ): string {
		$s = trim( $s );
		if ( $s === '' ) {
			return '';
		}

		$s = preg_replace( '/[^a-zA-Z0-9\s\-_]/', '', $s );
		$s = preg_replace( '/[\s\-_]+/', '-', $s );
		return trim( strtolower( (string) $s ), '-' );
	}

	private function applyCaseTransformation( string $s, string $case ): string {
		switch ( $case ) {
			case 'uppercase':
				return strtoupper( $s );
			case 'titlecase':
				return ucwords( strtolower( $s ), " \t\r\n\f\v-_" );
			case 'nochange':
				return $s;
			default:
				return strtolower( $s );
		}
	}

	private function asciify( string $s ): string {
		$s = preg_replace( '/[àáâãäå]/u', 'a', $s );
		$s = preg_replace( '/[èéêë]/u', 'e', $s );
		$s = preg_replace( '/[ìíîï]/u', 'i', $s );
		$s = preg_replace( '/[òóôõö]/u', 'o', $s );
		$s = preg_replace( '/[ùúûü]/u', 'u', $s );
		$s = preg_replace( '/[ñ]/u', 'n', $s );
		$s = preg_replace( '/[ýÿ]/u', 'y', $s );
		$s = preg_replace( '/[ç]/u', 'c', $s );
		return (string) $s;
	}

	private function generateUniqueId(): string {
		$chars = 'abcdefghjkmnpqrstuvwxyz23456789';
		$id    = '';
		for ( $i = 0; $i < 3; $i++ ) {
			$id .= $chars[ random_int( 0, strlen( $chars ) - 1 ) ];
		}
		return $id;
	}

	public function scanReferences( int $attachment_id ): array {
		$file = get_attached_file( $attachment_id, true );
		if ( ! $file || ! is_file( $file ) ) {
			return [ 'posts' => [], 'meta' => [], 'options' => [], 'featured_in' => [] ];
		}

		$filename = basename( $file );
		$url      = wp_get_attachment_url( $attachment_id );
		if ( ! $url ) {
			return [ 'posts' => [], 'meta' => [], 'options' => [], 'featured_in' => [] ];
		}

		global $wpdb;

		$posts = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT ID, post_title, post_type FROM {$wpdb->posts}
				WHERE post_type NOT IN ('revision', 'attachment')
				AND (post_content LIKE %s OR post_content LIKE %s)",
				'%' . $wpdb->esc_like( $filename ) . '%',
				'%' . $wpdb->esc_like( $url ) . '%'
			),
			ARRAY_A
		) ?: [];

		$featured_in = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT p.ID, p.post_title, p.post_type FROM {$wpdb->posts} p
				INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID AND pm.meta_key = '_thumbnail_id' AND pm.meta_value = %s
				WHERE p.post_type != 'revision' AND p.post_status != 'trash'",
				(string) $attachment_id
			),
			ARRAY_A
		) ?: [];

		$meta = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT meta_id, meta_key, post_id FROM {$wpdb->postmeta}
				WHERE meta_value LIKE %s
				AND post_id != %d
				AND meta_key NOT IN ('_wp_attached_file', '_wp_attachment_metadata')",
				'%' . $wpdb->esc_like( $filename ) . '%',
				$attachment_id
			),
			ARRAY_A
		) ?: [];

		$options = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT option_name FROM {$wpdb->options} WHERE option_value LIKE %s",
				'%' . $wpdb->esc_like( $filename ) . '%'
			)
		) ?: [];

		return [
			'posts'       => $posts,
			'meta'        => $meta,
			'options'     => $options,
			'featured_in' => $featured_in,
		];
	}

	private function updateReferences( string $old_url, string $new_url, string $old_filename, string $new_filename ): void {
		global $wpdb;

		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)
				WHERE post_content LIKE %s AND post_type NOT IN ('revision') AND post_status NOT IN ('trash','auto-draft')",
				$old_url,
				$new_url,
				'%' . $wpdb->esc_like( $old_url ) . '%'
			)
		);

		$this->updatePostmetaReferences( $old_url, $new_url );
		$this->updatePostmetaReferences( $old_filename, $new_filename );

		$meta_ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s",
				'%' . $wpdb->esc_like( $old_filename ) . '%'
			)
		);

		foreach ( $meta_ids as $meta_id ) {
			$row = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_id = %d",
					(int) $meta_id
				),
				ARRAY_A
			);
			if ( ! $row || empty( $row['meta_value'] ) ) {
				continue;
			}

			$decoded = maybe_unserialize( $row['meta_value'] );
			if ( ! is_array( $decoded ) ) {
				continue;
			}

			$modified = false;
			if ( isset( $decoded['file'] ) && is_string( $decoded['file'] ) && str_contains( $decoded['file'], $old_filename ) ) {
				$decoded['file'] = str_replace( $old_filename, $new_filename, $decoded['file'] );
				$modified        = true;
			}

			if ( isset( $decoded['sizes'] ) && is_array( $decoded['sizes'] ) ) {
				foreach ( $decoded['sizes'] as $kk => $vv ) {
					if ( is_array( $vv ) && isset( $vv['file'] ) && str_contains( (string) $vv['file'], $old_filename ) ) {
						$decoded['sizes'][ $kk ]['file'] = str_replace( $old_filename, $new_filename, (string) $vv['file'] );
						$modified                        = true;
					}
				}
			}

			if ( $modified ) {
				$wpdb->update(
					$wpdb->postmeta,
					[ 'meta_value' => maybe_serialize( $decoded ) ],
					[ 'meta_id' => (int) $meta_id ]
				);
			}
		}
	}

	private function updatePostmetaReferences( string $search, string $replace ): void {
		if ( $search === '' || $search === $replace ) {
			return;
		}

		global $wpdb;
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT meta_id, meta_value FROM {$wpdb->postmeta}
				WHERE meta_value LIKE %s
				AND meta_key NOT IN ('_wp_attached_file', '_wp_attachment_metadata')",
				'%' . $wpdb->esc_like( $search ) . '%'
			),
			ARRAY_A
		);

		if ( empty( $rows ) ) {
			return;
		}

		foreach ( $rows as $row ) {
			$value = (string) $row['meta_value'];
			if ( is_serialized( $value ) ) {
				continue;
			}

			$updated = str_replace( $search, $replace, $value );
			if ( $updated !== $value ) {
				$wpdb->update(
					$wpdb->postmeta,
					[ 'meta_value' => $updated ],
					[ 'meta_id' => (int) $row['meta_id'] ]
				);
			}
		}
	}

	private function createRedirect( string $old_url, string $new_url ): void {
		if ( ! class_exists( \RedirectManager\Module::class ) ) {
			return;
		}

		\RedirectManager\Module::addRedirectRule( $old_url, $new_url );
	}
}
