<?php
defined( 'ABSPATH' ) || exit;

class BW_WebP_Converter_Gd implements BW_WebP_Converter {

	public static function is_available(): bool {
		return function_exists( 'imagewebp' )
			&& function_exists( 'imagecreatefromjpeg' )
			&& function_exists( 'imagecreatefrompng' );
	}

	public function name(): string {
		return 'gd';
	}

	public function convert( string $src, string $dest, int $quality ): void {
		bw_webp_assert_safe_paths( $src, $dest );

		$quality = max( 1, min( 100, $quality ) );

		$mime = wp_check_filetype( $src )['type'] ?? '';
		$image = $this->load( $src, $mime );

		if ( false === $image ) {
			throw new RuntimeException( 'GD: failed to load source' );
		}

		try {
			if ( in_array( $mime, array( 'image/png', 'image/gif' ), true ) ) {
				imagepalettetotruecolor( $image );
				imagealphablending( $image, false );
				imagesavealpha( $image, true );
			}

			$ok = imagewebp( $image, $dest, $quality );
			if ( ! $ok ) {
				throw new RuntimeException( 'GD: imagewebp returned false' );
			}
		} finally {
			imagedestroy( $image );
		}

		if ( ! is_file( $dest ) || filesize( $dest ) === 0 ) {
			throw new RuntimeException( 'GD: destination missing or empty after run' );
		}
	}

	private function load( string $src, string $mime ) {
		switch ( $mime ) {
			case 'image/jpeg':
				return imagecreatefromjpeg( $src );
			case 'image/png':
				return imagecreatefrompng( $src );
			case 'image/gif':
				return imagecreatefromgif( $src );
		}
		throw new RuntimeException( 'GD: unsupported source mime: ' . $mime );
	}
}
