<?php
/**
 * Configuration loader for environment variables
 */

function loadEnv($path) {
    if (!file_exists($path)) {
        throw new Exception('.env file not found. Please copy .env.example to .env and configure your settings.');
    }
    
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) {
            continue; // Skip comments
        }
        
        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        $value = trim($value);
        
        if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
            putenv(sprintf('%s=%s', $name, $value));
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
    }
}

// Load environment variables
try {
    loadEnv(__DIR__ . '/.env');
} catch (Exception $e) {
    error_log('Configuration error: ' . $e->getMessage());
    // In production, you might want to show a generic error page
    if (php_sapi_name() !== 'cli') {
        http_response_code(500);
        die('Configuration error. Please contact the administrator.');
    }
}

// Configuration constants
define('RECAPTCHA_SECRET_KEY', getenv('RECAPTCHA_SECRET_KEY'));
define('RECAPTCHA_SITE_KEY', getenv('RECAPTCHA_SITE_KEY'));
define('CONTACT_EMAIL', getenv('CONTACT_EMAIL'));
define('RATE_LIMIT_SECONDS', (int)getenv('RATE_LIMIT_SECONDS') ?: 180);
define('MAX_REQUESTS_PER_PERIOD', (int)getenv('MAX_REQUESTS_PER_PERIOD') ?: 1);

// Twilio Configuration
define('TWILIO_ACCOUNT_SID', getenv('TWILIO_ACCOUNT_SID'));
define('TWILIO_AUTH_TOKEN', getenv('TWILIO_AUTH_TOKEN'));
define('TWILIO_PHONE_NUMBER', getenv('TWILIO_PHONE_NUMBER'));
define('TWILIO_WEBHOOK_URL', getenv('TWILIO_WEBHOOK_URL'));

// Database Configuration
define('DB_HOST', getenv('DB_HOST') ?: 'localhost');
define('DB_NAME', getenv('DB_NAME'));
define('DB_USER', getenv('DB_USER'));
define('DB_PASS', getenv('DB_PASS'));

// Validate required configuration
$required_config = ['RECAPTCHA_SECRET_KEY', 'RECAPTCHA_SITE_KEY', 'CONTACT_EMAIL'];
foreach ($required_config as $config) {
    if (!constant($config) || empty(constant($config))) {
        error_log("Missing required configuration: $config");
        if (php_sapi_name() !== 'cli') {
            http_response_code(500);
            die('Configuration error. Please contact the administrator.');
        }
    }
}
?>
