<?php

declare(strict_types=1);

namespace SiteFort\Includes;

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

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

	private const DATA_DIR_NAME = 'sitefort-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 ( ! FilesystemMutation::ensure_directory( $dir ) ) {
			return false;
		}

		$index_contents = "<?php\n// Silence is golden.\n";
		$index = trailingslashit( $dir ) . 'index.php';
		$current_index = FilesystemMutation::read_file_contents( $index );
		if ( ! is_string( $current_index ) || self::normalize_contents( $current_index ) !== self::normalize_contents( $index_contents ) ) {
			FilesystemMutation::write_bytes_to_file( $index, $index_contents, 0644 );
		}

		if ( self::server_honors_htaccess() ) {
			$htaccess = trailingslashit( $dir ) . '.htaccess';
			$desired_htaccess = self::get_local_htaccess_contents();
			$current_htaccess = FilesystemMutation::read_file_contents( $htaccess );
			if ( ! is_string( $current_htaccess ) || self::normalize_contents( $current_htaccess ) !== self::normalize_contents( $desired_htaccess ) ) {
				FilesystemMutation::write_bytes_to_file( $htaccess, $desired_htaccess, 0644 );
			}
		}

		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 SiteFort 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 SiteFort runtime storage',
				"location = {$exact} {",
				'  return 403;',
				'}',
				"location ^~ {$normalized} {",
				'  return 403;',
				'}',
				'',
			]
		);
	}
}
