<?php

/**
 * @file
 * Drupal site-specific configuration file.
 */

// Load .env file if it exists.
$env_file = dirname(DRUPAL_ROOT) . '/.env';
if (file_exists($env_file)) {
  $lines = file($env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  foreach ($lines as $line) {
    $line = trim($line);
    if ($line === '' || str_starts_with($line, '#')) {
      continue;
    }
    if (str_contains($line, '=')) {
      [$key, $value] = explode('=', $line, 2);
      $key = trim($key);
      $value = trim($value);
      if (!getenv($key)) {
        putenv("$key=$value");
        $_ENV[$key] = $value;
        $_SERVER[$key] = $value;
      }
    }
  }
}

if (!function_exists('env')) {
  function env(string $key, mixed $default = NULL): mixed {
    $value = getenv($key);
    return $value !== FALSE ? $value : $default;
  }
}

// Database connection settings.
$databases['default']['default'] = [
  'database' => env('DB_NAME', 'drupal11'),
  'username' => env('DB_USER', 'drupal11'),
  'password' => env('DB_PASSWORD', 'drupal11'),
  'prefix'   => '',
  'host'     => env('DB_HOST', 'database'),
  'port'     => env('DB_PORT', '3306'),
  'driver'   => env('DB_DRIVER', 'mysql'),
  'namespace' => 'Drupal\\mysql\\Driver\\Database\\mysql',
  'autoload' => 'core/modules/mysql/src/Driver/Database/mysql/',
];

$settings['config_sync_directory'] = env('DRUPAL_CONFIG_SYNC_DIR', '../config/sync');
$settings['hash_salt'] = env('DRUPAL_HASH_SALT', 'change-me-to-a-random-secure-string');

$trusted_hosts_raw = env('DRUPAL_TRUSTED_HOST_PATTERNS', '');
if (!empty($trusted_hosts_raw)) {
  $settings['trusted_host_patterns'] = explode(',', $trusted_hosts_raw);
}

$settings['file_public_path'] = env('DRUPAL_FILE_PUBLIC_PATH', 'sites/default/files');
$settings['file_private_path'] = env('DRUPAL_FILE_PRIVATE_PATH', '../private');

// Redis caching configuration.
if (
  extension_loaded('redis') &&
  !(\Drupal\Core\Installer\InstallerKernel::installationAttempted()) &&
  file_exists($app_root . '/modules/contrib/redis/example.services.yml')
) {
  try {
    $redis_host = env('REDIS_HOST', 'redis');
    $redis_port = env('REDIS_PORT', 6379);

    $redis_client = new \Redis();
    if (@$redis_client->connect($redis_host, (int) $redis_port, 1)) {
      $redis_client->close();

      $settings['redis.connection']['interface'] = 'PhpRedis';
      $settings['redis.connection']['host'] = $redis_host;
      $settings['redis.connection']['port'] = (int) $redis_port;
      $settings['cache']['default'] = 'cache.backend.redis';
      $settings['container_yamls'][] = 'modules/contrib/redis/example.services.yml';
    }
  }
  catch (\Exception $e) {
  }
}

// Load local development settings if available.
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}
