<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'tasmoybb_dazzaii');
define('DB_PASS', '3XT3RN4l!337');
define('DB_NAME', 'tasmoybb_dazza2');

$https = (
  (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
  (!empty($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443) ||
  (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
);
$scheme = $https ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';

$scriptDir = '/';
if (!empty($_SERVER['SCRIPT_NAME'])) {
  $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
}
$scriptDir = ($scriptDir === '/' || $scriptDir === '\\') ? '' : rtrim($scriptDir, '/');

$basePathOverride = getenv('BASE_PATH');
define('BASE_PATH', ($basePathOverride !== false && $basePathOverride !== '') ? rtrim($basePathOverride, '/') : $scriptDir);

define('BASE_URL', $scheme . $host . BASE_PATH);

define('IMAGE_PATH', rtrim($_SERVER['DOCUMENT_ROOT'] ?? __DIR__, '/') . BASE_PATH . '/images');
define('IMAGE_URL', BASE_URL . '/images');

function getDB(): PDO {
  static $pdo = null;
  if ($pdo === null) {
    $pdo = new PDO(
      "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
      DB_USER,
      DB_PASS,
      [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
      ]
    );
    $pdo->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
  }
  return $pdo;
}

/**
 * Robust champion image resolver:
 * Tries multiple case variants to match your real folders/files.
 *
 * Expected structure (your preference):
 * /images/champions/Gaia/Gaia-flyer.png
 * /images/champions/Gaia/Gaia-avatar.png
 * /images/champions/Gaia/Gaia-card.png
 */
function getChampionImage(string $championName, string $type = 'flyer'): string {
  $nameRaw = preg_replace('/[^A-Za-z0-9_-]/', '', $championName);

  $variants = array_values(array_unique([
    $nameRaw,
    ucfirst(strtolower($nameRaw)),
    strtoupper($nameRaw),
    strtolower($nameRaw),
  ]));

  foreach ($variants as $n) {
    $path = IMAGE_PATH . "/champions/{$n}/{$n}-{$type}.png";
    if (file_exists($path)) {
      return IMAGE_URL . "/champions/{$n}/{$n}-{$type}.png";
    }
  }

  // fall back to the "expected" path even if missing (lets browser show broken icon if you want)
  return IMAGE_URL . "/champions/{$nameRaw}/{$nameRaw}-{$type}.png";
}
