<?php
echo "<h1>🔑 Generate APP_KEY</h1>";
echo "<style>body{font-family:Arial,sans-serif;margin:20px;} .success{color:green;font-weight:bold;} .error{color:red;font-weight:bold;} .info{color:blue;}</style>";

$envFile = '../.env';

if (file_exists($envFile)) {
    echo "<p class='info'>Reading current .env file...</p>";

    $envContent = file_get_contents($envFile);

    // Generate new APP_KEY
    $newKey = 'base64:' . base64_encode(random_bytes(32));
    echo "<p><strong>New APP_KEY generated:</strong> " . substr($newKey, 0, 20) . "...</p>";

    // Replace existing APP_KEY or add new one
    if (preg_match('/^APP_KEY=.*/m', $envContent)) {
        $envContent = preg_replace('/^APP_KEY=.*/m', "APP_KEY=$newKey", $envContent);
        echo "<p class='success'>✅ Existing APP_KEY replaced</p>";
    } else {
        $envContent .= "\nAPP_KEY=$newKey\n";
        echo "<p class='success'>✅ New APP_KEY added</p>";
    }

    // Save the updated .env
    if (file_put_contents($envFile, $envContent)) {
        echo "<p class='success'>✅ .env file updated successfully</p>";
    } else {
        echo "<p class='error'>❌ Failed to update .env file</p>";
    }

    // Verify the key was saved
    $savedContent = file_get_contents($envFile);
    if (strpos($savedContent, $newKey) !== false) {
        echo "<p class='success'>✅ APP_KEY verification passed</p>";
    } else {
        echo "<p class='error'>❌ APP_KEY verification failed</p>";
    }

} else {
    echo "<p class='error'>❌ .env file not found</p>";
}

echo "<h2>Test Laravel with New Key</h2>";
try {
    require_once '../vendor/autoload.php';
    $app = require_once '../bootstrap/app.php';
    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    echo "<p class='success'>✅ Laravel bootstrap successful with new APP_KEY</p>";

    // Test encryption/decryption
    $testString = 'test_encryption_' . time();
    $encrypted = encrypt($testString);
    $decrypted = decrypt($encrypted);

    if ($decrypted === $testString) {
        echo "<p class='success'>✅ Encryption/Decryption working correctly</p>";
    } else {
        echo "<p class='error'>❌ Encryption/Decryption failed</p>";
    }

} catch (Exception $e) {
    echo "<p class='error'>❌ Laravel test failed: " . $e->getMessage() . "</p>";
}

echo "<h2>Next Steps</h2>";
echo "<p class='info'>APP_KEY has been generated. Clear application cache and try accessing your Laravel app again.</p>";
echo "<p><a href='clear_all_cache.php'>Clear All Cache →</a></p>";
echo "<p><a href='debug_500.php'>← Back to Debug Page</a></p>";
?>
