<?php
/**
 * ============================================================================
 * auto-fix-openssl.php - Automatically Fix OpenSSL Configuration
 * ============================================================================
 */

echo "<h1>Auto-Fix OpenSSL Configuration</h1>";
echo "<style>
    body { font-family: Arial, sans-serif; padding: 20px; max-width: 800px; }
    .success { color: green; font-weight: bold; }
    .error { color: red; font-weight: bold; }
    .warning { color: orange; font-weight: bold; }
    pre { background: #f5f5f5; padding: 10px; border-left: 3px solid #333; }
    .step { background: #e3f2fd; padding: 15px; margin: 10px 0; border-radius: 5px; }
</style>";

$sourceFile = 'C:/Server/xampp/apache/conf/openssl.cnf';
$targetFile = 'C:/Server/xampp/apache/bin/openssl.cnf';

echo "<div class='step'>";
echo "<h2>Step 1: Check Source File</h2>";

if (file_exists($sourceFile)) {
    echo "<p class='success'>✅ Source file exists: $sourceFile</p>";
    $sourceSize = filesize($sourceFile);
    echo "<p>File size: " . number_format($sourceSize) . " bytes</p>";
} else {
    echo "<p class='error'>❌ Source file NOT found: $sourceFile</p>";
    echo "<p>Cannot proceed without source file.</p>";
    echo "<h3>Possible Solutions:</h3>";
    echo "<ol>";
    echo "<li>Reinstall XAMPP</li>";
    echo "<li>Download openssl.cnf from a working XAMPP installation</li>";
    echo "<li>Generate a new openssl.cnf using OpenSSL command line</li>";
    echo "</ol>";
    exit;
}
echo "</div>";

echo "<div class='step'>";
echo "<h2>Step 2: Check Target Directory</h2>";

$targetDir = dirname($targetFile);
if (is_dir($targetDir)) {
    echo "<p class='success'>✅ Target directory exists: $targetDir</p>";
} else {
    echo "<p class='error'>❌ Target directory NOT found: $targetDir</p>";
    exit;
}

if (is_writable($targetDir)) {
    echo "<p class='success'>✅ Target directory is writable</p>";
} else {
    echo "<p class='error'>❌ Target directory is NOT writable</p>";
    echo "<p><strong>Solution:</strong> Run this script as Administrator, or manually copy the file.</p>";
    echo "<p><strong>Manual Copy Command:</strong></p>";
    echo "<pre>copy \"$sourceFile\" \"$targetFile\"</pre>";
    exit;
}
echo "</div>";

echo "<div class='step'>";
echo "<h2>Step 3: Copy File</h2>";

if (file_exists($targetFile)) {
    echo "<p class='warning'>⚠️ Target file already exists</p>";
    echo "<p>Checking if it's the same...</p>";
    
    $sourceContent = file_get_contents($sourceFile);
    $targetContent = file_get_contents($targetFile);
    
    if ($sourceContent === $targetContent) {
        echo "<p class='success'>✅ Files are identical - no copy needed</p>";
    } else {
        echo "<p class='warning'>⚠️ Files are different - will overwrite</p>";
        
        // Backup existing file
        $backupFile = $targetFile . '.backup.' . date('Y-m-d_H-i-s');
        if (copy($targetFile, $backupFile)) {
            echo "<p class='success'>✅ Backed up existing file to: $backupFile</p>";
        }
        
        // Copy new file
        if (copy($sourceFile, $targetFile)) {
            echo "<p class='success'>✅ Successfully copied openssl.cnf to bin directory</p>";
        } else {
            echo "<p class='error'>❌ Failed to copy file</p>";
            echo "<p>Error: " . error_get_last()['message'] . "</p>";
            exit;
        }
    }
} else {
    echo "<p>Target file doesn't exist, creating...</p>";
    
    if (copy($sourceFile, $targetFile)) {
        echo "<p class='success'>✅ Successfully copied openssl.cnf to bin directory</p>";
    } else {
        echo "<p class='error'>❌ Failed to copy file</p>";
        echo "<p>Error: " . error_get_last()['message'] . "</p>";
        
        echo "<h3>Manual Copy Instructions:</h3>";
        echo "<ol>";
        echo "<li>Open Command Prompt as Administrator</li>";
        echo "<li>Run this command:</li>";
        echo "</ol>";
        echo "<pre>copy \"$sourceFile\" \"$targetFile\"</pre>";
        exit;
    }
}
echo "</div>";

echo "<div class='step'>";
echo "<h2>Step 4: Test OpenSSL</h2>";

// Set environment variable
putenv("OPENSSL_CONF=$targetFile");

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

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

echo "<p>Testing RSA key generation...</p>";

$res = openssl_pkey_new($config);

if ($res === false) {
    echo "<p class='error'>❌ Key generation still FAILED</p>";
    echo "<pre>";
    while ($msg = openssl_error_string()) {
        echo $msg . "\n";
    }
    echo "</pre>";
    
    echo "<h3>Additional Steps Needed:</h3>";
    echo "<ol>";
    echo "<li>Restart Apache in XAMPP Control Panel</li>";
    echo "<li>Run this script again</li>";
    echo "<li>If still failing, check Apache httpd.conf for OPENSSL_CONF setting</li>";
    echo "</ol>";
    
} else {
    echo "<p class='success'>✅ RSA key generation SUCCESSFUL!</p>";
    
    $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 "<h2 class='success'>🎉 SUCCESS! OpenSSL is now working! 🎉</h2>";
}
echo "</div>";

echo "<div class='step'>";
echo "<h2>Step 5: Next Steps</h2>";

echo "<ol>";
echo "<li><strong>Restart Apache</strong> in XAMPP Control Panel</li>";
echo "<li>Go to your chat: <a href='/aims/chat/'>http://localhost/aims/chat/</a></li>";
echo "<li>Click \"Setup Now\" to generate encryption keys</li>";
echo "<li>Should work now! ✅</li>";
echo "</ol>";

echo "<h3>Files Modified:</h3>";
echo "<ul>";
echo "<li>Created: <code>$targetFile</code></li>";
if (isset($backupFile)) {
    echo "<li>Backup: <code>$backupFile</code></li>";
}
echo "</ul>";

echo "<h3>To Undo (if needed):</h3>";
echo "<pre>del \"$targetFile\"</pre>";

echo "</div>";

echo "<hr>";
echo "<p><a href='verify-fix.php'>Run Verification Test</a></p>";
?>