<?php

declare(strict_types=1);

namespace SecurWP\Includes;

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

/**
 * Shared protection helpers for the plugin-owned runtime storage directory.
 */
class DataDirectoryProtection {

	private const DATA_DIR_NAME = 'securwp-data';

	public static function get_data_dir_path(): string {
		return WP_CONTENT_DIR . '/' . self::DATA_DIR_NAME;
	}

	public static function get_public_path(): ?string {
		return SitePathResolver::get_content_public_path( self::DATA_DIR_NAME . '/' );
	}

	public static function get_local_htaccess_contents(): string {
		return implode(
			"\n",
			[
				'<IfModule mod_authz_core.c>',
				'Require all denied',
				'</IfModule>',
				'<IfModule mod_litespeed.c>',
				'Order Deny,Allow',
				'Deny from all',
				'</IfModule>',
				'<IfModule !mod_authz_core.c>',
				'  <IfModule !mod_litespeed.c>',
				'    Order Deny,Allow',
				'    Deny from all',
				'  </IfModule>',
				'</IfModule>',
				'',
			]
		);
	}

	public static function ensure_local_protection( string $dir ): bool {
		if ( ! is_dir( $dir ) && ! wp_mkdir_p( $dir ) ) {
			return false;
		}

		$index_contents = "<?php\n// Silence is golden.\n";
		$index = trailingslashit( $dir ) . 'index.php';
		$current_index = @file_get_contents( $index );
		if ( ! is_string( $current_index ) || self::normalize_contents( $current_index ) !== self::normalize_contents( $index_contents ) ) {
			@file_put_contents( $index, $index_contents ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
		}

		if ( self::server_honors_htaccess() ) {
			$htaccess = trailingslashit( $dir ) . '.htaccess';
			$desired_htaccess = self::get_local_htaccess_contents();
			$current_htaccess = @file_get_contents( $htaccess );
			if ( ! is_string( $current_htaccess ) || self::normalize_contents( $current_htaccess ) !== self::normalize_contents( $desired_htaccess ) ) {
				@file_put_contents( $htaccess, $desired_htaccess ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			}
		}

		return true;
	}

	private static function server_honors_htaccess(): bool {
		if ( ! class_exists( ServerConfigWriter::class ) ) {
			return true;
		}
		return 'nginx' !== ServerConfigWriter::detect_server();
	}

	private static function normalize_contents( string $contents ): string {
		return preg_replace( "/\R/u", "\n", trim( $contents ) ) ?? trim( $contents );
	}

	public static function get_htaccess_rules(): string {
		$public_path = self::get_public_path();
		if ( ! is_string( $public_path ) || $public_path === '' ) {
			return '';
		}

		$relative = trim( SitePathResolver::get_site_relative_path( $public_path ), '/' );
		$relative = trim( $relative, '/' );
		if ( $relative === '' ) {
			return '';
		}

		$relative_regex = preg_quote( $relative, '#' );

		return implode(
			"\n",
			[
				'',
				'# Protect SecurWP runtime storage',
				'<IfModule mod_rewrite.c>',
				'RewriteEngine On',
				"RewriteRule ^{$relative_regex}(?:$|/) - [F,L]",
				'</IfModule>',
				'',
			]
		);
	}

	public static function get_nginx_rules(): string {
		$public_path = self::get_public_path();
		if ( ! is_string( $public_path ) || $public_path === '' ) {
			return '';
		}

		$normalized = SitePathResolver::normalize_request_path( $public_path, true );
		if ( $normalized === '/' ) {
			return '';
		}

		$exact = untrailingslashit( $normalized );

		return implode(
			"\n",
			[
				'',
				'# Protect SecurWP runtime storage',
				"location = {$exact} {",
				'  return 403;',
				'}',
				"location ^~ {$normalized} {",
				'  return 403;',
				'}',
				'',
			]
		);
	}
}
