<?php
echo "<h1>🔑 FIX APP_KEY - ENCRYPTION ERROR</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;} code{background:#f5f5f5;padding:2px 4px;border-radius:3px;}</style>";

// Initialize Laravel first
try {
    require_once '../vendor/autoload.php';
    $app = require_once '../bootstrap/app.php';
    $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
    $kernel->bootstrap();
    echo "<p class='success'>✅ Laravel initialized successfully</p>";
} catch (Exception $e) {
    echo "<p class='error'>❌ Failed to initialize Laravel: " . $e->getMessage() . "</p>";
    exit;
}

$envFile = '../.env';

echo "<h2>🔍 Current APP_KEY Status</h2>";

// Read current .env
if (file_exists($envFile)) {
    $envContent = file_get_contents($envFile);

    // Find APP_KEY
    if (preg_match('/^APP_KEY=(.+)$/m', $envContent, $matches)) {
        $currentKey = trim($matches[1]);
        echo "<p><strong>Current APP_KEY:</strong> <code>$currentKey</code></p>";

        // Test the key using Laravel
        try {
            $encrypter = app('encrypter');
            echo "<p class='success'>✅ Current APP_KEY is valid (Laravel can initialize encrypter)</p>";
        } catch (Exception $e) {
            echo "<p class='error'>❌ Current APP_KEY is INVALID: " . $e->getMessage() . "</p>";
            echo "<p class='info'>🔄 Generating new APP_KEY...</p>";

            // Generate new key using Laravel
            $newKey = 'base64:' . base64_encode(\Illuminate\Support\Str::random(32));
            echo "<p><strong>New APP_KEY generated:</strong> <code>$newKey</code></p>";

            // Replace in .env
            $envContent = preg_replace('/^APP_KEY=.*/m', "APP_KEY=$newKey", $envContent);

            if (file_put_contents($envFile, $envContent)) {
                echo "<p class='success'>✅ APP_KEY updated in .env file</p>";

                // Clear config cache to reload new key
                try {
                    \Illuminate\Support\Facades\Artisan::call('config:clear');
                    echo "<p class='success'>✅ Config cache cleared</p>";
                } catch (Exception $cacheException) {
                    echo "<p class='warning'>⚠️ Could not clear config cache: " . $cacheException->getMessage() . "</p>";
                }

                // Test new key by trying to get encrypter again
                try {
                    // We need to restart Laravel with new config
                    echo "<p class='info'>🔄 Reloading Laravel with new APP_KEY...</p>";
                    echo "<p class='success'>✅ APP_KEY updated - please refresh this page to test</p>";
                } catch (Exception $e2) {
                    echo "<p class='error'>❌ Error testing new APP_KEY: " . $e2->getMessage() . "</p>";
                }

            } else {
                echo "<p class='error'>❌ Failed to update .env file</p>";
            }
        }

    } else {
        echo "<p class='error'>❌ APP_KEY not found in .env file</p>";
        echo "<p class='info'>🔄 Adding APP_KEY to .env file...</p>";

        // Generate and add new key
        $newKey = 'base64:' . base64_encode(\Illuminate\Support\Str::random(32));
        $envContent .= "\nAPP_KEY=$newKey\n";

        if (file_put_contents($envFile, $envContent)) {
            echo "<p class='success'>✅ APP_KEY added to .env file</p>";
            echo "<p><strong>Generated APP_KEY:</strong> <code>$newKey</code></p>";
        } else {
            echo "<p class='error'>❌ Failed to add APP_KEY to .env file</p>";
        }
    }

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

echo "<h2>🧪 Test Encryption System</h2>";
try {
    // Test Laravel encryption using current setup
    $testData = 'test_encryption_' . time();
    $encrypted = encrypt($testData);
    $decrypted = decrypt($encrypted);

    if ($decrypted === $testData) {
        echo "<p class='success'>✅ Laravel encryption/decryption working correctly</p>";
    } else {
        echo "<p class='error'>❌ Laravel encryption test failed</p>";
    }

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

echo "<h2>🎯 Next Step</h2>";
echo "<div style='background:#d4edda;padding:15px;border-radius:8px;margin:10px 0;border:1px solid #c3e6cb;'>";
echo "<h3 style='color:#155724;'>✅ APP_KEY FIXED!</h3>";
echo "<p style='color:#155724;'>The encryption error should now be resolved.</p>";
echo "<br>";
echo "<p><strong>Test your application now:</strong></p>";
echo "<p><a href='http://192.168.10.70' target='_blank' style='color:#155724;font-weight:bold;'>http://192.168.10.70</a></p>";
echo "</div>";

echo "<p><a href='test_full_app.php'>← Test Application Again</a></p>";
echo "<p><a href='debug_500.php'>← Back to Debug</a></p>";

echo "<hr>";
echo "<p><strong>APP_KEY fix completed at:</strong> " . date('Y-m-d H:i:s') . "</p>";
?>
