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

class BW_WebP_Rewrite {

	const MARKER = 'BW WebP';

	public function install(): bool {
		if ( ! $this->htaccess_writable() ) {
			return false;
		}
		require_once ABSPATH . 'wp-admin/includes/misc.php';
		return (bool) insert_with_markers( $this->htaccess_path(), self::MARKER, $this->rules() );
	}

	public function remove(): bool {
		$path = $this->htaccess_path();
		if ( ! is_writable( $path ) ) {
			return false;
		}
		require_once ABSPATH . 'wp-admin/includes/misc.php';
		return (bool) insert_with_markers( $path, self::MARKER, array() );
	}

	public function nginx_snippet(): string {
		return <<<NGX
# BW WebP — paste into your server block
map \$http_accept \$bw_webp_suffix {
    default "";
    "~*image/webp" ".webp";
}

location ~* ^(?<bwwebpbase>.+\.(jpe?g|png|gif))$ {
    add_header Vary Accept;
    try_files \$bwwebpbase\$bw_webp_suffix \$uri =404;
}
NGX;
	}

	public function htaccess_writable(): bool {
		$path = $this->htaccess_path();
		if ( file_exists( $path ) ) {
			return is_writable( $path );
		}
		return is_writable( dirname( $path ) );
	}

	public function rules(): array {
		return array(
			'<IfModule mod_rewrite.c>',
			'RewriteEngine On',
			'RewriteCond %{HTTP_ACCEPT} image/webp',
			'RewriteCond %{REQUEST_FILENAME} (?i)(.+\.(jpe?g|png|gif))$',
			'RewriteCond %{REQUEST_FILENAME}.webp -f',
			'RewriteRule ^ %{REQUEST_URI}.webp [T=image/webp,E=accept:1,L]',
			'</IfModule>',
			'<IfModule mod_headers.c>',
			'<FilesMatch "(?i)\.(jpe?g|png|gif)$">',
			'Header append Vary Accept env=accept',
			'</FilesMatch>',
			'AddType image/webp .webp',
			'</IfModule>',
		);
	}

	private function htaccess_path(): string {
		return get_home_path() . '.htaccess';
	}
}
