<?php
/**
 * env-doctor.php — DB credential / config-cache diagnostic.
 *
 * Shows three things side by side:
 *   1. What is literally written in .env right now.
 *   2. What Laravel is ACTUALLY using (may be stale if config was cached).
 *   3. Whether MySQL itself accepts the .env credentials directly.
 * Also offers a button to clear Laravel's cached config so fresh .env
 * values take effect immediately.
 *
 * HOW TO USE:
 *  1. Upload into the same folder as "artisan" (next to install-web.php).
 *  2. Visit: https://yourdomain.com/env-doctor.php?token=THE_TOKEN_BELOW
 *  3. Delete this file from the server when you're done.
 */

$TOKEN = 'bec3e3ee1a544fe37099baed2328c125';

$root = __DIR__;
function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES); }

if (!hash_equals($TOKEN, $_GET['token'] ?? '')) {
    http_response_code(403);
    die('Forbidden. Add ?token=YOUR_TOKEN to the URL.');
}

echo '<!doctype html><html><head><meta charset="utf-8"><title>Env Doctor</title>';
echo '<style>body{font-family:sans-serif;max-width:760px;margin:40px auto;padding:0 16px;line-height:1.5}
pre{background:#f4f4f4;padding:12px;border-radius:6px;overflow:auto}
.ok{color:#1a7d1a} .err{color:#c0392b} .warn{color:#b8860b}
.btn{display:inline-block;padding:10px 18px;border-radius:5px;text-decoration:none;color:#fff;background:#2980b9}
table{border-collapse:collapse;width:100%} td,th{border:1px solid #ddd;padding:6px 10px;text-align:left;font-size:14px}
</style></head><body>';
echo '<h1>Env Doctor</h1>';

// ---------- 1. Raw .env values ----------
$envPath = $root . '/.env';
$rawEnv = [];
if (file_exists($envPath)) {
    foreach (file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#' || strpos($line, '=') === false) continue;
        [$k, $v] = explode('=', $line, 2);
        $rawEnv[trim($k)] = trim(trim($v), "\"'");
    }
}
$rHost = $rawEnv['DB_HOST'] ?? '';
$rPort = $rawEnv['DB_PORT'] ?? '';
$rDb   = $rawEnv['DB_DATABASE'] ?? '';
$rUser = $rawEnv['DB_USERNAME'] ?? '';
$rPass = $rawEnv['DB_PASSWORD'] ?? '';

echo '<h2>1. Raw .env file, right now</h2>';
if (!file_exists($envPath)) {
    echo '<p class="err">.env not found.</p>';
} else {
    echo '<pre>';
    echo 'DB_HOST     = ' . h($rHost) . "\n";
    echo 'DB_PORT     = ' . h($rPort) . "\n";
    echo 'DB_DATABASE = ' . h($rDb) . "\n";
    echo 'DB_USERNAME = ' . h($rUser) . "\n";
    echo 'DB_PASSWORD = ' . (strlen($rPass) ? str_repeat('*', strlen($rPass)) . ' (' . strlen($rPass) . ' chars)' : '(EMPTY)') . "\n";
    echo '</pre>';
    if (strpos($rUser, '@') !== false) {
        echo '<p class="err">DB_USERNAME contains an "@" — this usually means the password got typed into the username field by mistake. A real MySQL username should not contain "@".</p>';
    }
}

// ---------- 2. Cached config files ----------
$cacheDir = $root . '/bootstrap/cache';
$cacheFiles = ['config.php', 'routes-v7.php', 'packages.php', 'services.php'];
$foundCache = [];
foreach ($cacheFiles as $f) {
    if (file_exists($cacheDir . '/' . $f)) $foundCache[] = $f;
}

echo '<h2>2. Laravel cached config files</h2>';
if (empty($foundCache)) {
    echo '<p class="ok">No cached config files found — Laravel is reading .env fresh on every request. (Good — rules out stale caching.)</p>';
} else {
    echo '<p class="warn">Found cached files: ' . h(implode(', ', $foundCache)) . '</p>';
    echo '<p class="warn">If <code>config.php</code> is in that list, Laravel is using a FROZEN snapshot of .env taken earlier and is ignoring any edits you\'ve made since. This is very likely why the same wrong username keeps showing up.</p>';

    if (isset($_GET['clear_cache']) && $_GET['clear_cache'] === 'yes') {
        $removed = [];
        foreach ($foundCache as $f) {
            if (@unlink($cacheDir . '/' . $f)) $removed[] = $f;
        }
        echo '<p class="ok">Cleared: ' . h(implode(', ', $removed)) . '. Reload this page to confirm.</p>';
        echo '<p><a href="?token=' . urlencode($TOKEN) . '">Reload</a></p>';
    } else {
        $clearUrl = '?token=' . urlencode($TOKEN) . '&clear_cache=yes';
        echo '<a class="btn" href="' . h($clearUrl) . '">Clear cached config now</a>';
    }
}

// ---------- 3. What Laravel is actually using ----------
echo '<h2>3. What Laravel is actually using right now</h2>';
try {
    require $root . '/vendor/autoload.php';
    $app = require $root . '/bootstrap/app.php';
    $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
    $kernel->bootstrap();

    $lHost = config('database.connections.mysql.host');
    $lPort = config('database.connections.mysql.port');
    $lDb   = config('database.connections.mysql.database');
    $lUser = config('database.connections.mysql.username');
    $lPass = (string) config('database.connections.mysql.password');

    echo '<table><tr><th>Setting</th><th>In .env file</th><th>Laravel is using</th><th>Match?</th></tr>';
    $rows = [
        ['HOST', $rHost, $lHost],
        ['PORT', $rPort, $lPort],
        ['DATABASE', $rDb, $lDb],
        ['USERNAME', $rUser, $lUser],
        ['PASSWORD length', strlen($rPass), strlen($lPass)],
    ];
    foreach ($rows as [$label, $envVal, $liveVal]) {
        $match = ((string)$envVal === (string)$liveVal);
        echo '<tr><td>' . h($label) . '</td><td>' . h($envVal) . '</td><td>' . h($liveVal) . '</td><td>'
            . ($match ? '<span class="ok">match</span>' : '<span class="err">MISMATCH</span>') . '</td></tr>';
    }
    echo '</table>';

    if ((string)$rUser !== (string)$lUser || (string)$rPass !== (string)$lPass) {
        echo '<p class="err">Confirmed: Laravel is using different credentials than what\'s in .env right now. Clear the cache above, then reload this page — the "Laravel is using" column should update to match .env.</p>';
    }
} catch (\Throwable $e) {
    echo '<p class="err">Could not boot the app to check: ' . h($e->getMessage()) . '</p>';
}

// ---------- 4. Direct MySQL test using raw .env values ----------
echo '<h2>4. Direct MySQL test (using the raw .env values from section 1)</h2>';
if ($rUser !== '') {
    $mysqli = @new mysqli($rHost ?: 'localhost', $rUser, $rPass, $rDb, (int)($rPort ?: 3306));
    if ($mysqli->connect_errno) {
        echo '<p class="err">FAILED: ' . h($mysqli->connect_error) . '</p>';
        echo '<p>This confirms the values in section 1 are wrong — fix DB_USERNAME/DB_PASSWORD in .env to exactly match what you created under cPanel &raquo; MySQL&reg; Databases, then reload this page.</p>';
    } else {
        echo '<p class="ok">SUCCESS — MySQL accepts these exact .env credentials directly.</p>';
        echo '<p>If section 3 still shows a mismatch, clear the cache in section 2 and reload. If everything matches now, go back to the installer and try again.</p>';
    }
} else {
    echo '<p class="err">DB_USERNAME is empty in .env — nothing to test.</p>';
}

echo '<hr><p class="err"><strong>Delete this file (env-doctor.php) from the server once you\'re done — it can reveal your database configuration.</strong></p>';
echo '</body></html>';
