<?php
/*
 +--------------------------------------------------------------------+
 | CiviCRM version 5                                                  |
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC (c) 2004-2020                                |
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the GNU Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
*/

/**
 * CiviCRM Configuration File — Greenleaf ONE Bedrock
 *
 * Environment-parameterized configuration. All credentials and paths are
 * read from environment variables (typically via .env). Run `composer
 * generate-salts` to auto-generate security keys.
 */
global $civicrm_root, $civicrm_setting, $civicrm_paths;

/**
 * Environment-aware path and URL configuration.
 * HOSTING_ROOT: filesystem root (Docker: /var/www/html, production: /home/site/www/sitename)
 * WP_HOME: site URL (set in .env)
 */
$_civicrm_hosting_root = getenv('HOSTING_ROOT') ?: '/var/www/html';
$_civicrm_base_url = getenv('WP_HOME') ?: 'http://localhost:8080';

/**
 * Content Management System (CMS) Host
 */
if (!defined('CIVICRM_UF')) {
  if (getenv('CIVICRM_UF')) {
    define('CIVICRM_UF', getenv('CIVICRM_UF'));
  }
  else {
    define('CIVICRM_UF', 'WordPress');
  }
}

/**
 * Content Management System (CMS) Datasource
 *
 * Builds the WordPress database DSN from environment variables.
 * Required env vars: DB_USER, DB_PASSWORD, DB_HOST, DB_NAME
 */
if (!defined('CIVICRM_UF_DSN') && CIVICRM_UF !== 'UnitTests') {
  if (getenv('DB_USER') && getenv('DB_PASSWORD') && getenv('DB_HOST') && getenv('DB_NAME')) {
    $_db_password = rawurlencode(getenv('DB_PASSWORD'));
    define('CIVICRM_UF_DSN', 'mysql://' . getenv('DB_USER') . ':' . $_db_password . '@' . getenv('DB_HOST') . '/' . getenv('DB_NAME') . '?new_link=true');
  } else {
    trigger_error('CiviCRM: Database environment variables (DB_USER, DB_PASSWORD, DB_HOST, DB_NAME) are not set. Check your .env file.', E_USER_WARNING);
  }
}

// Additional settings (environment-aware):
$civicrm_paths['civicrm.private']['path'] = $_civicrm_hosting_root . '/web/app/uploads/civicrm';
$civicrm_paths['wp.frontend.base']['url'] = $_civicrm_base_url . '/';
$civicrm_paths['wp.backend.base']['url'] = $_civicrm_base_url . '/wp/wp-admin/';
$civicrm_setting['domain']['userFrameworkResourceURL'] = $_civicrm_base_url . '/app/plugins/civicrm/core';

// Docker logging: send CiviCRM logs to stderr for visibility in docker logs
if (getenv('CIVICRM_LOG_STDERR')) {
  $civicrm_paths['civicrm.log']['path'] = 'php://stderr';
}

/**
 * CiviCRM Database Settings
 *
 * Uses CIVICRM_DB_NAME for a separate CiviCRM database, or falls back to
 * the WordPress database (DB_NAME) if not set.
 */
if (!defined('CIVICRM_DSN')) {
  if (CIVICRM_UF === 'UnitTests') {
    if (isset($GLOBALS['_CV']['TEST_DB_DSN'])) {
      define('CIVICRM_DSN', $GLOBALS['_CV']['TEST_DB_DSN']);
    }
    else {
      throw new \Exception('$GLOBALS["_CV"]["TEST_DB_DSN"] is not set');
    }
  }
  elseif (getenv('DB_USER') && getenv('DB_PASSWORD') && getenv('DB_HOST')) {
    $_db_password_civi = rawurlencode(getenv('DB_PASSWORD'));
    $_civicrm_db_name = getenv('CIVICRM_DB_NAME') ?: getenv('DB_NAME');
    define('CIVICRM_DSN', 'mysql://' . getenv('DB_USER') . ':' . $_db_password_civi . '@' . getenv('DB_HOST') . '/' . $_civicrm_db_name . '?new_link=true');
  }
}

// define ('DB_DSN_MODE', 'auto');

/**
 * CiviCRM Logging Database
 *
 * Separate database for detailed logging. Uses CIVICRM_LOGGING_DB_NAME env var
 * with the same credentials as the main database. The DB user needs TRIGGER and
 * CREATE TEMPORARY TABLES privileges on this database.
 *
 * Falls back to CIVICRM_DSN (same database) if not configured.
 */
if (!defined('CIVICRM_LOGGING_DSN')) {
  if (getenv('CIVICRM_LOGGING_DB_NAME') && getenv('DB_USER') && getenv('DB_PASSWORD') && getenv('DB_HOST')) {
    $_db_password_log = rawurlencode(getenv('DB_PASSWORD'));
    define('CIVICRM_LOGGING_DSN', 'mysql://' . getenv('DB_USER') . ':' . $_db_password_log . '@' . getenv('DB_HOST') . '/' . getenv('CIVICRM_LOGGING_DB_NAME') . '?new_link=true');
  } else {
    define('CIVICRM_LOGGING_DSN', CIVICRM_DSN);
  }
}

/**
 * File System Paths
 */
$civicrm_root = $_civicrm_hosting_root . '/vendor/civicrm/civicrm-core/';
if (!defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
  define('CIVICRM_TEMPLATE_COMPILEDIR', $_civicrm_hosting_root . '/web/app/uploads/civicrm/templates_c');
}

/**
 * Site URLs
 */
if (!defined('CIVICRM_UF_BASEURL')) {
  define('CIVICRM_UF_BASEURL', $_civicrm_base_url . '/wp');
}

/**
 * Smarty autoload — defaults to Smarty5
 */
if (!defined('CIVICRM_SMARTY_AUTOLOAD_PATH') && getenv('CIVICRM_SMARTY_AUTOLOAD_PATH') === FALSE) {
  // Bedrock: civicrm-packages is in vendor via Composer
  $_packages_dir = $_civicrm_hosting_root . '/vendor/civicrm/civicrm-packages';
  if (is_dir($_packages_dir)) {
    define('CIVICRM_SMARTY_AUTOLOAD_PATH', $_packages_dir . '/smarty5/Smarty.php');
  }
  elseif (is_dir($civicrm_root . '/packages')) {
    define('CIVICRM_SMARTY_AUTOLOAD_PATH', $civicrm_root . '/packages/smarty5/Smarty.php');
  }
}

if (!defined('CIVICRM_DEDUPE_OPTIMIZER')) {
  define('CIVICRM_DEDUPE_OPTIMIZER', FALSE);
}

/**
 * Security Keys — read from environment variables.
 * Run `composer generate-salts` to auto-generate these values in .env.
 */
if (!defined('CIVICRM_SITE_KEY')) {
  $_site_key = getenv('CIVICRM_SITE_KEY') ?: 'generateme';
  define('CIVICRM_SITE_KEY', $_site_key);
}

if (!defined('CIVICRM_CRED_KEYS')) {
  $_cred_keys = getenv('CIVICRM_CRED_KEYS') ?: 'generateme';
  define('CIVICRM_CRED_KEYS', $_cred_keys);
}

if (!defined('CIVICRM_DEPLOY_ID')) {
  define('CIVICRM_DEPLOY_ID', substr(md5(CIVICRM_SITE_KEY), 0, 12));
}

if (!defined('CIVICRM_SIGN_KEYS')) {
  $_sign_keys = getenv('CIVICRM_SIGN_KEYS') ?: 'generateme';
  define('CIVICRM_SIGN_KEYS', $_sign_keys);
}

/**
 * Mail settings
 */
if (!defined('CIVICRM_MAIL_SMARTY')) {
  define('CIVICRM_MAIL_SMARTY', 0);
}

// Uncomment for mail debugging (disables actual sending):
// if (!defined('CIVICRM_MAIL_LOG')) {
//   define('CIVICRM_MAIL_LOG', $_civicrm_hosting_root . '/web/app/uploads/civicrm/templates_c/mail.log');
// }

if (!defined('CIVICRM_DOMAIN_ID')) {
  define('CIVICRM_DOMAIN_ID', 1);
}

// Uncomment to set the CiviCRM environment (Production, Staging, Development):
// $civicrm_setting['domain']['environment'] = 'Production';

/**
 * Cache settings — defaults to ArrayCache (in-memory)
 */
if (!defined('CIVICRM_DB_CACHE_CLASS')) {
  define('CIVICRM_DB_CACHE_CLASS', 'ArrayCache');
}

if (!defined('CIVICRM_DB_CACHE_HOST')) {
  define('CIVICRM_DB_CACHE_HOST', 'localhost');
}

if (!defined('CIVICRM_DB_CACHE_PORT')) {
  if (CIVICRM_DB_CACHE_CLASS === 'Redis') {
    define('CIVICRM_DB_CACHE_PORT', 6379);
  }
  else {
    define('CIVICRM_DB_CACHE_PORT', 11211);
  }
}

if (!defined('CIVICRM_DB_CACHE_PASSWORD')) {
  define('CIVICRM_DB_CACHE_PASSWORD', '');
}

if (!defined('CIVICRM_DB_CACHE_TIMEOUT')) {
  define('CIVICRM_DB_CACHE_TIMEOUT', 3600);
}

if (!defined('CIVICRM_DB_CACHE_PREFIX')) {
  define('CIVICRM_DB_CACHE_PREFIX', '');
}

if (!defined('CIVICRM_PSR16_STRICT')) {
  define('CIVICRM_PSR16_STRICT', FALSE);
}

/**
 * Performance settings
 */
define('CIVICRM_DEADLOCK_RETRIES', 3);

if (CIVICRM_UF === 'UnitTests') {
  if (!defined('CIVICRM_CONTAINER_CACHE')) define('CIVICRM_CONTAINER_CACHE', 'auto');
}

if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' && !defined('CIVICRM_EXCLUDE_DIRS_PATTERN')) {
  define('CIVICRM_EXCLUDE_DIRS_PATTERN', '@/(\.|node_modules|js/|css/|bower_components|packages/|sites/default/files/private)@');
}

/**
 * Do not change anything below this line. Keep as is.
 */

$_civicrm_packages = $_civicrm_hosting_root . '/vendor/civicrm/civicrm-packages';
$include_path = '.'           . PATH_SEPARATOR .
                $civicrm_root . PATH_SEPARATOR .
                $_civicrm_packages . PATH_SEPARATOR .
                get_include_path();
if (set_include_path($include_path) === false) {
   echo "Could not set the include path<p>";
   exit();
}

if (!defined('CIVICRM_CLEANURL')) {
  if (function_exists('variable_get') && variable_get('clean_url', '0') != '0') {
    define('CIVICRM_CLEANURL', 1);
  }
  elseif (function_exists('config_get') && config_get('system.core', 'clean_url') != 0) {
    define('CIVICRM_CLEANURL', 1);
  }
  elseif (function_exists('get_option') && get_option('permalink_structure') != '') {
    define('CIVICRM_CLEANURL', 1);
  }
  else {
    define('CIVICRM_CLEANURL', 0);
  }
}

/**
 * Ensure memory_limit is at least 128 MB.
 */
$memLimitString = trim(ini_get('memory_limit'));
$memLimitUnit   = strtolower(substr($memLimitString, -1));
$memLimit       = (int) $memLimitString;
switch ($memLimitUnit) {
    case 'g': $memLimit *= 1024;
    case 'm': $memLimit *= 1024;
    case 'k': $memLimit *= 1024;
}
if ($memLimit >= 0 and $memLimit < 134217728) {
    ini_set('memory_limit', '128M');
}

require_once 'CRM/Core/ClassLoader.php';
CRM_Core_ClassLoader::singleton()->register();
