<?php
/**
 * ============================================================================
 * verify-fix.php - Test if OpenSSL fix works
 * ============================================================================
 */

echo "<h1>Verify OpenSSL Fix</h1>";
echo "<style>
    body { font-family: monospace; padding: 20px; }
    .success { color: green; font-weight: bold; }
    .error { color: red; font-weight: bold; }
    pre { background: #f5f5f5; padding: 10px; }
</style>";

// Step 1: Set the correct path
putenv('OPENSSL_CONF=C:/Server/xampp/apache/conf/openssl.cnf');

echo "<h2>Step 1: Check OpenSSL Config Path</h2>";
$configPath = 'C:/Server/xampp/apache/conf/openssl.cnf';

if (file_exists($configPath)) {
    echo "<p class='success'>✅ Config file exists: $configPath</p>";
} else {
    echo "<p class='error'>❌ Config file NOT found: $configPath</p>";
    echo "<p>Checking alternative locations...</p>";
    
    $alternatives = [
        'C:/Server/xampp/apache/conf/extra/openssl.cnf',
        'C:/Server/xampp/php/extras/openssl/openssl.cnf',
        'C:/Server/xampp/share/openssl/openssl.cnf'
    ];
    
    foreach ($alternatives as $alt) {
        if (file_exists($alt)) {
            echo "<p class='success'>✅ Found at: $alt</p>";
            putenv("OPENSSL_CONF=$alt");
            $configPath = $alt;
            break;
        }
    }
}

// Step 2: Test key generation
echo "<h2>Step 2: Test RSA Key Generation</h2>";

$config = [
    "digest_alg" => "sha512",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
];

// Clear errors
while ($msg = openssl_error_string()) {}

echo "<p>Generating 2048-bit RSA key pair...</p>";

$res = openssl_pkey_new($config);

if ($res === false) {
    echo "<p class='error'>❌ Key generation FAILED</p>";
    echo "<h3>Errors:</h3><pre>";
    while ($msg = openssl_error_string()) {
        echo $msg . "\n";
    }
    echo "</pre>";
    
    echo "<h3>❌ FIX DID NOT WORK</h3>";
    echo "<p>The openssl.cnf file might not exist at the specified location.</p>";
    echo "<p>Please check if the file exists manually.</p>";
    
} else {
    echo "<p class='success'>✅ Key generation SUCCESSFUL!</p>";
    
    // Extract keys
    $privateKey = '';
    openssl_pkey_export($res, $privateKey);
    
    $keyDetails = openssl_pkey_get_details($res);
    $publicKey = $keyDetails["key"];
    
    echo "<p>✅ Private key length: " . strlen($privateKey) . " bytes</p>";
    echo "<p>✅ Public key length: " . strlen($publicKey) . " bytes</p>";
    
    echo "<h3 class='success'>✅✅✅ SUCCESS! OpenSSL is now working!</h3>";
    
    echo "<hr>";
    echo "<h2>Next Steps:</h2>";
    echo "<ol>";
    echo "<li><strong>Replace</strong> <code>classes/Encryption.php</code> with <code>Encryption-FINAL.php</code></li>";
    echo "<li><strong>Replace</strong> <code>chat/ajax/generate-keys.php</code> with <code>generate-keys-FINAL.php</code></li>";
    echo "<li><strong>Replace</strong> <code>chat/index.php</code> with <code>chat-index-sweetalert.php</code></li>";
    echo "<li><strong>Restart Apache</strong></li>";
    echo "<li><strong>Try encryption setup again</strong> - it should work now!</li>";
    echo "</ol>";
}

// Step 3: Test Encryption class
echo "<h2>Step 3: Test Encryption Class</h2>";

define('AIMS_ACCESS', true);
require_once __DIR__ . '/config/config.php';

if (class_exists('\App\Encryption')) {
    echo "<p class='success'>✅ Encryption class found</p>";
    
    try {
        $keys = \App\Encryption::generateKeyPair();
        
        if ($keys && isset($keys['public_key']) && isset($keys['private_key'])) {
            echo "<p class='success'>✅ Encryption::generateKeyPair() works!</p>";
            
            // Test password encryption
            $testPassword = "Test1234";
            $encrypted = \App\Encryption::encryptPrivateKey($keys['private_key'], $testPassword);
            
            if ($encrypted && isset($encrypted['encrypted_key'])) {
                echo "<p class='success'>✅ Private key encryption works!</p>";
                
                // Test decryption
                $decrypted = \App\Encryption::decryptPrivateKey($encrypted, $testPassword);
                
                if ($decrypted && $decrypted === $keys['private_key']) {
                    echo "<p class='success'>✅ Private key decryption works!</p>";
                    echo "<h3 class='success'>🎉🎉🎉 ALL TESTS PASSED! 🎉🎉🎉</h3>";
                    echo "<p>Your encryption system is fully functional!</p>";
                } else {
                    echo "<p class='error'>❌ Decryption failed</p>";
                }
            } else {
                echo "<p class='error'>❌ Password encryption failed</p>";
            }
            
        } else {
            echo "<p class='error'>❌ Encryption::generateKeyPair() failed</p>";
            echo "<pre>" . print_r($keys, true) . "</pre>";
        }
        
    } catch (Exception $e) {
        echo "<p class='error'>❌ Error: " . $e->getMessage() . "</p>";
    }
    
} else {
    echo "<p class='error'>❌ Encryption class not found</p>";
}

echo "<hr>";
echo "<h2>Environment Info</h2>";
echo "<table border='1' cellpadding='5'>";
echo "<tr><td>OPENSSL_CONF</td><td>" . getenv('OPENSSL_CONF') . "</td></tr>";
echo "<tr><td>OpenSSL Version</td><td>" . OPENSSL_VERSION_TEXT . "</td></tr>";
echo "<tr><td>PHP Version</td><td>" . phpversion() . "</td></tr>";
echo "</table>";
?>