<?php
/**
 * Registers FENSE_BPVT_detection() on the relevant WordPress hooks.
 *
 *
 * @package FENSE_BPVT
 */

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

add_action( 'wp', 'FENSE_BPVT_detection', 0 );
add_action( 'login_init', 'FENSE_BPVT_detection', 0 );
add_action( 'login_form', 'FENSE_BPVT_detection', 0 );

function FENSE_BPVT_detection(): void
{
	$run = new FENSE_BPVT_RUN();
	
	// BUG 2
	if ( __FENSE_BPVT_isDetected( $run ) ) return;
	
	if ( $run->isWhitelisted() ) return;
	
	// Blacklisted IPs skip the API and go straight to the protection mode.
	if ( $run->isBlacklisted() ) {
		$run->applyProtectionMode( true );
		return;
	}
	
	if ( $run->shouldSkipPageType() ) return;
	
	
	$data = $run->loadData();
	
	if ( $run->isReferrerBlocked() ) {
		$run->applyReferrerBlock();
		return;
	}
	
	if ( in_array( $data->status ?? '', [ 'Error', 'error' ], true ) ) return;
	
	
	$country = $run->evaluateCountry();
	
	$run->applyProtectionMode( $country['ignoreProxy'], $country['exclude'] );
}

function __FENSE_BPVT_isDetected( FENSE_BPVT_RUN $run ): bool
{
	if ( $run->isAjaxCall() ) return true;
	
	if ( $run->isAdminOrLoggedIn() ) return true;
	
	if ( FENSE_BPVT_FUN::runOnce() ) return true;
	
	if ( $run->isCrawlerBot() ) return true;
	
	if ( $run->isDailyLimitReached() ) return true;
	
	if ( $run->loadUserIp() === '' ) return true;
	
	$settings = $run->loadSettings();
	
	if ( empty( $settings->appKey ) ) return true;
	if ( !$settings->enable ) return true;
	
	
	if ( $settings->cache_safe_mode && ( $GLOBALS['pagenow'] ?? '' ) !== 'wp-login.php' ) {
		return true;
	}
	
	if ( !$run->isUrlAllowed() ) return true;
	
	return false;
}

add_action( 'wp_head', function () {
	echo "\n<!-- Site protected by Fense VPN & Proxy Blocker - https://fense.in/ -->\n";
}, 1 );
