<?php
/**
 * One-time DB diagnostic for shared hosting (e.g. kgmb.page.gd).
 * Upload to htdocs next to index.php, open in browser, then DELETE this file.
 */
error_reporting(E_ALL);
ini_set('display_errors', '1');

header('Content-Type: text/html; charset=utf-8');
echo '<h2>Database diagnostic</h2><pre>';

$paths = [
    'DOCUMENT_ROOT/.env' => (!empty($_SERVER['DOCUMENT_ROOT']) ? rtrim($_SERVER['DOCUMENT_ROOT'], '/\\') . '/.env' : '(no DOCUMENT_ROOT)'),
    'parent of this file/.env' => dirname(__FILE__) . '/.env',
    'config/../.env' => dirname(__FILE__) . '/config/../.env',
];

foreach ($paths as $label => $path) {
  $real = @realpath($path);
  $exists = file_exists($path);
  $readable = $exists && is_readable($path);
  echo $label . "\n  path: " . $path . "\n  exists: " . ($exists ? 'YES' : 'NO');
  echo "\n  readable: " . ($readable ? 'YES' : 'NO');
  if ($real) {
    echo "\n  realpath: " . $real;
  }
  echo "\n\n";
}

require_once __DIR__ . '/config/EnvLoader.php';
EnvLoader::load();

$host = EnvLoader::get('DB_HOST', '(not set)');
$db = EnvLoader::get('DB_NAME', '(not set)');
$user = EnvLoader::get('DB_USER', '(not set)');
$passSet = EnvLoader::get('DB_PASS', '') !== '' ? 'YES' : 'NO';

echo "Loaded from EnvLoader:\n";
echo "  DB_HOST = " . $host . "\n";
echo "  DB_NAME = " . $db . "\n";
echo "  DB_USER = " . $user . "\n";
echo "  DB_PASS set = " . $passSet . "\n\n";

if ($host === 'localhost' || $host === '127.0.0.1' || $host === '(not set)') {
    echo ">>> PROBLEM: DB_HOST is still localhost — .env is NOT loaded or DB_HOST missing in .env\n\n";
}

$testHost = 'sql301.infinityfree.com';
$testDb = 'if0_35599065_kgmb';
$testUser = 'if0_35599065';
$testPass = EnvLoader::get('DB_PASS', '');

echo "Connection test with loaded credentials...\n";
try {
    $pdo = new PDO(
        "mysql:host={$host};port=3306;dbname={$db};charset=utf8mb4",
        $user,
        EnvLoader::get('DB_PASS', ''),
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 15]
    );
    $n = $pdo->query('SHOW TABLES')->rowCount();
    echo "  SUCCESS — connected. Tables found: {$n}\n";
} catch (PDOException $e) {
    echo "  FAILED: " . $e->getMessage() . "\n";
}

echo "\n---\nIf .env exists=NO: create file named exactly .env (with leading dot) in htdocs.\n";
echo "InfinityFree File Manager sometimes hides dotfiles — use FTP or rename env.txt to .env\n";
echo "Delete db_diagnostic.php after fixing.\n</pre>";
