<?php
// Function to load .env file
if (!function_exists('loadEnv')) {
    function loadEnv($path) {
        if (!file_exists($path)) {
            return false;
        }
        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $line = trim($line);
            // Skip comments or empty lines
            if (empty($line) || strpos($line, '#') === 0) {
                continue;
            }
            
            // Parse line
            if (strpos($line, '=') !== false) {
                list($name, $value) = explode('=', $line, 2);
                $name = trim($name);
                $value = trim($value);
                
                // Strip quotes if any
                if (preg_match('/^"(.*)"$/', $value, $matches)) {
                    $value = $matches[1];
                } elseif (preg_match('/^\'(.*)\'$/', $value, $matches)) {
                    $value = $matches[1];
                }
                
                if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
                    putenv("{$name}={$value}");
                    $_ENV[$name] = $value;
                    $_SERVER[$name] = $value;
                }
            }
        }
        return true;
    }
}

// Load env file
loadEnv(__DIR__ . '/../.env');

// Set connection constants with environment fallbacks
define('DB_SERVER', $_ENV['DB_SERVER'] ?? ($_SERVER['DB_SERVER'] ?? (getenv('DB_SERVER') ?: '')));
define('DB_USER', $_ENV['DB_USER'] ?? ($_SERVER['DB_USER'] ?? (getenv('DB_USER') ?: '')));
define('DB_PASS', $_ENV['DB_PASS'] ?? ($_SERVER['DB_PASS'] ?? (getenv('DB_PASS') !== false ? getenv('') : '')));
define('DB_NAME', $_ENV['DB_NAME'] ?? ($_SERVER['DB_NAME'] ?? (getenv('DB_NAME') ?: '')));

$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
