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

/* -------------------------------------------------------------------------
 * HTTP common args
 * ---------------------------------------------------------------------- */

function misticease_http_args( array $extra = [], string $url = '' ): array {
	$ua = sprintf( 'MisticEase/%s', MISTICEASE_VER );
	$args = [
		'timeout' => 5,
		'headers' => [
			'User-Agent' => apply_filters( 'misticease_user_agent', $ua, $url ),
		],
	];
	$args = apply_filters( 'misticease_http_args', $args, $url );
	if ( isset( $extra['headers'] ) && is_array( $extra['headers'] ) ) {
		$args['headers'] = array_merge( $args['headers'], $extra['headers'] );
		unset( $extra['headers'] );
	}
	return array_merge( $args, $extra );
}

function misticease_should_avoid_remote(): bool {
	if ( is_admin() ) {
		return true;
	}
	if ( is_feed() ) {
		return true;
	}
	if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
		return true;
	}
	if ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) {
		return true;
	}
	if ( defined( 'WP_CLI' ) && WP_CLI ) {
		return true;
	}
	if ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) {
		return true;
	}
	return false;
}

function misticease_allow_remote(): bool {
	return ! misticease_should_avoid_remote();
}

/* -------------------------------------------------------------------------
 * oEmbed title
 * ---------------------------------------------------------------------- */

function misticease_get_video_oembed_endpoint( string $url ): string {
	if ( preg_match( '#youtu\.be|youtube\.com#i', $url ) ) {
		$endpoint = 'https://www.youtube.com/oembed?url=' . rawurlencode( $url ) . '&format=json';
	} elseif ( preg_match( '#vimeo\.com#i', $url ) ) {
		$endpoint = 'https://vimeo.com/api/oembed.json?url=' . rawurlencode( $url );
	} elseif ( preg_match( '#dailymotion\.com|dai\.ly#i', $url ) ) {
		$endpoint = 'https://www.dailymotion.com/services/oembed?url=' . rawurlencode( $url ) . '&format=json';
	} else {
		return '';
	}

	$parts   = wp_parse_url( $url );
	$host    = isset( $parts['host'] ) ? strtolower( (string) $parts['host'] ) : '';
	$allowed = [
		'youtu.be',
		'youtube.com',
		'www.youtube.com',
		'm.youtube.com',
		'vimeo.com',
		'www.vimeo.com',
		'player.vimeo.com',
		'dailymotion.com',
		'www.dailymotion.com',
		'dai.ly',
	];
	if ( ! in_array( $host, $allowed, true ) ) {
		return '';
	}

	return $endpoint;
}

function misticease_fetch_video_title_remote( string $url ): string {
	$endpoint = misticease_get_video_oembed_endpoint( $url );
	if ( '' === $endpoint ) {
		return (string) $url;
	}

	$title = (string) $url;
	$res   = wp_remote_get( $endpoint, misticease_http_args( [ 'timeout' => 5 ], $endpoint ) );
	if ( ! is_wp_error( $res ) && 200 === wp_remote_retrieve_response_code( $res ) ) {
		$data = json_decode( wp_remote_retrieve_body( $res ), true );
		if ( isset( $data['title'] ) ) {
			$title = sanitize_text_field( $data['title'] );
		}
	}

	return $title;
}

function misticease_get_video_title( string $url ): string {
	static $runtime_cache = array();

	$key = md5( $url );

	if ( isset( $runtime_cache[ $key ] ) ) {
		return (string) $runtime_cache[ $key ];
	}

	if ( ! misticease_allow_remote() ) {
		$runtime_cache[ $key ] = (string) $url;
		return (string) $url;
	}

	$title = misticease_fetch_video_title_remote( $url );

	if ( '' === trim( $title ) ) {
		$title = (string) $url;
	}

	$runtime_cache[ $key ] = $title;

	return $title;
}

/* -------------------------------------------------------------------------
 * Thumbnail: local-first + delayed HD prefetch
 * ---------------------------------------------------------------------- */

function misticease_touch_file( string $file ): void {
	if ( '' === $file ) {
		return;
	}

	global $wp_filesystem;
	if ( ! isset( $wp_filesystem ) || ! $wp_filesystem || ! is_object( $wp_filesystem ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
	}

	if ( ! $wp_filesystem || ! is_object( $wp_filesystem ) || ! method_exists( $wp_filesystem, 'touch' ) ) {
		return;
	}

	if ( method_exists( $wp_filesystem, 'exists' ) && ! $wp_filesystem->exists( $file ) ) {
		return;
	}

	if ( method_exists( $wp_filesystem, 'is_file' ) && ! $wp_filesystem->is_file( $file ) ) {
		return;
	}

	$now = time();
	$wp_filesystem->touch( $file, $now, $now );
}

function misticease_build_remote_list( string $service, string $video_id ): array {
	$service  = strtolower( $service );
	$video_id = preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $video_id );
	$remotes  = [];

	if ( '' === $video_id ) {
		return [];
	}

	switch ( $service ) {
		case 'youtube':
			$remotes[] = "https://img.youtube.com/vi/{$video_id}/maxresdefault.jpg";
			$remotes[] = "https://img.youtube.com/vi/{$video_id}/mqdefault.jpg";
			break;

		case 'vimeo':
			$o = wp_remote_get(
				"https://vimeo.com/api/oembed.json?url=https://vimeo.com/{$video_id}&width=1280",
				misticease_http_args( [ 'timeout' => 5, 'reject_unsafe_urls' => true ], 'https://vimeo.com/api/oembed.json' )
			);
			if ( ! is_wp_error( $o ) && 200 === wp_remote_retrieve_response_code( $o ) ) {
				$d = json_decode( wp_remote_retrieve_body( $o ), true );
				if ( isset( $d['thumbnail_url'] ) ) {
					$hd        = preg_replace( '/_(\d+x\d+)(\.\w+)$/', '_1280x720$2', $d['thumbnail_url'] );
					$remotes[] = $hd;
					$remotes[] = $d['thumbnail_url'];
				}
			}
			break;

		case 'dailymotion':
			$api = wp_remote_get(
				"https://api.dailymotion.com/video/{$video_id}?fields=thumbnail_720_url,thumbnail_480_url",
				misticease_http_args( [ 'timeout' => 5, 'reject_unsafe_urls' => true ], 'https://api.dailymotion.com/' )
			);
			if ( ! is_wp_error( $api ) && 200 === wp_remote_retrieve_response_code( $api ) ) {
				$d = json_decode( wp_remote_retrieve_body( $api ), true );
				foreach ( [ 'thumbnail_720_url', 'thumbnail_480_url' ] as $k ) {
					if ( ! empty( $d[ $k ] ) ) {
						$remotes[] = $d[ $k ];
					}
				}
			}
			$remotes[] = "https://www.dailymotion.com/thumbnail/1280x720/video/{$video_id}";
			$remotes[] = "https://www.dailymotion.com/thumbnail/video/{$video_id}";
			break;
	}

	return array_values(
		array_unique(
			array_filter(
				array_map(
					static function ( $url ) {
						$url = is_string( $url ) ? trim( $url ) : '';
						return ( '' !== $url ) ? $url : null;
					},
					$remotes
				)
			)
		)
	);
}

function misticease_get_thumb_local( string $service, string $video_id ): string {
	$local = misticease_local_thumb_path( $service, $video_id );

	misticease_ensure_dir_with_index( dirname( $local ) );

	if ( file_exists( $local ) && is_file( $local ) ) {
		misticease_touch_file( $local );
		return misticease_local_thumb_url( $service, $video_id );
	}

	misticease_bg_fetch_hd_thumb( $service, $video_id );
	return misticease_remote_fallback( $service, $video_id );
}

function misticease_vimeo_placeholder_url(): string {
	return plugins_url( 'inc/app/img/vimeo-placeholder.jpg', misticease_basefile() );
}

function misticease_remote_fallback( string $service, string $video_id ): string {
	$video_id = preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $video_id );
	switch ( strtolower( $service ) ) {
		case 'youtube':
			return "https://img.youtube.com/vi/{$video_id}/mqdefault.jpg";
		case 'vimeo':
			return misticease_vimeo_placeholder_url();
		case 'dailymotion':
			return "https://www.dailymotion.com/thumbnail/video/{$video_id}";
		default:
			return '';
	}
}

function misticease_hd_thumb_prefetch_token( string $service, string $video_id ): string {
	$service  = strtolower( (string) $service );
	$video_id = preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $video_id );
	$video_id = is_string( $video_id ) ? $video_id : '';

	return hash_hmac( 'sha256', $service . '|' . $video_id, wp_salt( 'nonce' ) );
}

function misticease_hd_thumb_lock_ttl(): int {
	return max( 10, (int) apply_filters( 'misticease_hd_thumb_lock_ttl', 60 ) );
}

function misticease_hd_thumb_prefetch_limit(): int {
	return max( 1, (int) apply_filters( 'misticease_hd_thumb_prefetch_limit', 50 ) );
}

function misticease_hd_thumb_lock_path( string $service, string $video_id ): string {
	$local = misticease_local_thumb_path( $service, $video_id );
	return $local . '.lock';
}

function misticease_hd_thumb_lock_is_active( string $lock_file ): bool {
	if ( '' === $lock_file || ! file_exists( $lock_file ) || ! is_file( $lock_file ) ) {
		return false;
	}

	$mtime = filemtime( $lock_file );
	if ( false === $mtime || ( time() - (int) $mtime ) > misticease_hd_thumb_lock_ttl() ) {
		wp_delete_file( $lock_file );
		return false;
	}

	return true;
}

function misticease_acquire_hd_thumb_lock( string $lock_file ): bool {
	if ( '' === $lock_file || ! misticease_path_is_under_uploads( $lock_file ) ) {
		return false;
	}

	$dir = dirname( $lock_file );
	wp_mkdir_p( $dir );
	misticease_ensure_dir_with_index( $dir );

	if ( misticease_hd_thumb_lock_is_active( $lock_file ) ) {
		return false;
	}

	$handle = @fopen( $lock_file, 'x' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Atomic lock creation in the uploads cache directory.
	if ( false === $handle ) {
		if ( misticease_hd_thumb_lock_is_active( $lock_file ) ) {
			return false;
		}
		wp_delete_file( $lock_file );
		$handle = @fopen( $lock_file, 'x' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Atomic lock creation in the uploads cache directory.
		if ( false === $handle ) {
			return false;
		}
	}

	fwrite( $handle, (string) time() ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite -- Lock file content is not user-facing and is stored in the plugin cache directory.
	fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Matching close for the atomic lock handle.

	return true;
}

function misticease_release_hd_thumb_lock( string $lock_file ): void {
	if ( '' !== $lock_file && misticease_path_is_under_uploads( $lock_file ) && file_exists( $lock_file ) ) {
		wp_delete_file( $lock_file );
	}
}

function misticease_bg_fetch_hd_thumb( string $service, string $video_id ): void {
	static $queued = [];

	if ( ! misticease_allow_remote() ) {
		return;
	}

	$service  = strtolower( (string) $service );
	$video_id = preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $video_id );
	if ( '' === $video_id || ! in_array( $service, [ 'youtube', 'vimeo', 'dailymotion' ], true ) ) {
		return;
	}

	$local = misticease_local_thumb_path( $service, $video_id );
	if ( file_exists( $local ) && is_file( $local ) ) {
		return;
	}

	if ( misticease_hd_thumb_lock_is_active( misticease_hd_thumb_lock_path( $service, $video_id ) ) ) {
		return;
	}

	$key = $service . '|' . $video_id;
	if ( isset( $queued[ $key ] ) ) {
		return;
	}
	$queued[ $key ] = true;

	global $misticease_hd_thumb_prefetch_jobs;
	if ( ! is_array( $misticease_hd_thumb_prefetch_jobs ) ) {
		$misticease_hd_thumb_prefetch_jobs = [];
	}

	$misticease_hd_thumb_prefetch_jobs[ $key ] = [
		'service'  => $service,
		'video_id' => $video_id,
		'token'    => misticease_hd_thumb_prefetch_token( $service, $video_id ),
	];
}

function misticease_do_fetch_hd_thumb( string $service, string $video_id, string $local ): void {
	$service  = strtolower( (string) $service );
	$video_id = preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $video_id );

	if ( '' === $video_id || ! in_array( $service, [ 'youtube', 'vimeo', 'dailymotion' ], true ) ) {
		return;
	}

	if ( function_exists( 'fastcgi_finish_request' ) ) {
		fastcgi_finish_request();
	}

	if ( file_exists( $local ) && is_file( $local ) && filesize( $local ) > 0 ) {
		return;
	}

	require_once ABSPATH . 'wp-admin/includes/file.php';
	wp_mkdir_p( dirname( $local ) );
	misticease_ensure_dir_with_index( dirname( $local ) );

	$remotes = misticease_build_remote_list( $service, $video_id );
	if ( empty( $remotes ) ) {
		return;
	}

	$saved = false;

	foreach ( $remotes as $url ) {
		if ( file_exists( $local ) ) {
			wp_delete_file( $local );
		}

		$r = wp_remote_get(
			$url,
			misticease_http_args(
				[
					'timeout'             => 8,
					'redirection'         => 2,
					'limit_response_size' => 5 * 1024 * 1024,
					'stream'              => true,
					'reject_unsafe_urls'  => true,
					'sslverify'           => true,
					'headers'             => [ 'Accept' => 'image/jpeg,image/*;q=0.8,*/*;q=0.5' ],
					'filename'            => $local,
				],
				$url
			)
		);

		if ( is_wp_error( $r ) ) {
			if ( file_exists( $local ) ) {
				wp_delete_file( $local );
			}
			continue;
		}
		if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
			if ( file_exists( $local ) ) {
				wp_delete_file( $local );
			}
			continue;
		}
		if ( ! file_exists( $local ) || ! is_file( $local ) || filesize( $local ) <= 0 ) {
			continue;
		}

		$mime = function_exists( 'wp_get_image_mime' ) ? wp_get_image_mime( $local ) : '';
		if ( ! is_string( $mime ) || 0 !== strpos( $mime, 'image/' ) ) {
			wp_delete_file( $local );
			continue;
		}

		$saved = true;
		break;
	}

	if ( $saved ) {
		misticease_touch_file( $local );
		misticease_sync_used_thumb_cache();
		misticease_enforce_thumb_quota();
	} else {
		wp_delete_file( $local );
	}
}

function misticease_handle_hd_thumb_prefetch(): void {
	$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';

	if ( ! wp_verify_nonce( $nonce, 'misticease_hd_thumb_prefetch' ) ) {
		wp_die( '0', 403 );
	}

	$service_raw  = isset( $_POST['service'] ) ? sanitize_text_field( wp_unslash( $_POST['service'] ) ) : '';
	$video_id_raw = isset( $_POST['video_id'] ) ? sanitize_text_field( wp_unslash( $_POST['video_id'] ) ) : '';
	$token        = isset( $_POST['token'] ) ? sanitize_text_field( wp_unslash( $_POST['token'] ) ) : '';

	$service = strtolower( sanitize_key( $service_raw ) );
	$video_id = preg_replace( '/[^A-Za-z0-9_-]/', '', $video_id_raw );
	$video_id     = is_string( $video_id ) ? $video_id : '';

	if ( '' === $service || '' === $video_id || ! in_array( $service, [ 'youtube', 'vimeo', 'dailymotion' ], true ) ) {
		wp_die( '0', 400 );
	}

	$expected_token = misticease_hd_thumb_prefetch_token( $service, $video_id );
	if ( '' === $token || ! hash_equals( $expected_token, $token ) ) {
		wp_die( '0', 403 );
	}

	$local = misticease_local_thumb_path( $service, $video_id );
	if ( file_exists( $local ) && is_file( $local ) && filesize( $local ) > 0 ) {
		misticease_touch_file( $local );
		wp_die( '1' );
	}

	$lock_file = misticease_hd_thumb_lock_path( $service, $video_id );
	if ( ! misticease_acquire_hd_thumb_lock( $lock_file ) ) {
		wp_die( '1' );
	}

	ignore_user_abort( true );
	if ( function_exists( 'set_time_limit' ) ) {
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- Background HD thumbnail downloads may exceed the default time limit on slow remote responses.
		@set_time_limit( 0 );
	}

	try {
		misticease_do_fetch_hd_thumb( $service, $video_id, $local );
	} finally {
		misticease_release_hd_thumb_lock( $lock_file );
	}

	wp_die( '1' );
}
add_action( 'wp_ajax_misticease_hd_thumb_prefetch', 'misticease_handle_hd_thumb_prefetch' );
add_action( 'wp_ajax_nopriv_misticease_hd_thumb_prefetch', 'misticease_handle_hd_thumb_prefetch' );

function misticease_enqueue_hd_thumb_prefetch_script(): void {
	if ( is_admin() ) {
		return;
	}

	global $misticease_hd_thumb_prefetch_jobs;
	if ( empty( $misticease_hd_thumb_prefetch_jobs ) || ! is_array( $misticease_hd_thumb_prefetch_jobs ) ) {
		return;
	}

	$items = [];
	foreach ( array_values( $misticease_hd_thumb_prefetch_jobs ) as $item ) {
		$service  = isset( $item['service'] ) ? strtolower( sanitize_key( (string) $item['service'] ) ) : '';
		$video_id = isset( $item['video_id'] ) ? preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $item['video_id'] ) : '';
		$video_id = is_string( $video_id ) ? $video_id : '';
		if ( '' === $service || '' === $video_id ) {
			continue;
		}
		$local = misticease_local_thumb_path( $service, $video_id );
		if ( file_exists( $local ) && is_file( $local ) && filesize( $local ) > 0 ) {
			continue;
		}
		if ( misticease_hd_thumb_lock_is_active( misticease_hd_thumb_lock_path( $service, $video_id ) ) ) {
			continue;
		}
		$items[] = $item;
		if ( count( $items ) >= misticease_hd_thumb_prefetch_limit() ) {
			break;
		}
	}
	if ( empty( $items ) ) {
		return;
	}

	$config = [
		'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
		'nonce'         => wp_create_nonce( 'misticease_hd_thumb_prefetch' ),
		'maxConcurrent' => 2,
		'items'         => $items,
	];

	$payload = wp_json_encode( $config );
	if ( false === $payload ) {
		return;
	}

	[ $url, $ver ] = misticease_asset( 'inc/app/js/misticease-hd-thumb-prefetch.js' );
	wp_register_script( 'misticease-hd-thumb-prefetch', $url, [], $ver, true );
	wp_add_inline_script( 'misticease-hd-thumb-prefetch', 'window.misticeaseHdThumbPrefetchConfig = ' . $payload . ';', 'before' );
	wp_enqueue_script( 'misticease-hd-thumb-prefetch' );
}
add_action( 'wp_footer', 'misticease_enqueue_hd_thumb_prefetch_script', 1 );

function misticease_effective_quota_mb(): int {
	if ( is_multisite() && (bool) get_site_option( 'misticease_network_enforce_quota', false ) ) {
		return max( 0, (int) get_site_option( 'misticease_network_default_quota_mb', 0 ) );
	}
	$o = misticease_opts_get();
	return max( 0, (int) ( $o['cache_quota_mb'] ?? 0 ) );
}

function misticease_collect_thumb_cache_files( string $dir ): array {
	$dir = rtrim( $dir, "/ \t\n\r\0\x0B" );
	if ( '' === $dir || ! is_dir( $dir ) ) {
		return [];
	}

	clearstatcache();

	$paths = glob( trailingslashit( $dir ) . '*', GLOB_NOSORT );
	if ( false === $paths ) {
		$entries = scandir( $dir );
		if ( false === $entries ) {
			return [];
		}

		$paths = [];
		foreach ( $entries as $entry ) {
			if ( '.' === $entry || '..' === $entry ) {
				continue;
			}
			$paths[] = trailingslashit( $dir ) . $entry;
		}
	}

	$files = [];
	foreach ( $paths as $path ) {
		if ( ! is_file( $path ) || is_link( $path ) ) {
			continue;
		}

		$base = basename( $path );
		if ( in_array( $base, [ 'index.php', 'index.html', '.htaccess' ], true ) ) {
			continue;
		}

		$ext = strtolower( (string) pathinfo( $base, PATHINFO_EXTENSION ) );
		if ( ! in_array( $ext, [ 'jpg', 'jpeg', 'webp' ], true ) ) {
			continue;
		}

		$size = is_readable( $path ) ? filesize( $path ) : false;
		if ( false === $size || $size <= 0 ) {
			continue;
		}

		$mtime = filemtime( $path );
		if ( false === $mtime ) {
			$mtime = 0;
		}

		$files[] = [
			'path'  => $path,
			'size'  => (int) $size,
			'mtime' => (int) $mtime,
		];
	}

	return $files;
}

function misticease_enforce_thumb_quota(): void {
	$cap_mb = misticease_effective_quota_mb();
	if ( $cap_mb <= 0 ) {
		return;
	}
	$cap_bytes = (int) $cap_mb * 1024 * 1024;
	misticease_cleanup_thumbs_to_cap( $cap_bytes );
}

function misticease_cleanup_thumbs_to_cap( int $cap_bytes ): void {
	$dir = misticease_cache_dir();
	if ( ! is_dir( $dir ) ) {
		misticease_opts_update( [ 'used_cache_bytes' => 0 ] );
		set_transient( 'misticease_used_cache_bytes_t', 0, 10 * MINUTE_IN_SECONDS );
		return;
	}

	$files = misticease_collect_thumb_cache_files( $dir );
	$total = 0;
	foreach ( $files as $file ) {
		$total += (int) $file['size'];
	}

	if ( $total <= $cap_bytes ) {
		misticease_opts_update( [ 'used_cache_bytes' => (int) $total ] );
		set_transient( 'misticease_used_cache_bytes_t', (int) $total, 10 * MINUTE_IN_SECONDS );
		return;
	}

	usort(
		$files,
		static function ( $a, $b ) {
			if ( $a['mtime'] === $b['mtime'] ) {
				return strcmp( $a['path'], $b['path'] );
			}
			return ( $a['mtime'] < $b['mtime'] ) ? -1 : 1;
		}
	);

	foreach ( $files as $file ) {
		if ( $total <= $cap_bytes ) {
			break;
		}

		if ( wp_delete_file( $file['path'] ) ) {
			$total -= (int) $file['size'];
		}
	}

	$final = misticease_calc_dir_size_bytes( $dir );
	misticease_opts_update( [ 'used_cache_bytes' => (int) $final ] );
	set_transient( 'misticease_used_cache_bytes_t', (int) $final, 10 * MINUTE_IN_SECONDS );
}

function misticease_cleanup_current_site_thumbs(): void {
	$dir = misticease_cache_dir();
	if ( ! is_dir( $dir ) ) {
		misticease_opts_update( [ 'used_cache_bytes' => 0 ] );
		set_transient( 'misticease_used_cache_bytes_t', 0, 10 * MINUTE_IN_SECONDS );
		return;
	}

	$cutoff = time() - ( 90 * DAY_IN_SECONDS );
	$files  = misticease_collect_thumb_cache_files( $dir );

	foreach ( $files as $file ) {
		if ( ! empty( $file['mtime'] ) && (int) $file['mtime'] < $cutoff ) {
			wp_delete_file( $file['path'] );
		}
	}

	misticease_enforce_thumb_quota();
	misticease_sync_used_thumb_cache();
}

add_filter(
	'cron_schedules',
	static function ( array $schedules ): array {
		$schedules['misticease_every_30_days'] = [
			'interval' => 30 * DAY_IN_SECONDS,
			'display'  => __( 'Every 30 days', 'misticease' ),
		];
		return $schedules;
	}
);

function misticease_is_cron_owner_blog(): bool {
	if ( ! is_multisite() ) {
		return true;
	}

	if ( function_exists( 'is_main_site' ) && is_main_site() ) {
		return true;
	}

	if ( function_exists( 'get_main_site_id' ) ) {
		return (int) get_current_blog_id() === (int) get_main_site_id();
	}

	return (int) get_current_blog_id() === 1;
}

function misticease_schedule_thumb_cleanup(): void {
	if ( ! misticease_is_cron_owner_blog() ) {
		return;
	}

	$hook             = 'misticease_cleanup_thumbs';
	$desired_schedule = 'misticease_every_30_days';
	$desired_interval = 30 * DAY_IN_SECONDS;
	$event            = wp_get_scheduled_event( $hook );

	if ( ! $event ) {
		wp_schedule_event( time() + 300, $desired_schedule, $hook );
		return;
	}

	$event_schedule = isset( $event->schedule ) ? (string) $event->schedule : '';
	$event_interval = isset( $event->interval ) ? (int) $event->interval : 0;

	if ( $desired_schedule === $event_schedule && $desired_interval === $event_interval ) {
		return;
	}

	wp_clear_scheduled_hook( $hook );

	$timestamp = isset( $event->timestamp ) ? (int) $event->timestamp : 0;
	if ( $timestamp <= 0 ) {
		$timestamp = time() + 300;
	}

	wp_schedule_event( $timestamp, $desired_schedule, $hook );
}

function misticease_unschedule_thumb_cleanup(): void {
	wp_clear_scheduled_hook( 'misticease_cleanup_thumbs' );
}


add_action(
	'init',
	static function (): void {
		misticease_schedule_thumb_cleanup();
	}
);

add_action(
	'misticease_cleanup_thumbs',
	static function (): void {
		if ( ! misticease_is_cron_owner_blog() ) {
			misticease_unschedule_thumb_cleanup();
			return;
		}

		if ( is_multisite() ) {
			$ids = get_sites( array( 'number' => 0, 'fields' => 'ids', 'deleted' => false ) );
			foreach ( (array) $ids as $blog_id ) {
				$blog_id = (int) $blog_id;
				if ( $blog_id <= 0 ) {
					continue;
				}
				switch_to_blog( $blog_id );
				misticease_cleanup_current_site_thumbs();
				restore_current_blog();
			}
			return;
		}

		misticease_cleanup_current_site_thumbs();
	}
);