<?php
/**
 * WebP Conversion module settings template.
 *
 * @package WebpConversion
 */

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 ?? 'webp-conversion' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'WebP Conversion requires an active license. Activate your license to convert uploads and manage restore options.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

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

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

$module_id = $module_id ?? 'webp-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'] );
$quality          = isset( $settings['quality'] ) ? max( 60, min( 100, (int) $settings['quality'] ) ) : 80;
$original_files   = ( isset( $settings['original_files'] ) && $settings['original_files'] === 'keep' ) ? 'keep' : 'delete';
$exclusion_suffix = isset( $settings['exclusion_suffix'] ) && is_string( $settings['exclusion_suffix'] ) ? $settings['exclusion_suffix'] : '-wpps';

require_once __DIR__ . '/module.php';
$webp_module = new \WebpConversion\Module();

$webp_supported       = $webp_module->serverSupportsWebp();
$capability_message   = $webp_module->getServerCapabilityMessage();
$cached_restorable    = get_transient( 'wp_powersuite_webp_restorable_count_v1' );
$restorable_count     = false !== $cached_restorable ? max( 0, (int) $cached_restorable ) : $webp_module->countRestorableAttachments();
$show_webp_restore    = $restorable_count > 0 && $webp_module->isEnabled();
?>

<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="notice notice-<?php echo $webp_supported ? 'success' : 'error'; ?> inline wpps-module-callout">
			<strong><?php esc_html_e( 'Server support:', 'wppowersuite-lite' ); ?></strong>
			<span><?php echo esc_html( $capability_message ); ?></span>
		</div>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label for="webp-convert-jpeg"><?php esc_html_e( 'Convert JPEG files', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<label for="webp-convert-jpeg">
							<input type="checkbox" name="convert_jpeg" id="webp-convert-jpeg" value="1" <?php checked( $convert_jpeg ); ?> class="wp-powersuite-advanced-setting" data-setting-key="convert_jpeg" />
							<?php esc_html_e( 'Convert uploaded JPEG images to WebP', 'wppowersuite-lite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="webp-convert-png"><?php esc_html_e( 'Convert PNG files', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<label for="webp-convert-png">
							<input type="checkbox" name="convert_png" id="webp-convert-png" value="1" <?php checked( $convert_png ); ?> class="wp-powersuite-advanced-setting" data-setting-key="convert_png" />
							<?php esc_html_e( 'Convert uploaded PNG images (preserves transparency)', 'wppowersuite-lite' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="webp-quality"><?php esc_html_e( 'WebP quality', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<input type="number" name="quality" id="webp-quality" value="<?php echo esc_attr( $quality ); ?>" min="60" max="100" class="small-text wp-powersuite-advanced-setting" data-setting-key="quality" />
						<p class="description"><?php esc_html_e( 'Quality level (60–100). Higher = better quality, larger files. Recommended: 80.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="webp-original-files"><?php esc_html_e( 'Original files', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<select name="original_files" id="webp-original-files" class="wp-powersuite-advanced-setting" data-setting-key="original_files">
							<option value="delete" <?php selected( $original_files, 'delete' ); ?>><?php esc_html_e( 'Delete original (save space)', 'wppowersuite-lite' ); ?></option>
							<option value="keep" <?php selected( $original_files, 'keep' ); ?>><?php esc_html_e( 'Keep original as backup (FTP/File Manager only)', 'wppowersuite-lite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'When keeping originals: they are moved to an "originals" subfolder in the same date folder, e.g. wp-content/uploads/YYYY/MM/originals/. The WebP stays in wp-content/uploads/YYYY/MM/ and appears in the Media Library; the original is only accessible via FTP or File Manager.', 'wppowersuite-lite' ); ?></p>
						<p class="description"><?php esc_html_e( 'To verify "Delete original" works: upload a JPEG or PNG, then open that folder via FTP or your host\'s File Manager (e.g. wp-content/uploads/2025/02/). You should see only the .webp file; the .jpg or .png should be gone.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="webp-exclusion-suffix"><?php esc_html_e( 'Exclusion suffix', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<input type="text" name="exclusion_suffix" id="webp-exclusion-suffix" 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 name ends with this suffix (before extension) skip conversion. Example: photo-wpps.jpg stays as JPEG.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<?php if ( $show_webp_restore ) : ?>
	<div class="notice notice-warning inline wpps-webp-restore" style="margin-top: 24px; max-width: 720px;">
		<h3><?php esc_html_e( 'Restore JPEG/PNG originals', 'wppowersuite-lite' ); ?></h3>
		<p style="margin: 0 0 12px;">
			<?php
			echo esc_html(
				sprintf(
					/* translators: %s: number of attachments that can be restored */
					_n(
						'%s attachment has a backup in the originals folder and can be switched back from WebP.',
						'%s attachments have backups in the originals folder and can be switched back from WebP.',
						$restorable_count,
						'wppowersuite-lite'
					),
					number_format_i18n( $restorable_count )
				)
			);
			?>
		</p>
		<p style="margin: 0 0 12px;" class="description">
			<?php esc_html_e( 'Only applies when originals were kept (not deleted). Restores the JPEG or PNG next to the WebP and removes the library WebP file. Large libraries are processed in batches.', 'wppowersuite-lite' ); ?>
		</p>
		<button type="button" class="button button-secondary" id="wpps-webp-restore-btn" data-nonce="<?php echo esc_attr( wp_create_nonce( \WebpConversion\Module::RESTORE_NONCE_ACTION ) ); ?>">
			<?php esc_html_e( 'Restore now', 'wppowersuite-lite' ); ?>
		</button>
		<p id="wpps-webp-restore-status" class="description" style="margin-top: 12px; margin-bottom: 0;" aria-live="polite"></p>
	</div>
	<?php ob_start(); ?>
	(function() {
		var btn = document.getElementById( 'wpps-webp-restore-btn' );
		var statusEl = document.getElementById( 'wpps-webp-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_webp_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.', 'wppowersuite-lite' ) ); ?>';
						statusEl.textContent = msg;
						btn.disabled = false;
						return;
					}
					var d = resp.data || {};
					var next = typeof d.next_cursor === 'number' ? d.next_cursor : 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.', 'wppowersuite-lite' ) ); ?>';
						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).', 'wppowersuite-lite' ), 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.', 'wppowersuite-lite' ) ); ?>';
						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.', 'wppowersuite-lite' ) ); ?>';
					btn.disabled = false;
				} );
		}
		btn.addEventListener( 'click', function() {
			if ( btn.disabled ) {
				return;
			}
			btn.disabled = true;
			statusEl.textContent = '<?php echo esc_js( __( 'Starting…', 'wppowersuite-lite' ) ); ?>';
			runBatch( 0 );
		} );
	} )();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-webp-conversion-admin-php-script-1', (string) ob_get_clean() ); ?>
	<?php endif; ?>
</div>

