<?php
/**
 * ============================================================================
 * openssl-test.php - Diagnose OpenSSL Configuration Issues
 * ============================================================================
 */

echo "<h1>OpenSSL Configuration Test</h1>";
echo "<style>
    body { font-family: monospace; padding: 20px; }
    .success { color: green; }
    .error { color: red; }
    .warning { color: orange; }
    pre { background: #f5f5f5; padding: 10px; border-left: 3px solid #333; }
</style>";

// Test 1: Check if OpenSSL extension is loaded
echo "<h2>1. OpenSSL Extension Check</h2>";
if (extension_loaded('openssl')) {
    echo "<p class='success'>✅ OpenSSL extension is LOADED</p>";
    echo "<p>Version: " . OPENSSL_VERSION_TEXT . "</p>";
} else {
    echo "<p class='error'>❌ OpenSSL extension is NOT loaded</p>";
    echo "<p><strong>Fix:</strong></p>";
    echo "<ol>
            <li>Open php.ini (usually at C:\\xampp\\php\\php.ini)</li>
            <li>Find the line: ;extension=openssl</li>
            <li>Remove the semicolon: extension=openssl</li>
            <li>Restart Apache</li>
          </ol>";
    exit;
}

// Test 2: Check OpenSSL configuration
echo "<h2>2. OpenSSL Configuration</h2>";
$config = [
    "digest_alg" => "sha512",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
];
echo "<pre>" . print_r($config, true) . "</pre>";

// Test 3: Try to generate keys with detailed error reporting
echo "<h2>3. RSA Key Generation Test</h2>";

// Clear any previous OpenSSL errors
while ($msg = openssl_error_string()) {
    // Clear error queue
}

echo "<p>Attempting to generate 2048-bit RSA key pair...</p>";

$res = openssl_pkey_new($config);

if ($res === false) {
    echo "<p class='error'>❌ Key generation FAILED</p>";
    echo "<h3>OpenSSL Errors:</h3>";
    echo "<pre>";
    while ($msg = openssl_error_string()) {
        echo "- " . $msg . "\n";
    }
    echo "</pre>";
    
    // Try to diagnose the issue
    echo "<h3>Possible Causes:</h3>";
    echo "<ol>";
    echo "<li><strong>Missing openssl.cnf file</strong>
            <ul>
                <li>Check if C:\\xampp\\apache\\conf\\openssl.cnf exists</li>
                <li>Or C:\\xampp\\php\\extras\\openssl\\openssl.cnf</li>
            </ul>
          </li>";
    echo "<li><strong>Environment variable not set</strong>
            <ul>
                <li>OPENSSL_CONF should point to openssl.cnf</li>
                <li>Try setting in Apache config or php.ini</li>
            </ul>
          </li>";
    echo "<li><strong>Permission issues</strong>
            <ul>
                <li>Check if PHP has permission to create temp files</li>
                <li>Check C:\\Windows\\Temp permissions</li>
            </ul>
          </li>";
    echo "</ol>";
    
    // Test alternative approach
    echo "<h3>Testing Alternative Configuration:</h3>";
    
    // Try with explicit config file
    $configFile = 'C:/xampp/apache/conf/openssl.cnf';
    if (file_exists($configFile)) {
        echo "<p class='success'>✅ Found openssl.cnf at: $configFile</p>";
        putenv("OPENSSL_CONF=$configFile");
        
        $res2 = openssl_pkey_new($config);
        if ($res2 === false) {
            echo "<p class='error'>❌ Still failed with explicit config</p>";
        } else {
            echo "<p class='success'>✅ SUCCESS with explicit config!</p>";
            echo "<p><strong>Solution:</strong> Add this to your generate-keys.php:</p>";
            echo "<pre>putenv('OPENSSL_CONF=$configFile');</pre>";
        }
    } else {
        echo "<p class='error'>❌ openssl.cnf not found at expected location</p>";
        echo "<p>Searching for openssl.cnf...</p>";
        
        // Search common locations
        $searchPaths = [
            'C:/xampp/apache/conf/openssl.cnf',
            'C:/xampp/php/extras/openssl/openssl.cnf',
            'C:/Program Files/OpenSSL/bin/openssl.cnf',
            'C:/OpenSSL-Win64/bin/openssl.cnf'
        ];
        
        foreach ($searchPaths as $path) {
            if (file_exists($path)) {
                echo "<p class='success'>✅ Found at: $path</p>";
            }
        }
    }
    
} else {
    echo "<p class='success'>✅ Key generation SUCCESSFUL!</p>";
    
    // Extract the private key
    $privateKey = '';
    openssl_pkey_export($res, $privateKey);
    
    // Extract the public key
    $keyDetails = openssl_pkey_get_details($res);
    $publicKey = $keyDetails["key"];
    
    echo "<h3>Generated Keys:</h3>";
    echo "<p><strong>Private Key:</strong></p>";
    echo "<pre>" . substr($privateKey, 0, 100) . "...</pre>";
    echo "<p>Length: " . strlen($privateKey) . " characters</p>";
    
    echo "<p><strong>Public Key:</strong></p>";
    echo "<pre>" . substr($publicKey, 0, 100) . "...</pre>";
    echo "<p>Length: " . strlen($publicKey) . " characters</p>";
    
    echo "<h3>✅ OpenSSL is working correctly!</h3>";
    echo "<p>The issue might be in how the Encryption class is calling OpenSSL.</p>";
}

// Test 4: Check Encryption class
echo "<h2>4. Encryption Class Test</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 {
        echo "<p>Testing Encryption::generateKeyPair()...</p>";
        $keys = \App\Encryption::generateKeyPair();
        
        if ($keys && isset($keys['public_key']) && isset($keys['private_key'])) {
            echo "<p class='success'>✅ Encryption::generateKeyPair() works!</p>";
            echo "<p>Public key length: " . strlen($keys['public_key']) . "</p>";
            echo "<p>Private key length: " . strlen($keys['private_key']) . "</p>";
        } else {
            echo "<p class='error'>❌ Encryption::generateKeyPair() returned invalid data</p>";
            echo "<pre>" . print_r($keys, true) . "</pre>";
        }
        
    } catch (Exception $e) {
        echo "<p class='error'>❌ Error: " . $e->getMessage() . "</p>";
        echo "<pre>" . $e->getTraceAsString() . "</pre>";
    }
    
} else {
    echo "<p class='error'>❌ Encryption class not found</p>";
    echo "<p>Check if classes/Encryption.php exists</p>";
}

// Test 5: Environment info
echo "<h2>5. Environment Information</h2>";
echo "<table border='1' cellpadding='5'>";
echo "<tr><th>Setting</th><th>Value</th></tr>";
echo "<tr><td>PHP Version</td><td>" . phpversion() . "</td></tr>";
echo "<tr><td>OS</td><td>" . PHP_OS . "</td></tr>";
echo "<tr><td>Temp Directory</td><td>" . sys_get_temp_dir() . "</td></tr>";
echo "<tr><td>OPENSSL_CONF</td><td>" . (getenv('OPENSSL_CONF') ?: 'Not Set') . "</td></tr>";
echo "</table>";

// Test 6: Temp directory permissions
echo "<h2>6. Temp Directory Test</h2>";
$tempDir = sys_get_temp_dir();
echo "<p>Temp directory: $tempDir</p>";

if (is_writable($tempDir)) {
    echo "<p class='success'>✅ Temp directory is writable</p>";
} else {
    echo "<p class='error'>❌ Temp directory is NOT writable</p>";
    echo "<p>This may prevent OpenSSL from creating temporary files.</p>";
}

echo "<h2>Summary</h2>";
echo "<p>Run this test to identify why OpenSSL is failing.</p>";
echo "<p>Once identified, apply the fix to your generate-keys.php file.</p>";
?>