<?php
/**
 * Generate APP_KEY — standalone, no Laravel needed
 * Works from root OR public/ folder
 * DELETE AFTER USE
 */

// Try multiple paths for .env
$paths = [
    __DIR__ . '/.env',
    __DIR__ . '/../.env',
    __DIR__ . '/../../.env',
];

$envPath = null;
foreach ($paths as $p) {
    if (file_exists($p)) { $envPath = $p; break; }
}

if (!$envPath) {
    die("❌ .env not found. Tried:\n" . implode("\n", $paths));
}

echo "Found .env at: $envPath\n\n";

// Generate a random 32-character key
$key = 'base64:' . base64_encode(random_bytes(32));

// Read .env
$env = file_get_contents($envPath);

// Replace or add APP_KEY
if (preg_match('/^APP_KEY=.*$/m', $env)) {
    $env = preg_replace('/^APP_KEY=.*$/m', 'APP_KEY=' . $key, $env);
} else {
    $env .= "\nAPP_KEY=" . $key . "\n";
}

// Write back
if (file_put_contents($envPath, $env)) {
    echo "✅ APP_KEY generated and saved!\n\n";
    echo "Your site should now work at:\n";
    echo "https://sarkinmota-autos.com/\n\n";
    echo "⚠️ DELETE this file (key.php) NOW!\n";
} else {
    echo "❌ Failed to write .env. Check permissions.\n";
}
