<?php

declare(strict_types=1);

namespace SecurWP\Modules\Firewall;

use SecurWP\Includes\IpDetector;

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

class IpBlocking {
	private array $settings;

	private ?bool $is_allowed_cache = null;
	private ?array $allowlisted_entries_cache = null;
	private ?array $active_banned_entries_cache = null;

	public function __construct( array $settings ) {
		$this->settings = FirewallSettings::sanitize( $settings );
	}

	public function is_allowed( string $ip ): bool {
		if ( $this->is_allowed_cache !== null ) {
			return $this->is_allowed_cache;
		}

		$this->is_allowed_cache = RuleEngine::find_ip_match( $ip, $this->get_allowlisted_entries() ) !== null;
		return $this->is_allowed_cache;
	}

	public function is_banned( string $ip ): bool {
		return RuleEngine::find_ip_match( $ip, $this->get_active_banned_entries() ) !== null;
	}

	/**
	 * @return array<int, string>
	 */
	public function get_allowlisted_entries(): array {
		if ( $this->allowlisted_entries_cache !== null ) {
			return $this->allowlisted_entries_cache;
		}

		$this->allowlisted_entries_cache = RuleEngine::normalize_ip_entries( (string) ( $this->settings['allowlist'] ?? '' ), true );
		return $this->allowlisted_entries_cache;
	}

	/**
	 * @return array<int, string>
	 */
	public function get_active_banned_entries(): array {
		if ( $this->active_banned_entries_cache !== null ) {
			return $this->active_banned_entries_cache;
		}

		$manager = new LockoutManager();
		if ( $manager->purge_expired_if_due() > 0 ) {
			$this->settings = FirewallSettings::sanitize( FirewallSettings::get() );
		}

		$this->active_banned_entries_cache = RuleEngine::normalize_ip_entries( (string) ( $this->settings['banned_ips'] ?? '' ), true );
		return $this->active_banned_entries_cache;
	}

	public function block_request( string $message, string $reason ): void {
		do_action( 'securwp_firewall_block', [
			'site_url' => home_url(),
			'ip' => IpDetector::get_ip(),
			'attack_type' => $reason,
			'request_uri' => IpDetector::get_server_value( 'REQUEST_URI' ),
		] );

		if ( ! headers_sent() ) {
			http_response_code( 403 );
			header( 'Content-Type: text/html; charset=UTF-8' );
			header( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0' );
		}

		require_once __DIR__ . '/block-page.php';
		securwp_render_block_page( 403, $message, IpDetector::get_ip() );
		exit;
	}
}
