<?php
/**
 * AJAX endpoints for Cache-Safe Mode.
 *
 * BUG 7 FIX: __country() was called a second time immediately after isCache()
 * already called it internally. getCacheResult() now returns the combined
 * result so the caller never needs to call evaluateCountry() again.
 *
 * @package FENSE_BPVT
 */

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

class FENSE_BPVT_Cache_Safe_Mode
{
	
	private const NONCE_ACTION = 'SaveMode-nonce';
	public FENSE_BPVT_RUN_SAVE_MODE $engine;
	private string $actionSave;
	private string $actionGet;
	
	public function __construct()
	{
		$this->actionSave = FENSE_BPVT_PLUGIN::PREFIX . 'SaveMode';
		$this->actionGet = FENSE_BPVT_PLUGIN::PREFIX . 'GetSaveMode';
		
		foreach ( [ 'SaveMode', 'GetSaveMode' ] as $method ) {
			$action = FENSE_BPVT_PLUGIN::PREFIX . $method;
			add_action( 'wp_ajax_nopriv_' . $action, [ $this, $method ] );
			add_action( 'wp_ajax_' . $action, [ $this, $method ] );
		}
	}
	
	// -----------------------------------------------------------------------
	// AJAX handlers
	// -----------------------------------------------------------------------
	public function SaveMode(): void
	{
		$this->validateRequest();
		
		$engine = new FENSE_BPVT_RUN_SAVE_MODE();
		$this->engine = $engine;
		
		$this->runPreChecks( $engine );
		$this->runLookup( $engine );
		$this->runProtection( $engine );
	}

// ─────────────────────────────────────────────
// Pre-checks: fast exits that bypass API lookup
// ─────────────────────────────────────────────
	
	private function validateRequest(): void
	{
		if ( !$this->isValidAction() ) $this->sendError( 1 );
		if ( !$this->isValidOrigin() ) $this->sendError( 2 );
		
		if ( FENSE_BPVT_FUN::runOnce() ) $this->sendSuccess( false, [ 'd' => 1 ] );
	}

// ─────────────────────────────────────────────
// Cache + whitelist/blacklist/bot shortcuts
// ─────────────────────────────────────────────
	
	private function runPreChecks( FENSE_BPVT_RUN_SAVE_MODE $engine ): void
	{
		if ( $engine->isAdminOrLoggedIn() ) $this->sendSuccess( false, [ 'd' => 2 ] );
		if ( $engine->isCrawlerBot() ) $this->sendSuccess( false, [ 'd' => 10 ] );
		if ( $engine->isDailyLimitReached() ) $this->sendSuccess( false, [ 'd' => 3 ] );
		if ( $engine->loadUserIp() === '' ) $this->sendSuccess( false, [ 'd' => 5 ] );
		
		$settings = $engine->loadSettings();
		
		if ( empty( $settings->appKey ) ) $this->sendSuccess( false, [ 'd' => 4 ] );
		if ( !$settings->enable ) $this->sendSuccess( false, [ 'd' => 6 ] );
		
		if ( !$engine->isUrlAllowed() ) $this->sendSuccess( false, [ 'd' => 7 ] );
	}

// ─────────────────────────────────────────────
// Full data load + country + protection result
// ─────────────────────────────────────────────
	
	private function runLookup( FENSE_BPVT_RUN_SAVE_MODE $engine ): void
	{
		if ( $engine->isWhitelisted() ) $this->sendSuccess( false, [ 'd' => 9 ] );
		if ( $engine->shouldSkipPageType() ) $this->sendSuccess( false, [ 'd' => 11 ] );
		
		if ( $engine->isBlacklisted() ) {
			$this->sendSuccess( true, [ 'd' => 16 ] );
		}
	}
	
	private function runProtection( FENSE_BPVT_RUN_SAVE_MODE $engine ): void
	{
		$data = $engine->loadData();
		
		
		if ( $engine->isReferrerBlocked() ) {
			$this->sendSuccess( true, [ 'd' => 12 ] );
		}
		
		if ( in_array( $data->status ?? '', [ 'Error', 'error' ], true ) ) {
			$this->sendSuccess( false, [ 'd' => 13 ] );
		}
		
		// BUG 7 FIX: getCountryResult() called once — was called twice before.
		$country = $engine->getCountryResult();
		
		if ( $country['exclude'] ) {
			$this->sendSuccess( false, [ 'd' => 17 ] );
		}
		
		if ( $country['ignoreProxy'] && !$country['exclude'] ) {
			$this->sendSuccess( true, [ 'd' => 18 ] );
		}
		
		$this->sendSuccess( $engine->isProxy(), [ 'd' => 15 ] );
	}
	
	// -----------------------------------------------------------------------
	// Response helpers
	// -----------------------------------------------------------------------
	
	private function sendSuccess( bool $isProxy = false, array $extra = [] ): void
	{
		
		$payload = array_merge(
			[ 'status' => $isProxy ],
			$this->engine->getProtectionResult(),
			$extra
		);
		
		wp_send_json_success( $payload );
	}
	
	private function sendError( int $debug = 0, int $code = 403 ): void
	{
		wp_send_json_error( [ 'status' => false, 'd' => $debug ], $code );
	}
	
	// -----------------------------------------------------------------------
	// Validation helpers
	// -----------------------------------------------------------------------
	
	private function isValidOrigin(): bool
	{
		$allowed = parse_url( home_url(), PHP_URL_HOST );
		$origin = parse_url( $_SERVER['HTTP_ORIGIN'] ?? '', PHP_URL_HOST );
		return $origin !== null && $origin === $allowed;
	}
	
	private function isValidAction(): bool
	{
		return ( $_REQUEST['action'] ?? '' ) === $this->actionSave;
	}
}

new FENSE_BPVT_Cache_Safe_Mode();
