<?php
// ============================================
// Environment Configuration Loader
// ============================================

// Load environment variables from .env file
function loadEnv($filePath = __DIR__ . '/.env') {
    if (!file_exists($filePath)) {
        // If no .env file exists, use defaults
        return;
    }
    
    $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        // Skip comments
        if (strpos(trim($line), '#') === 0) {
            continue;
        }
        
        // Parse KEY=VALUE
        if (strpos($line, '=') !== false) {
            list($key, $value) = explode('=', $line, 2);
            $key = trim($key);
            $value = trim($value);
            
            // Remove quotes if present
            if ((strpos($value, '"') === 0 && strrpos($value, '"') === strlen($value) - 1) ||
                (strpos($value, "'") === 0 && strrpos($value, "'") === strlen($value) - 1)) {
                $value = substr($value, 1, -1);
            }
            
            // Set environment variable
            $_ENV[$key] = $value;
            putenv("$key=$value");
        }
    }
}

// Load environment configuration
loadEnv();

// Helper function to get configuration values
function config($key, $default = null) {
    return $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key) ?: $default;
}

// Define configuration constants
if (!defined('DB_HOST')) {
    define('DB_HOST', config('DB_HOST', 'localhost'));
    define('DB_USER', config('DB_USER', 'root'));
    define('DB_PASS', config('DB_PASS', ''));
    define('DB_NAME', config('DB_NAME', 'admin_panel'));
    define('APP_NAME', config('APP_NAME', 'JBR Sofa'));
    define('APP_VERSION', config('APP_VERSION', '1.0.0'));
    define('APP_ENV', config('APP_ENV', 'development'));
    define('APP_DEBUG', config('APP_DEBUG', 'false') === 'true');
    define('CURRENCY_SYMBOL', config('CURRENCY_SYMBOL', '₹'));
    define('SESSION_LIFETIME', (int)config('SESSION_LIFETIME', 3600));
    define('LOG_LEVEL', config('LOG_LEVEL', 'error'));
}

// Configure error handling based on environment
if (APP_ENV === 'production') {
    ini_set('display_errors', '0');
    ini_set('display_startup_errors', '0');
    error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
} else {
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
}

// Set session configuration
ini_set('session.gc_maxlifetime', SESSION_LIFETIME);
if (APP_ENV === 'production') {
    ini_set('session.cookie_secure', config('SECURE_COOKIES', 'false') === 'true' ? '1' : '0');
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', config('SAME_SITE_COOKIES', 'Lax'));
}
