<?php
/**
 * AVIF Conversion module settings.
 *
 * @package AvifConversion
 */

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'avif-conversion' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'AVIF Conversion requires an active license. Activate your license to convert uploads, serve AVIF to visitors, and manage restore options.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! \WP_PowerSuite\Core\NetworkScope::canManagePlugin() ) {
	return;
}

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

$module_id = $module_id ?? 'avif-conversion';

$settings     = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $settings ) ) {
	$settings = [];
}

$convert_jpeg           = ! array_key_exists( 'convert_jpeg', $settings ) || ! empty( $settings['convert_jpeg'] );
$convert_png            = ! array_key_exists( 'convert_png', $settings ) || ! empty( $settings['convert_png'] );
$keep_original          = ! array_key_exists( 'keep_original', $settings ) || ! empty( $settings['keep_original'] );
$replace_original       = ! empty( $settings['replace_original'] );
$serve_avif_picture     = ! array_key_exists( 'serve_avif_picture', $settings ) || ! empty( $settings['serve_avif_picture'] );
$allow_external_binary  = ! empty( $settings['allow_external_binary'] );
$preset                 = isset( $settings['preset'] ) ? sanitize_key( (string) $settings['preset'] ) : 'balanced';
if ( ! in_array( $preset, [ 'balanced', 'max_compression', 'max_quality', 'custom' ], true ) ) {
	$preset = 'balanced';
}
$quality                = isset( $settings['quality'] ) ? max( 0, min( 100, (int) $settings['quality'] ) ) : 80;
$encoding_speed         = isset( $settings['encoding_speed'] ) ? max( 0, min( 10, (int) $settings['encoding_speed'] ) ) : 6;
$exclusion_suffix       = isset( $settings['exclusion_suffix'] ) && is_string( $settings['exclusion_suffix'] ) ? $settings['exclusion_suffix'] : '-wpps';
$external_binary_path   = isset( $settings['external_binary_path'] ) && is_string( $settings['external_binary_path'] ) ? $settings['external_binary_path'] : '';

require_once __DIR__ . '/module.php';
$avif_module = new \AvifConversion\Module();

// Use cached library summary when available to avoid cold-scan on every settings open.
$cached_summary = get_transient( 'wp_powersuite_avif_library_summary_v1' );
if ( is_array( $cached_summary ) && isset( $cached_summary['count'], $cached_summary['bytes_saved'] ) ) {
	$stat_images = max( 0, (int) $cached_summary['count'] );
	$stat_bytes  = max( 0, (int) $cached_summary['bytes_saved'] );
} else {
	$avif_summary = $avif_module->computeLibraryAvifSummary();
	$stat_images  = (int) ( $avif_summary['count'] ?? 0 );
	$stat_bytes   = (int) ( $avif_summary['bytes_saved'] ?? 0 );
}

$cached_restorable = get_transient( 'wp_powersuite_avif_restorable_count_v1' );
if ( false !== $cached_restorable ) {
	$restorable_count = max( 0, (int) $cached_restorable );
} else {
	$restorable_count = $avif_module->countRestorableAttachments();
}
$show_avif_restore = $restorable_count > 0 && $avif_module->isEnabled() && \WP_PowerSuite\Core\NetworkScope::canManagePlugin();

require_once __DIR__ . '/includes/class-avif-engine.php';
$probe_engine = new \AvifConversion\Avif_Engine( $external_binary_path, $allow_external_binary );
$supported    = $probe_engine->isSupported();
$method       = $probe_engine->detectMethod();
$cap_message  = $probe_engine->getCapabilityMessage();

$method_label = match ( $method ) {
	\AvifConversion\Avif_Engine::METHOD_IMAGICK => __( 'ImageMagick (Imagick)', 'wp-powersuite' ),
	\AvifConversion\Avif_Engine::METHOD_GD => __( 'GD (imageavif)', 'wp-powersuite' ),
	\AvifConversion\Avif_Engine::METHOD_BINARY => __( 'External encoder (cavif)', 'wp-powersuite' ),
	default => __( 'None', 'wp-powersuite' ),
};
?>

<div class="wp-powersuite-module-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<div class="wpps-avif-capability" style="margin-bottom: 16px; padding: 10px 12px; border-left: 4px solid <?php echo $supported ? '#00a32a' : '#d63638'; ?>; background: <?php echo $supported ? '#edfaef' : '#fcf0f1'; ?>;">
			<strong><?php echo $supported ? esc_html__( 'Status: Ready', 'wp-powersuite' ) : esc_html__( 'Status: Not ready', 'wp-powersuite' ); ?></strong>
			<?php if ( $supported ) : ?>
				<span> — <?php echo esc_html( $method_label ); ?>. <?php echo esc_html( $cap_message ); ?></span>
			<?php else : ?>
				<p style="margin: 8px 0 0;"><?php echo esc_html( $cap_message ); ?></p>
			<?php endif; ?>
		</div>

		<p class="description" style="margin-bottom: 16px;">
			<?php esc_html_e( 'When you upload JPEG or PNG photos, we add a smaller AVIF version so your pages can load faster. Turn on “Faster images for visitors” below so modern browsers use that version. Use only this or WebP Conversion—not both.', 'wp-powersuite' ); ?>
		</p>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'JPEG photos', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="convert_jpeg" value="1" <?php checked( $convert_jpeg ); ?> class="wp-powersuite-advanced-setting" data-setting-key="convert_jpeg" />
							<?php esc_html_e( 'Create AVIF copies for JPEG uploads', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'PNG images', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="convert_png" value="1" <?php checked( $convert_png ); ?> class="wp-powersuite-advanced-setting" data-setting-key="convert_png" />
							<?php esc_html_e( 'Create AVIF copies for PNG uploads (transparency is kept)', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="avif-preset"><?php esc_html_e( 'File size vs. quality', 'wp-powersuite' ); ?></label></th>
					<td>
						<select name="preset" id="avif-preset" class="wp-powersuite-advanced-setting" data-setting-key="preset">
							<option value="balanced" <?php selected( $preset, 'balanced' ); ?>><?php esc_html_e( 'Balanced — best for most sites', 'wp-powersuite' ); ?></option>
							<option value="max_compression" <?php selected( $preset, 'max_compression' ); ?>><?php esc_html_e( 'Smaller files', 'wp-powersuite' ); ?></option>
							<option value="max_quality" <?php selected( $preset, 'max_quality' ); ?>><?php esc_html_e( 'Sharper images (larger files)', 'wp-powersuite' ); ?></option>
							<option value="custom" <?php selected( $preset, 'custom' ); ?>><?php esc_html_e( 'I want to choose myself', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>
				<tr class="wpps-avif-custom-encoding-row" style="<?php echo $preset === 'custom' ? 'display: table-row;' : 'display: none;'; ?>">
					<th scope="row"><label for="avif-quality"><?php esc_html_e( 'Quality', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="range" name="quality" id="avif-quality" min="0" max="100" value="<?php echo esc_attr( (string) $quality ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="quality" />
						<span id="avif-quality-val"><?php echo esc_html( (string) $quality ); ?></span>
						<p class="description"><?php esc_html_e( 'Lower = smaller files and softer detail. Higher = sharper photos and larger files.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr class="wpps-avif-custom-encoding-row" style="<?php echo $preset === 'custom' ? 'display: table-row;' : 'display: none;'; ?>">
					<th scope="row"><label for="avif-speed"><?php esc_html_e( 'Speed while creating files', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="range" name="encoding_speed" id="avif-speed" min="0" max="10" value="<?php echo esc_attr( (string) $encoding_speed ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="encoding_speed" />
						<span id="avif-speed-val"><?php echo esc_html( (string) $encoding_speed ); ?></span>
						<p class="description"><?php esc_html_e( 'Higher usually finishes each image faster on the server.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Faster images for visitors', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="serve_avif_picture" value="1" <?php checked( $serve_avif_picture ); ?> class="wp-powersuite-advanced-setting" data-setting-key="serve_avif_picture" />
							<?php esc_html_e( 'Let supported browsers load the smaller AVIF when they view your site', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'What happens to the original upload', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="replace_original" value="1" <?php checked( $replace_original ); ?> class="wp-powersuite-advanced-setting" data-setting-key="replace_original" />
							<?php esc_html_e( 'Turn the main library file into AVIF (default: keep JPEG/PNG and add a separate AVIF file)', 'wp-powersuite' ); ?>
						</label>
						<p class="description"><?php esc_html_e( 'Keeping the original is safer for plugins, editors, and older browsers.', 'wp-powersuite' ); ?></p>
						<label>
							<input type="checkbox" name="keep_original" value="1" <?php checked( $keep_original ); ?> class="wp-powersuite-advanced-setting" data-setting-key="keep_original" />
							<?php esc_html_e( 'If you replace the file, save a backup copy in the uploads folder', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="avif-exclude"><?php esc_html_e( 'Skip certain file names', 'wp-powersuite' ); ?></label></th>
					<td>
						<input type="text" name="exclusion_suffix" id="avif-exclude" value="<?php echo esc_attr( $exclusion_suffix ); ?>" class="regular-text wp-powersuite-advanced-setting" data-setting-key="exclusion_suffix" />
						<p class="description"><?php esc_html_e( 'Files whose names end with this text (before .jpg or .png) are not converted.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>

	</form>

	<script>
	(function() {
		var presetEl = document.getElementById( 'avif-preset' );
		var customRows = document.querySelectorAll( '.wpps-avif-custom-encoding-row' );
		function wppsAvifSyncCustomRows() {
			if ( ! presetEl || ! customRows.length ) {
				return;
			}
			var show = presetEl.value === 'custom';
			customRows.forEach( function( row ) {
				row.style.display = show ? 'table-row' : 'none';
			} );
		}
		if ( presetEl ) {
			presetEl.addEventListener( 'change', wppsAvifSyncCustomRows );
			wppsAvifSyncCustomRows();
		}
		var q = document.getElementById( 'avif-quality' );
		var qs = document.getElementById( 'avif-quality-val' );
		var s = document.getElementById( 'avif-speed' );
		var ss = document.getElementById( 'avif-speed-val' );
		if ( q && qs ) {
			q.addEventListener( 'input', function() { qs.textContent = q.value; } );
		}
		if ( s && ss ) {
			s.addEventListener( 'input', function() { ss.textContent = s.value; } );
		}
	})();
	</script>

	<div class="wpps-avif-status notice notice-info inline" style="margin-top: 24px; max-width: 720px;">
		<h3 style="margin-top: 0;"><?php esc_html_e( 'Summary', 'wp-powersuite' ); ?></h3>
		<p style="margin: 0;">
			<?php
			echo esc_html(
				sprintf(
					/* translators: 1: number of attachments that currently have AVIF, 2: formatted size */
					__( 'Current library: %1$s attachments with AVIF — about %2$s smaller than their source files (cached scan)', 'wp-powersuite' ),
					number_format_i18n( $stat_images ),
					size_format( max( 0, $stat_bytes ), 2 )
				)
			);
			?>
		</p>
	</div>

	<?php if ( $show_avif_restore ) : ?>
	<div class="wpps-avif-restore notice notice-warning inline" style="margin-top: 16px; max-width: 720px;">
		<h3 style="margin-top: 0;"><?php esc_html_e( 'Restore JPEG/PNG originals', 'wp-powersuite' ); ?></h3>
		<p style="margin: 0 0 12px;">
			<?php
			echo esc_html(
				sprintf(
					/* translators: %s: number of attachments that can be restored */
					_n(
						'%s attachment can have AVIF outputs removed and originals brought back (when backups exist).',
						'%s attachments can have AVIF outputs removed and originals brought back (when backups exist).',
						$restorable_count,
						'wp-powersuite'
					),
					number_format_i18n( $restorable_count )
				)
			);
			?>
		</p>
		<p style="margin: 0 0 12px;" class="description">
			<?php esc_html_e( 'This removes plugin-created AVIF files and restores from backups where applicable. Large libraries are processed in batches.', 'wp-powersuite' ); ?>
		</p>
		<button type="button" class="button button-secondary" id="wpps-avif-restore-btn" data-nonce="<?php echo esc_attr( wp_create_nonce( \AvifConversion\Module::RESTORE_NONCE_ACTION ) ); ?>">
			<?php esc_html_e( 'Restore now', 'wp-powersuite' ); ?>
		</button>
		<p id="wpps-avif-restore-status" class="description" style="margin-top: 12px; margin-bottom: 0;" aria-live="polite"></p>
	</div>
	<script>
	(function() {
		var btn = document.getElementById( 'wpps-avif-restore-btn' );
		var statusEl = document.getElementById( 'wpps-avif-restore-status' );
		if ( ! btn || typeof window.ajaxurl === 'undefined' ) {
			return;
		}
		var nonce = btn.getAttribute( 'data-nonce' );
		function runBatch( cursor ) {
			var fd = new FormData();
			fd.append( 'action', 'wp_powersuite_avif_restore_batch' );
			fd.append( 'nonce', nonce );
			fd.append( 'cursor', String( cursor ) );
			fd.append( 'batch', '12' );
			fetch( window.ajaxurl, { method: 'POST', credentials: 'same-origin', body: fd } )
				.then( function( r ) { return r.json(); } )
				.then( function( resp ) {
					if ( ! resp || ! resp.success ) {
						var msg = ( resp && resp.data && resp.data.message ) ? resp.data.message : '<?php echo esc_js( __( 'Restore failed.', 'wp-powersuite' ) ); ?>';
						statusEl.textContent = msg;
						btn.disabled = false;
						return;
					}
					var d = resp.data || {};
					var next = typeof d.next_cursor === 'number' ? d.next_cursor : ( typeof d.next_offset === 'number' ? d.next_offset : cursor );
					var restored = typeof d.restored === 'number' ? d.restored : 0;
					var processed = typeof d.processed === 'number' ? d.processed : 0;
					var done = !! d.done;
					if ( done && processed === 0 && cursor === 0 ) {
						statusEl.textContent = '<?php echo esc_js( __( 'Nothing left to restore.', 'wp-powersuite' ) ); ?>';
						btn.disabled = false;
						return;
					}
					<?php /* translators: 1: number, 2: number. */ ?>
					var batchFmt = <?php echo wp_json_encode( __( 'Restored %1$d in this batch (%2$d processed).', 'wp-powersuite' ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); ?>;
					statusEl.textContent = batchFmt
						.replace( /%1\$d/g, String( restored ) )
						.replace( /%2\$d/g, String( processed ) );
					if ( done ) {
						statusEl.textContent = '<?php echo esc_js( __( 'Restore finished.', 'wp-powersuite' ) ); ?>';
						btn.disabled = false;
						btn.style.display = 'none';
						window.setTimeout( function() { window.location.reload(); }, 600 );
					} else {
						runBatch( next );
					}
				} )
				.catch( function() {
					statusEl.textContent = '<?php echo esc_js( __( 'Network error. Try again.', 'wp-powersuite' ) ); ?>';
					btn.disabled = false;
				} );
		}
		btn.addEventListener( 'click', function() {
			if ( btn.disabled ) {
				return;
			}
			btn.disabled = true;
			statusEl.textContent = '<?php echo esc_js( __( 'Starting…', 'wp-powersuite' ) ); ?>';
			runBatch( 0 );
		} );
	} )();
	</script>
	<?php endif; ?>
</div>

