<?php
// config/config.php

// Cargar variables de entorno
require_once __DIR__ . '/../vendor/autoload.php';

// Verificar si estamos en un contenedor Docker
$is_docker = (getenv('DOCKER_CONTAINER') === '1') || ($_SERVER['DOCKER_CONTAINER'] ?? null) === '1';

// Entorno: cargar archivo .env según APP_ENVIRONMENT
$env = getenv('APP_ENVIRONMENT') ?: ($_SERVER['APP_ENVIRONMENT'] ?? 'pruebas');

if ($env === 'reod') {
    $envFile = '.env';
} else {
    $envFile = '.env.' . $env;
}

$dotenv = null;
if (file_exists(dirname(__DIR__) . '/' . $envFile)) {
    $dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__), $envFile);
} elseif (file_exists(dirname(__DIR__) . '/.env')) {
    $dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
}

if ($dotenv) {
    try {
        $dotenv->load();
    } catch (Exception $e) {
        die('Error al cargar el archivo de entorno: ' . $e->getMessage());
    }
    // ... el resto de la configuración ...
    // Aquí es donde definimos las variables obligatorias
    $dotenv->required([
        'DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS',
        'JWT_SECRET', 'APP_URL'
    ]);
}


// Environment Configuration
define('ENVIRONMENT', $_ENV['APP_ENV'] ?? $_SERVER['APP_ENV'] ?? 'production');

// Detectar si se ejecuta desde la línea de comandos
$is_cli = (php_sapi_name() === 'cli' || defined('STDIN'));

// Helper function to get env vars
function getEnvVar($name, $default = null) {
    // Priorizamos getenv() para las variables cargadas por Dotenv,
    // ya que sabemos que funciona y $_ENV puede estar corrupto o contener Array en algunos entornos Docker.
    return getenv($name) ?: ($_ENV[$name] ?? $_SERVER[$name] ?? $default);
}

// Configurar la URL base y el protocolo
if ($is_cli) {
    define('BOT_BASE_URL', getEnvVar('APP_URL'));
    $protocol = 'http';
} else {
    $protocol = 'http';
    if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || 
        (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ||
        (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on') ||
        (!empty($_SERVER['HTTP_CF_VISITOR']) && strpos($_SERVER['HTTP_CF_VISITOR'], 'https') !== false)) {
        $protocol = 'https';
        $_SERVER['HTTPS'] = 'on';
        $_SERVER['SERVER_PORT'] = 443;
    }
    $app_url = getEnvVar('APP_URL');
    if ($app_url) {
        define('BOT_BASE_URL', trim($app_url, ' "\''));
    } else {
        define('BOT_BASE_URL', $protocol . '://' . $_SERVER['HTTP_HOST']);
    }
    $_SERVER['REQUEST_SCHEME'] = $protocol;
}
define('BASE_PATH', dirname(__DIR__));

// Database Configuration
define('DB_HOST', getEnvVar('DB_HOST'));
define('DB_USER', getEnvVar('DB_USER'));
define('DB_PASS', getEnvVar('DB_PASS'));
define('DB_NAME', getEnvVar('DB_NAME'));
define('DB_DIALECT', getEnvVar('DB_DIALECT'));
define('DB_PORT', getEnvVar('DB_PORT'));

// Session Configuration
define('SESSION_SECRET', getEnvVar('JWT_SECRET'));

// Discord API Configuration
define('DISCORD_GUILD_ID', getEnvVar('DISCORD_GUILD_ID'));
define('DISCORD_CLIENT_ID', getEnvVar('DISCORD_CLIENT_ID'));
define('DISCORD_CLIENT_SECRET', getEnvVar('DISCORD_CLIENT_SECRET'));
define('DISCORD_BOT_TOKEN', getEnvVar('DISCORD_BOT_TOKEN'));

// Telegram API Configuration
define('TELEGRAM_BOT_TOKEN', getEnvVar('TELEGRAM_BOT_TOKEN'));
define('TELEGRAM_WEBHOOK_TOKEN', getEnvVar('TELEGRAM_WEBHOOK_TOKEN'));

// LibreTranslate Configuration
define('LIBRETRANSLATE_URL', getEnvVar('LIBRETRANSLATE_URL'));

// N8N Configuration
define('N8N_URL', getEnvVar('N8N_URL'));
define('N8N_TOKEN', getEnvVar('N8N_TOKEN'));
define('N8N_PROCESS_QUEUE_WEBHOOK_URL', getEnvVar('N8N_PROCESS_QUEUE_WEBHOOK_URL'));
define('N8N_IA_WEBHOOK_URL', getEnvVar('N8N_IA_WEBHOOK_URL'));
define('N8N_IA_WEBHOOK_URL_DISCORD', getEnvVar('N8N_IA_WEBHOOK_URL_DISCORD'));
define('INTERNAL_API_KEY', getEnvVar('INTERNAL_API_KEY'));

// Error Reporting
switch (ENVIRONMENT) {
    case 'development':
        error_reporting(E_ALL);
        ini_set('display_errors', '1');
        ini_set('log_errors', '1');
        ini_set('error_log', dirname(__DIR__) . '/logs/php_errors.log');
        break;
    case 'production':
        error_reporting(E_ALL & ~E_DEPRECATED);
        ini_set('display_errors', '0');
        ini_set('log_errors', '1');
        ini_set('error_log', dirname(__DIR__) . '/logs/php_errors.log');
        break;
    default:
        error_reporting(E_ALL);
        ini_set('display_errors', '1');
        ini_set('log_errors', '1');
        ini_set('error_log', dirname(__DIR__) . '/logs/php_errors.log');
        break;
}

// Helper function to get full URL
function url($path = '') {
    $path = ltrim($path, '/');
    return BOT_BASE_URL . '/' . $path;
}

// Helper function to get full asset URL
function asset_url($path = '') {
    $path = ltrim($path, '/');
    return BOT_BASE_URL . '/assets/' . $path;
}
