<?php
/**
 * Admin functionality for STWP plugin.
 *
 * @package STWP
 * @since 1.1.0
 */

namespace STWP;

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access not allowed.' );
}

/**
 * Admin class handles all admin-side functionality.
 *
 * @since 1.0.0
 */
final class Admin {

	/**
	 * Initialize admin hooks and filters.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function init() {
		\add_action( 'admin_notices', array( __CLASS__, 'admin_notices' ) );
		\add_action( 'admin_init', array( __CLASS__, 'register_settings' ) );
		\add_filter( 'attachment_fields_to_edit', array( __CLASS__, 'attachment_restore_field' ), 10, 2 );
		\add_filter( 'attachment_fields_to_save', array( __CLASS__, 'attachment_fields_to_save' ), 10, 2 );
		\add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
	}

	/**
	 * Enqueue admin assets (CSS/JS).
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function enqueue_assets() {
		// Reserved for future admin styles/scripts if needed.
	}

	/**
	 * Display admin notices on relevant screens.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function admin_notices() {
		if ( ! Utils::is_admin_screen_media() ) {
			return;
		}

		// Check for WebP support.
		if ( ! Utils::can_output_webp() ) {
			echo '<div class="notice notice-warning"><p>';
			echo '<strong>' . esc_html__( 'STWP:', 'stintlief-webp-converter' ) . '</strong> ';
			echo esc_html__( 'WebP output is not supported on this server. Enable Imagick with WebP support or GD with WebP enabled to use conversion.', 'stintlief-webp-converter' );
			echo '</p></div>';
			return;
		}

		$enabled      = Utils::bool_option( 'stwp_convert_to_webp', false );
		$settings_url = \admin_url( 'options-media.php' );

		if ( $enabled ) {
			echo '<div class="notice notice-info is-dismissible"><p>';
			echo '<strong>' . esc_html__( 'STWP:', 'stintlief-webp-converter' ) . '</strong> ';
			echo esc_html__( 'WebP conversion is enabled.', 'stintlief-webp-converter' ) . ' ';
			/* translators: %s: Settings URL */
			printf( esc_html__( 'Configure it in %s.', 'stintlief-webp-converter' ), '<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Settings → Media', 'stintlief-webp-converter' ) . '</a>' );
			echo '</p></div>';
		} else {
			echo '<div class="notice notice-info is-dismissible"><p>';
			echo '<strong>' . esc_html__( 'STWP:', 'stintlief-webp-converter' ) . '</strong> ';
			echo esc_html__( 'WebP conversion is disabled.', 'stintlief-webp-converter' ) . ' ';
			/* translators: %s: Settings URL */
			printf( esc_html__( 'Enable it in %s.', 'stintlief-webp-converter' ), '<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Settings → Media', 'stintlief-webp-converter' ) . '</a>' );
			echo '</p></div>';
		}

		// Check for restoration success/failure messages.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only status parameter, capability verified.
		if ( isset( $_GET['stwp_restored'] ) && \current_user_can( 'upload_files' ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only status parameter, capability verified.
			$ok = \absint( $_GET['stwp_restored'] ) === 1;
			if ( $ok ) {
				echo '<div class="notice notice-success is-dismissible"><p>';
				echo '<strong>' . esc_html__( 'STWP:', 'stintlief-webp-converter' ) . '</strong> ';
				echo esc_html__( 'Original image restored successfully.', 'stintlief-webp-converter' );
				echo '</p></div>';
			} else {
				echo '<div class="notice notice-error is-dismissible"><p>';
				echo '<strong>' . esc_html__( 'STWP:', 'stintlief-webp-converter' ) . '</strong> ';
				echo esc_html__( 'Could not restore the original image. Backup not found.', 'stintlief-webp-converter' );
				echo '</p></div>';
			}
		}
	}

	/**
	 * Register plugin settings in Media settings page.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function register_settings() {
		// Toggle conversion on/off.
		\register_setting(
			'media',
			'stwp_convert_to_webp',
			array(
				'type'              => 'boolean',
				'sanitize_callback' => 'rest_sanitize_boolean',
				'default'           => false,
				'description'       => \__( 'Enable automatic WebP conversion for uploaded images.', 'stintlief-webp-converter' ),
			)
		);

		// Maximum width.
		\register_setting(
			'media',
			'stwp_max_width',
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
				'default'           => 1920,
				'description'       => \__( 'Maximum width for resized images in pixels.', 'stintlief-webp-converter' ),
			)
		);

		// Maximum height.
		\register_setting(
			'media',
			'stwp_max_height',
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
				'default'           => 1080,
				'description'       => \__( 'Maximum height for resized images in pixels.', 'stintlief-webp-converter' ),
			)
		);

		// Compression quality.
		\register_setting(
			'media',
			'stwp_compression_quality',
			array(
				'type'              => 'integer',
				'sanitize_callback' => function ( $value ) {
					$v = \absint( $value );
					return \max( 1, \min( 100, $v ) );
				},
				'default'           => 80,
				'description'       => \__( 'WebP compression quality (1-100).', 'stintlief-webp-converter' ),
			)
		);

		// Keep original backup.
		\register_setting(
			'media',
			'stwp_keep_original_backup',
			array(
				'type'              => 'boolean',
				'sanitize_callback' => 'rest_sanitize_boolean',
				'default'           => true,
				'description'       => \__( 'Keep a backup of original files for restoration.', 'stintlief-webp-converter' ),
			)
		);

		// Force WebP even if larger.
		\register_setting(
			'media',
			'stwp_force_webp',
			array(
				'type'              => 'boolean',
				'sanitize_callback' => 'rest_sanitize_boolean',
				'default'           => false,
				'description'       => \__( 'Force WebP conversion even if file size is larger.', 'stintlief-webp-converter' ),
			)
		);

		// Add settings fields.
		\add_settings_field(
			'stwp_convert_to_webp',
			\__( 'Convert uploaded images to WebP (STWP)', 'stintlief-webp-converter' ),
			array( __CLASS__, 'field_toggle' ),
			'media',
			'default',
			array( 'label_for' => 'stwp_convert_to_webp' )
		);

		\add_settings_field(
			'stwp_image_settings',
			\__( 'STWP image processing', 'stintlief-webp-converter' ),
			array( __CLASS__, 'field_image_settings' ),
			'media',
			'default'
		);
	}

	/**
	 * Render the main toggle field for WebP conversion.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function field_toggle() {
		$value = Utils::bool_option( 'stwp_convert_to_webp', false );
		?>
		<label>
			<input 
				type="checkbox" 
				id="stwp_convert_to_webp" 
				name="stwp_convert_to_webp" 
				value="1" 
				<?php checked( true, $value ); ?>
			/>
			<?php esc_html_e( 'Enable automatic conversion of uploaded images to WebP.', 'stintlief-webp-converter' ); ?>
		</label>
		<p class="description">
			<?php esc_html_e( 'Only converts when WebP is supported. Animated GIFs are skipped. By default, originals are backed up for restore.', 'stintlief-webp-converter' ); ?>
		</p>
		<?php
	}

	/**
	 * Render image processing settings fields.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function field_image_settings() {
		$max_w       = Utils::int_option( 'stwp_max_width', 1920 );
		$max_h       = Utils::int_option( 'stwp_max_height', 1080 );
		$quality     = Utils::int_option( 'stwp_compression_quality', 80 );
		$keep_backup = Utils::bool_option( 'stwp_keep_original_backup', true );
		$force       = Utils::bool_option( 'stwp_force_webp', false );
		?>
		<fieldset>
			<p>
				<label for="stwp_max_width"><?php esc_html_e( 'Max Width (px)', 'stintlief-webp-converter' ); ?></label><br />
				<input 
					type="number" 
					id="stwp_max_width" 
					name="stwp_max_width" 
					min="1" 
					max="9999" 
					value="<?php echo esc_attr( $max_w ); ?>" 
				/>
			</p>

			<p>
				<label for="stwp_max_height"><?php esc_html_e( 'Max Height (px)', 'stintlief-webp-converter' ); ?></label><br />
				<input 
					type="number" 
					id="stwp_max_height" 
					name="stwp_max_height" 
					min="1" 
					max="9999" 
					value="<?php echo esc_attr( $max_h ); ?>" 
				/>
			</p>

			<p>
				<label for="stwp_compression_quality"><?php esc_html_e( 'Compression Quality (1-100)', 'stintlief-webp-converter' ); ?></label><br />
				<input 
					type="number" 
					id="stwp_compression_quality" 
					name="stwp_compression_quality" 
					min="1" 
					max="100" 
					value="<?php echo esc_attr( $quality ); ?>" 
				/>
			</p>

			<p>
				<label>
					<input 
						type="checkbox" 
						name="stwp_keep_original_backup" 
						value="1" 
						<?php checked( true, $keep_backup ); ?>
					/> 
				<?php esc_html_e( 'Keep a backup of the original file (recommended).', 'stintlief-webp-converter' ); ?>
			</label>
		</p>

		<p>
			<label>
				<input 
					type="checkbox" 
					name="stwp_force_webp" 
					value="1" 
					<?php checked( true, $force ); ?>
				/> 
				<?php esc_html_e( 'Force WebP even if it is larger than the original (not recommended).', 'stintlief-webp-converter' ); ?>
	        </label>
       </p>
        </fieldset>
        <?php
    }

	/**
	 * Add restore button to attachment edit fields.
	 *
	 * @since 1.0.0
	 * @param array   $form_fields Array of fields to edit.
	 * @param WP_Post $post        The attachment post object.
	 * @return array Modified form fields.
	 */
	public static function attachment_restore_field( $form_fields, $post ) {
		// Only show for WebP attachments with backup metadata.
		$file = \get_attached_file( $post->ID );
		if ( ! $file || ! \is_string( $file ) || ! \file_exists( $file ) ) {
			return $form_fields;
		}

		$mime = \get_post_mime_type( $post->ID );
		if ( 'image/webp' !== $mime ) {
			return $form_fields;
		}

		$meta_path = $file . '.stwp.json';
		if ( ! \file_exists( $meta_path ) ) {
			return $form_fields;
		}

		$url = \wp_nonce_url(
			\admin_url( 'admin-post.php?action=stwp_restore_original&attachment_id=' . \absint( $post->ID ) ),
			'stwp_restore_original'
		);

		$form_fields['stwp_restore_original'] = array(
			'label' => \__( 'STWP', 'stintlief-webp-converter' ),
			'input' => 'html',
			'html'  => '<a class="button" href="' . \esc_url( $url ) . '">' . \esc_html__( 'Restore original file', 'stintlief-webp-converter' ) . '</a>' .
					   '<p class="description">' . \esc_html__( 'Restores the backed up original (if available) and regenerates sizes.', 'stintlief-webp-converter' ) . '</p>',
		);

		return $form_fields;
	}

	/**
	 * Process attachment field saves (currently no-op).
	 *
	 * @since 1.0.0
	 * @param array $post       Array of post data.
	 * @param array $attachment Array of attachment data.
	 * @return array Unmodified post data.
	 */
	public static function attachment_fields_to_save( $post, $attachment ) {
		return $post;
	}
}
