<?php
/**
 * Fix white screen — sets APP_ENV=production and clears cached views
 * DELETE AFTER USE
 */

$envPath = __DIR__ . '/.env';
if (!file_exists($envPath)) {
    $envPath = __DIR__ . '/../.env';
}
if (!file_exists($envPath)) {
    die("❌ .env not found");
}

$env = file_get_contents($envPath);
$fixed = [];

// Fix 1: Set APP_ENV to production
if (preg_match('/^APP_ENV=.*$/m', $env)) {
    $env = preg_replace('/^APP_ENV=.*$/m', 'APP_ENV=production', $env);
    $fixed[] = "APP_ENV → production";
} else {
    $env .= "\nAPP_ENV=production\n";
    $fixed[] = "APP_ENV → production (added)";
}

// Fix 2: Set APP_NAME
if (preg_match('/^APP_NAME=.*$/m', $env)) {
    $env = preg_replace('/^APP_NAME=.*$/m', 'APP_NAME="Sarkin Mota Group"', $env);
    $fixed[] = "APP_NAME → Sarkin Mota Group";
}

// Fix 3: Set APP_URL to your domain
if (preg_match('/^APP_URL=.*$/m', $env)) {
    $env = preg_replace('/^APP_URL=.*$/m', 'APP_URL=https://sarkinmota-autos.com', $env);
    $fixed[] = "APP_URL → https://sarkinmota-autos.com";
}

// Fix 4: Set ASSET_URL
if (preg_match('/^ASSET_URL=.*$/m', $env)) {
    $env = preg_replace('/^ASSET_URL=.*$/m', 'ASSET_URL=https://sarkinmota-autos.com', $env);
} else {
    $env .= "\nASSET_URL=https://sarkinmota-autos.com\n";
}
$fixed[] = "ASSET_URL → https://sarkinmota-autos.com";

file_put_contents($envPath, $env);

// Fix 5: Clear compiled views
$viewDirs = [
    __DIR__ . '/storage/framework/views',
    __DIR__ . '/../storage/framework/views',
];
foreach ($viewDirs as $vd) {
    if (is_dir($vd)) {
        $files = glob($vd . '/*.php');
        foreach ($files as $f) {
            unlink($f);
        }
        $fixed[] = "Cleared " . count($files) . " compiled views";
    }
}

// Report
echo "<h2>✅ White Screen Fixed!</h2>";
echo "<pre style='background:#1e1e1e;color:#4ade80;padding:20px;font-size:14px;'>";
foreach ($fixed as $f) {
    echo "✅ $f\n";
}
echo "\n🚀 Your site should now work:\n";
echo "   https://sarkinmota-autos.com/\n\n";
echo "⚠️ DELETE this file (fix-env.php) NOW!\n";
echo "</pre>";
