<?php
/**
 * Standalone Security Audit Script - care-api
 *
 * Analyzes code for security vulnerabilities without requiring WordPress
 */

echo "🔒 CARE-API SECURITY AUDIT (Standalone)\n";
echo "=" . str_repeat("=", 50) . "\n\n";

class Standalone_Security_Audit {

    private $project_root;
    private $results = [];

    public function __construct($project_root = __DIR__) {
        $this->project_root = $project_root;
    }

    public function run_audit() {
        echo "🚨 ANALYZING SECURITY FIXES\n\n";

        $this->check_authentication_fixes();
        $this->check_sql_injection_fixes();
        $this->check_xss_protection();
        $this->check_security_manager();
        $this->scan_vulnerable_patterns();

        $this->print_audit_summary();
    }

    /**
     * Check authentication hardening
     */
    public function check_authentication_fixes() {
        echo "1️⃣ AUTHENTICATION HARDENING CHECK\n";
        echo str_repeat("-", 40) . "\n";

        $files_to_check = [
            'src/includes/class-api-init.php',
            'src/includes/endpoints/class-auth-endpoints.php'
        ];

        $return_true_count = 0;
        $security_manager_count = 0;

        foreach ($files_to_check as $file) {
            $full_path = $this->project_root . '/' . $file;

            if (!file_exists($full_path)) {
                echo "  ⚠️ File not found: {$file}\n";
                continue;
            }

            $content = file_get_contents($full_path);

            // Count __return_true instances
            $return_true_matches = substr_count($content, '__return_true');
            $return_true_count += $return_true_matches;

            // Count Security_Manager references
            $security_manager_matches = substr_count($content, 'Security_Manager');
            $security_manager_count += $security_manager_matches;

            echo "  📁 {$file}:\n";
            if ($return_true_matches > 0) {
                echo "    ❌ Found {$return_true_matches} __return_true vulnerabilities\n";
            } else {
                echo "    ✅ No __return_true vulnerabilities\n";
            }

            if ($security_manager_matches > 0) {
                echo "    ✅ Uses Security_Manager ({$security_manager_matches} references)\n";
            } else {
                echo "    ⚠️ No Security_Manager usage found\n";
            }
        }

        // Overall assessment
        if ($return_true_count === 0 && $security_manager_count > 0) {
            $this->results['AUTH_HARDENING'] = '✅ PASS';
            echo "\n  🎯 RESULT: Authentication properly hardened\n";
        } elseif ($return_true_count > 0) {
            $this->results['AUTH_HARDENING'] = '❌ FAIL';
            echo "\n  🚨 RESULT: {$return_true_count} authentication vulnerabilities remain\n";
        } else {
            $this->results['AUTH_HARDENING'] = '⚠️ PARTIAL';
            echo "\n  ⚠️ RESULT: Authentication needs verification\n";
        }
        echo "\n";
    }

    /**
     * Check SQL injection fixes
     */
    public function check_sql_injection_fixes() {
        echo "2️⃣ SQL INJECTION PROTECTION CHECK\n";
        echo str_repeat("-", 40) . "\n";

        $api_init_file = $this->project_root . '/src/includes/class-api-init.php';

        if (!file_exists($api_init_file)) {
            echo "  ❌ API Init file not found\n\n";
            $this->results['SQL_INJECTION'] = '❌ FAIL';
            return;
        }

        $content = file_get_contents($api_init_file);

        // Check for prepared statements
        $prepared_statements = substr_count($content, '$wpdb->prepare(');
        $direct_queries = substr_count($content, '$wpdb->query(') - $prepared_statements;

        echo "  📊 SQL Query Analysis:\n";
        echo "    ✅ Prepared statements: {$prepared_statements}\n";
        echo "    ⚠️ Direct queries: {$direct_queries}\n";

        // Check for specific vulnerabilities
        if (strpos($content, 'WHERE expires_at < NOW()') !== false) {
            echo "    ❌ Found direct NOW() usage (potential vulnerability)\n";
            $vulnerability_fixed = false;
        } else {
            echo "    ✅ No direct NOW() usage found\n";
            $vulnerability_fixed = true;
        }

        // Check for proper table name handling
        if (strpos($content, '$table_name = $wpdb->prefix') !== false) {
            echo "    ✅ Proper table name handling found\n";
            $proper_table_handling = true;
        } else {
            echo "    ⚠️ Check table name handling\n";
            $proper_table_handling = false;
        }

        // Overall assessment
        if ($prepared_statements > 0 && $vulnerability_fixed && $proper_table_handling) {
            $this->results['SQL_INJECTION'] = '✅ PASS';
            echo "\n  🎯 RESULT: SQL injection protection implemented\n";
        } elseif ($prepared_statements > 0) {
            $this->results['SQL_INJECTION'] = '⚠️ PARTIAL';
            echo "\n  ⚠️ RESULT: Basic protection but needs verification\n";
        } else {
            $this->results['SQL_INJECTION'] = '❌ FAIL';
            echo "\n  🚨 RESULT: No SQL injection protection found\n";
        }
        echo "\n";
    }

    /**
     * Check XSS protection implementation
     */
    public function check_xss_protection() {
        echo "3️⃣ XSS PROTECTION CHECK\n";
        echo str_repeat("-", 40) . "\n";

        $security_file = $this->project_root . '/src/includes/class-security-manager.php';

        if (!file_exists($security_file)) {
            echo "  ❌ Security Manager file not found\n\n";
            $this->results['XSS_PROTECTION'] = '❌ FAIL';
            return;
        }

        $content = file_get_contents($security_file);

        // Check for sanitization methods
        $sanitization_methods = [
            'sanitize_output' => strpos($content, 'sanitize_output') !== false,
            'wp_kses' => strpos($content, 'wp_kses') !== false,
            'esc_html' => strpos($content, 'esc_html') !== false,
            'esc_url' => strpos($content, 'esc_url') !== false,
            'esc_attr' => strpos($content, 'esc_attr') !== false,
            'sanitize_text_field' => strpos($content, 'sanitize_text_field') !== false
        ];

        echo "  🛡️ Sanitization Methods Check:\n";
        $implemented_methods = 0;
        foreach ($sanitization_methods as $method => $found) {
            if ($found) {
                echo "    ✅ {$method}\n";
                $implemented_methods++;
            } else {
                echo "    ❌ {$method}\n";
            }
        }

        // Overall assessment
        if ($implemented_methods >= 4) {
            $this->results['XSS_PROTECTION'] = '✅ PASS';
            echo "\n  🎯 RESULT: Comprehensive XSS protection implemented\n";
        } elseif ($implemented_methods >= 2) {
            $this->results['XSS_PROTECTION'] = '⚠️ PARTIAL';
            echo "\n  ⚠️ RESULT: Basic XSS protection, needs enhancement\n";
        } else {
            $this->results['XSS_PROTECTION'] = '❌ FAIL';
            echo "\n  🚨 RESULT: Insufficient XSS protection\n";
        }
        echo "\n";
    }

    /**
     * Check Security Manager implementation
     */
    public function check_security_manager() {
        echo "4️⃣ SECURITY MANAGER CHECK\n";
        echo str_repeat("-", 40) . "\n";

        $security_file = $this->project_root . '/src/includes/class-security-manager.php';

        if (!file_exists($security_file)) {
            echo "  ❌ Security Manager not found\n\n";
            $this->results['SECURITY_MANAGER'] = '❌ FAIL';
            return;
        }

        $content = file_get_contents($security_file);

        // Check for key security features
        $security_features = [
            'check_api_permissions' => strpos($content, 'check_api_permissions') !== false,
            'check_rate_limit' => strpos($content, 'check_rate_limit') !== false,
            'validate_csrf_token' => strpos($content, 'validate_csrf_token') !== false,
            'verify_jwt_authentication' => strpos($content, 'verify_jwt_authentication') !== false,
            'log_security_event' => strpos($content, 'log_security_event') !== false,
            'get_client_ip' => strpos($content, 'get_client_ip') !== false
        ];

        echo "  🔐 Security Features Check:\n";
        $implemented_features = 0;
        foreach ($security_features as $feature => $found) {
            if ($found) {
                echo "    ✅ {$feature}\n";
                $implemented_features++;
            } else {
                echo "    ❌ {$feature}\n";
            }
        }

        // Check file size as complexity indicator
        $file_size = filesize($security_file);
        echo "    📏 File size: " . number_format($file_size) . " bytes\n";

        // Overall assessment
        if ($implemented_features >= 5 && $file_size > 5000) {
            $this->results['SECURITY_MANAGER'] = '✅ PASS';
            echo "\n  🎯 RESULT: Comprehensive Security Manager implemented\n";
        } elseif ($implemented_features >= 3) {
            $this->results['SECURITY_MANAGER'] = '⚠️ PARTIAL';
            echo "\n  ⚠️ RESULT: Basic Security Manager, needs enhancement\n";
        } else {
            $this->results['SECURITY_MANAGER'] = '❌ FAIL';
            echo "\n  🚨 RESULT: Inadequate Security Manager\n";
        }
        echo "\n";
    }

    /**
     * Scan for remaining vulnerable patterns
     */
    public function scan_vulnerable_patterns() {
        echo "5️⃣ VULNERABILITY PATTERN SCAN\n";
        echo str_repeat("-", 40) . "\n";

        $src_dir = $this->project_root . '/src';
        $vulnerable_patterns = 0;

        if (!is_dir($src_dir)) {
            echo "  ❌ Source directory not found\n\n";
            return;
        }

        // Patterns to scan for
        $patterns = [
            '__return_true' => 'Authentication bypass',
            'DELETE FROM.*NOW()' => 'SQL injection potential',
            'echo \\$' => 'Potential XSS',
            'print \\$' => 'Potential XSS',
            '\\$_GET\\[' => 'Unvalidated input',
            '\\$_POST\\[' => 'Unvalidated input'
        ];

        foreach ($patterns as $pattern => $description) {
            $matches = $this->scan_pattern_in_directory($src_dir, $pattern);

            if ($matches > 0) {
                echo "  ⚠️ {$description}: {$matches} matches\n";
                $vulnerable_patterns += $matches;
            } else {
                echo "  ✅ {$description}: Clean\n";
            }
        }

        // Overall vulnerability assessment
        if ($vulnerable_patterns === 0) {
            $this->results['VULNERABILITY_SCAN'] = '✅ PASS';
            echo "\n  🎯 RESULT: No vulnerable patterns detected\n";
        } elseif ($vulnerable_patterns <= 5) {
            $this->results['VULNERABILITY_SCAN'] = '⚠️ PARTIAL';
            echo "\n  ⚠️ RESULT: {$vulnerable_patterns} potential issues found\n";
        } else {
            $this->results['VULNERABILITY_SCAN'] = '❌ FAIL';
            echo "\n  🚨 RESULT: {$vulnerable_patterns} vulnerable patterns found\n";
        }
        echo "\n";
    }

    /**
     * Scan for pattern in directory
     */
    private function scan_pattern_in_directory($dir, $pattern) {
        $matches = 0;

        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dir)
        );

        foreach ($iterator as $file) {
            if ($file->isFile() && $file->getExtension() === 'php') {
                $content = file_get_contents($file->getPathname());
                $matches += preg_match_all('/' . $pattern . '/i', $content);
            }
        }

        return $matches;
    }

    /**
     * Print audit summary
     */
    public function print_audit_summary() {
        echo "📊 SECURITY AUDIT SUMMARY\n";
        echo str_repeat("=", 50) . "\n";

        $passed = 0;
        $failed = 0;
        $partial = 0;

        foreach ($this->results as $test => $status) {
            echo "{$status} {$test}\n";

            if (strpos($status, '✅') !== false) {
                $passed++;
            } elseif (strpos($status, '❌') !== false) {
                $failed++;
            } else {
                $partial++;
            }
        }

        echo "\nRESULTS:\n";
        echo "✅ Passed: {$passed}\n";
        echo "⚠️ Partial: {$partial}\n";
        echo "❌ Failed: {$failed}\n\n";

        $total_tests = count($this->results);
        if ($total_tests > 0) {
            $score = round(($passed + ($partial * 0.5)) / $total_tests * 100, 1);

            echo "🏆 SECURITY SCORE: {$score}/100\n";

            if ($score >= 90) {
                echo "🟢 EXCELLENT - Production ready\n";
            } elseif ($score >= 75) {
                echo "🟡 GOOD - Minor issues remain\n";
            } elseif ($score >= 50) {
                echo "🟠 FAIR - Major improvements needed\n";
            } else {
                echo "🔴 CRITICAL - Not suitable for production\n";
            }
        }

        echo "\n📋 NEXT STEPS:\n";
        if ($failed > 0) {
            echo "1. Address failed security checks immediately\n";
        }
        if ($partial > 0) {
            echo "2. Complete partial implementations\n";
        }
        echo "3. Run penetration testing\n";
        echo "4. Implement security monitoring\n";
    }
}

// Run the audit
$audit = new Standalone_Security_Audit();
$audit->run_audit();