<?php
/**
 * Environment Configuration for Go Legal CRM
 * Works out of the box on cPanel/shared hosting
 */

// Detect if running on local development vs production
if (!defined('ENVIRONMENT')) {
    // Auto-detect environment based on server variables
    $host = $_SERVER['HTTP_HOST'] ?? '';
    $serverName = $_SERVER['SERVER_NAME'] ?? '';
    
    if (strpos($host, 'localhost') !== false || 
        strpos($host, '127.0.0.1') !== false ||
        strpos($serverName, 'localhost') !== false) {
        define('ENVIRONMENT', 'development');
    } else {
        define('ENVIRONMENT', 'production');
    }
}

// Database Configuration
if (!defined('DB_TYPE')) {
    // Auto-detect: Use SQLite for development, MySQL for production
    if (ENVIRONMENT === 'development') {
        define('DB_TYPE', 'sqlite');
        define('DB_PATH', __DIR__ . '/crms.sqlite');
    } else {
        // Production defaults - can be overridden by environment variables
        // Default to sqlite for "out of the box" experience if mysql is not configured
        define('DB_TYPE', $_ENV['DB_TYPE'] ?? 'sqlite');
        define('DB_HOST', $_ENV['DB_HOST'] ?? 'localhost');
        define('DB_NAME', $_ENV['DB_NAME'] ?? 'golegal_db');
        define('DB_USER', $_ENV['DB_USER'] ?? 'golegal_user');
        define('DB_PASS', $_ENV['DB_PASS'] ?? '');
        define('DB_PORT', $_ENV['DB_PORT'] ?? '3306');
    }

}

// Chat/Real-time Configuration
if (!defined('CHAT_MODE')) {
    // In cPanel/shared hosting, WebSocket servers often don't work
    // Auto-detect: WebSocket for development, AJAX polling for production
    if (ENVIRONMENT === 'development') {
        define('CHAT_MODE', $_ENV['CHAT_MODE'] ?? 'websocket');
        define('CHAT_WS_PORT', $_ENV['CHAT_WS_PORT'] ?? '8082');
    } else {
        // Default to AJAX polling for cPanel compatibility
        define('CHAT_MODE', $_ENV['CHAT_MODE'] ?? 'ajax');
        define('CHAT_WS_PORT', $_ENV['CHAT_WS_PORT'] ?? '');
    }
}

// SSL/HTTPS Detection
if (!defined('IS_HTTPS')) {
    $isHttps = (!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');
    define('IS_HTTPS', $isHttps);
}

// Base URL Configuration
if (!defined('BASE_URL')) {
    $protocol = IS_HTTPS ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    
    // Improved subdirectory detection: 
    // Calculate the difference between the current script's path and the project root
    $projectRoot = realpath(__DIR__ . '/..');
    $scriptPath = realpath($_SERVER['SCRIPT_FILENAME'] ?? '');
    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    
    if ($projectRoot && $scriptPath && $scriptName) {
        $relativeToRoot = str_replace(DIRECTORY_SEPARATOR, '/', str_replace($projectRoot, '', $scriptPath));
        $baseDir = rtrim(str_replace($relativeToRoot, '', $scriptName), '/\\');
    } else {
        // Fallback for CLI or unusual setups
        $baseDir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
    }
    
    define('BASE_URL', $protocol . '://' . $host . $baseDir);
}

// Site Configuration
if (!defined('SITE_NAME')) {
    define('SITE_NAME', $_ENV['SITE_NAME'] ?? 'Go Legal');
}

// Error Handling
if (ENVIRONMENT === 'development') {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    ini_set('log_errors', '1');
} else {
    error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    ini_set('error_log', __DIR__ . '/../logs/error.log');
}

// Session Configuration for cPanel compatibility
// Only set if session hasn't started yet
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_secure', IS_HTTPS ? '1' : '0');
    ini_set('session.use_strict_mode', '1');
    ini_set('session.cookie_samesite', 'Lax');
}

// Timezone
if (!defined('DEFAULT_TIMEZONE')) {
    define('DEFAULT_TIMEZONE', $_ENV['TIMEZONE'] ?? 'Africa/Lagos');
    date_default_timezone_set(DEFAULT_TIMEZONE);
}
