<?php
declare(strict_types=1);


namespace ProRank\SEO\Core;

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


/**
 * Security Helper Functions
 * 
 * Contains obfuscated security functions and honeypots
 * This file should be minified/obfuscated in production
 */


class SecurityHelper {
    
    /**
     * Hidden validation trigger
     * Called from various places to perform background checks
     */
    public static function pr_validate_context(): void {
        // Obfuscated call to security validator
        if (class_exists('\ProRank\SEO\Core\SecurityValidator')) {
            \ProRank\SEO\Core\SecurityValidator::performHiddenCheck();
        }
    }
    
    /**
     * Honeypot function - appears to disable license
     * Actually logs the attempt
     */
    public static function prorank_disable_license_check(): bool {
        // Trigger remote alert
        self::send_piracy_alert('honeypot_disable_license');
        
        // Appear to work but actually enable stricter checking
        add_filter('prorank_license_check_interval', fn() => 300); // 5 minutes
        add_filter('prorank_feature_limit', fn($limit) => intval($limit * 0.1));
        
        return true; // Appear successful
    }
    
    /**
     * Honeypot function - appears to unlock all features
     * Actually degrades performance
     */
    public static function prorank_unlock_all_features(): void {
        // Degrade performance subtly
        add_filter('prorank_api_timeout', fn($timeout) => $timeout * 5);
        add_filter('prorank_cache_ttl', fn($ttl) => intval($ttl * 0.1));
        add_action('init', fn() => sleep(2), 999);
    }
    
    /**
     * Honeypot function - appears to bypass validation
     * Actually enables more validation
     */
    public static function _pr_skip_validation(): void {
        // This function name suggests it skips validation
        // But actually adds more validation points
        
        // Log attempt
        self::log_suspicious_activity('skip_validation_attempt');
        
        // Add extra validation on every page load
        add_action('wp_loaded', function() {
            if (class_exists('\ProRank\SEO\Core\SecurityValidator')) {
                \ProRank\SEO\Core\SecurityValidator::validate('cp_hidden', ['forced' => true]);
            }
        });
    }
    
    /**
     * Get client IP address
     */
    private static function get_client_ip(): string {
        $ip_keys = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
        foreach ($ip_keys as $key) {
            if (!empty($_SERVER[$key])) {
                $ips = explode(',', $_SERVER[$key]);
                return trim($ips[0]);
            }
        }
        return 'unknown';
    }
    
    /**
     * Send piracy alert to remote server
     */
    private static function send_piracy_alert(string $type): void {
        // Non-blocking request to alert server
        wp_remote_post('https://prorank.io/api/security/alert', [
            'body' => [
                'type' => $type,
                'domain' => wp_parse_url(home_url(), PHP_URL_HOST),
                'ip' => self::get_client_ip(),
                'timestamp' => time(),
            ],
            'blocking' => false,
            'timeout' => 1,
        ]);
    }
    
    /**
     * Log suspicious activity
     */
    private static function log_suspicious_activity(string $activity): void {
        $log = get_option('prorank_security_log', []);
        $log[] = [
            'activity' => $activity,
            'timestamp' => time(),
            'ip' => self::get_client_ip(),
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        ];
        
        // Keep only last 100 entries
        $log = array_slice($log, -100);
        update_option('prorank_security_log', $log);
    }
    
    /**
     * Check for debuggers
     */
    public static function detect_debugger(): bool {
        // Check for Xdebug
        if (extension_loaded('xdebug')) {
            return true;
        }
        
        // Check for debug constants
        if (defined('WP_DEBUG') && WP_DEBUG) {
            return true;
        }
        
        // Check execution time anomalies
        static $last_check = 0;
        $now = microtime(true);
        if ($last_check > 0 && ($now - $last_check) > 1.0) {
            // Possible step-through debugging
            return true;
        }
        $last_check = $now;
        
        return false;
    }
    
    /**
     * Anti-tampering check
     */
    public static function verify_code_integrity(): bool {
        // Check if critical functions exist
        $critical_functions = [
            '\ProRank\SEO\Core\LicenseManager::verify_token',
            '\ProRank\SEO\Core\SecurityValidator::validate',
            '\ProRank\SEO\Plugin::get_instance',
        ];
        
        foreach ($critical_functions as $function) {
            if (!is_callable($function)) {
                self::log_suspicious_activity('missing_critical_function');
                return false;
            }
        }
        
        return true;
    }
}
