<?php
/**
 * Security Validation Test Script
 * 
 * This script validates that all hardcoded JWT tokens and passwords
 * have been properly cleaned from admin documentation files.
 * 
 * @package Care_API
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) && php_sapi_name() !== 'cli' ) {
    exit;
}

class Care_API_Security_Validator {
    
    private $security_issues = array();
    private $files_scanned = 0;
    
    /**
     * Run security validation
     */
    public function run_validation() {
        echo "🔍 CARE API SECURITY VALIDATION\n";
        echo "==============================\n\n";
        
        $this->scan_admin_files();
        $this->scan_template_files();
        $this->scan_javascript_files();
        
        $this->report_results();
    }
    
    /**
     * Scan admin PHP files
     */
    private function scan_admin_files() {
        echo "📁 Scanning admin files...\n";
        
        $admin_files = glob( __DIR__ . '/src/admin/*.php' );
        
        foreach ( $admin_files as $file ) {
            $this->scan_file_for_security_issues( $file );
        }
    }
    
    /**
     * Scan template files
     */
    private function scan_template_files() {
        echo "📄 Scanning template files...\n";
        
        $template_files = glob( __DIR__ . '/templates/**/*.php' );
        
        foreach ( $template_files as $file ) {
            $this->scan_file_for_security_issues( $file );
        }
    }
    
    /**
     * Scan JavaScript files
     */
    private function scan_javascript_files() {
        echo "🟨 Scanning JavaScript files...\n";
        
        $js_files = glob( __DIR__ . '/src/assets/js/*.js' );
        
        foreach ( $js_files as $file ) {
            $this->scan_file_for_security_issues( $file );
        }
    }
    
    /**
     * Scan individual file for security issues
     */
    private function scan_file_for_security_issues( $file ) {
        if ( ! file_exists( $file ) ) {
            return;
        }
        
        $this->files_scanned++;
        $content = file_get_contents( $file );
        $filename = basename( $file );
        
        // Check for hardcoded JWT tokens (actual ones, not placeholders)
        if ( preg_match( '/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9\.[A-Za-z0-9+\/=]+\.[A-Za-z0-9+\/=]+/', $content ) ) {
            $this->security_issues[] = array(
                'file' => $filename,
                'type' => 'CRITICAL',
                'issue' => 'Hardcoded JWT token found',
                'details' => 'Real JWT token detected in documentation'
            );
        }
        
        // Check for specific insecure password examples
        if ( preg_match( '/[\'"]password[\'"]?\s*[:=]\s*[\'"]secure_password[\'"]/', $content ) ) {
            $this->security_issues[] = array(
                'file' => $filename,
                'type' => 'HIGH',
                'issue' => 'Insecure password example',
                'details' => 'Using "secure_password" as example password'
            );
        }
        
        // Check for specific insecure username examples
        if ( preg_match( '/[\'"]username[\'"]?\s*[:=]\s*[\'"]doctor_john[\'"]/', $content ) ) {
            $this->security_issues[] = array(
                'file' => $filename,
                'type' => 'MEDIUM',
                'issue' => 'Specific username in examples',
                'details' => 'Using "doctor_john" as example username'
            );
        }
        
        // Check for any exposed secrets or API keys
        if ( preg_match( '/[\'"]secret[\'"]?\s*[:=]\s*[\'"][A-Za-z0-9+\/=]{20,}[\'"]/', $content ) ) {
            $this->security_issues[] = array(
                'file' => $filename,
                'type' => 'CRITICAL',
                'issue' => 'Potential exposed secret',
                'details' => 'Long string that might be a secret key'
            );
        }
        
        // Check for database passwords
        if ( preg_match( '/DB_PASSWORD[\'"]?\s*[:=]\s*[\'"][^\'\"]+[\'"]/', $content ) ) {
            $this->security_issues[] = array(
                'file' => $filename,
                'type' => 'CRITICAL',
                'issue' => 'Database password exposed',
                'details' => 'Database password found in code'
            );
        }
        
        // Positive check: Verify security warnings are present in auth docs
        if ( basename( $file ) === 'class-docs-admin.php' ) {
            if ( ! strpos( $content, 'SECURITY WARNING' ) ) {
                $this->security_issues[] = array(
                    'file' => $filename,
                    'type' => 'INFO',
                    'issue' => 'Missing security warning',
                    'details' => 'Auth documentation should include security warnings'
                );
            }
        }
    }
    
    /**
     * Report validation results
     */
    private function report_results() {
        echo "\n📊 SECURITY VALIDATION RESULTS\n";
        echo "================================\n";
        echo "Files scanned: {$this->files_scanned}\n";
        echo "Issues found: " . count( $this->security_issues ) . "\n\n";
        
        if ( empty( $this->security_issues ) ) {
            echo "✅ SECURITY VALIDATION PASSED\n";
            echo "No security issues detected in documentation files.\n";
            echo "All JWT tokens and passwords use safe placeholder examples.\n";
            return;
        }
        
        echo "🚨 SECURITY ISSUES DETECTED\n";
        echo "===========================\n\n";
        
        $critical = 0;
        $high = 0;
        $medium = 0;
        $info = 0;
        
        foreach ( $this->security_issues as $issue ) {
            $icon = $this->get_severity_icon( $issue['type'] );
            echo "{$icon} {$issue['type']}: {$issue['file']}\n";
            echo "   Issue: {$issue['issue']}\n";
            echo "   Details: {$issue['details']}\n\n";
            
            switch ( $issue['type'] ) {
                case 'CRITICAL':
                    $critical++;
                    break;
                case 'HIGH':
                    $high++;
                    break;
                case 'MEDIUM':
                    $medium++;
                    break;
                case 'INFO':
                    $info++;
                    break;
            }
        }
        
        echo "📈 ISSUE SUMMARY\n";
        echo "Critical: {$critical}\n";
        echo "High: {$high}\n";
        echo "Medium: {$medium}\n";
        echo "Info: {$info}\n\n";
        
        if ( $critical > 0 || $high > 0 ) {
            echo "❌ SECURITY VALIDATION FAILED\n";
            echo "Please fix critical and high severity issues before deploying.\n";
        } else {
            echo "⚠️  SECURITY VALIDATION PASSED WITH WARNINGS\n";
            echo "Only minor issues detected. Review and fix if needed.\n";
        }
    }
    
    /**
     * Get severity icon
     */
    private function get_severity_icon( $type ) {
        switch ( $type ) {
            case 'CRITICAL':
                return '🔴';
            case 'HIGH':
                return '🟠';
            case 'MEDIUM':
                return '🟡';
            case 'INFO':
                return '🔵';
            default:
                return '⚪';
        }
    }
}

// Run validation if called directly
if ( php_sapi_name() === 'cli' ) {
    $validator = new Care_API_Security_Validator();
    $validator->run_validation();
}