<?php
// load_env.php

$envFile = realpath(__DIR__ . '/.env');

if ($envFile && file_exists($envFile)) {
    $envLines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($envLines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) continue; // skip comments
        if (!str_contains($line, '=')) continue; // skip invalid lines

        list($name, $value) = array_map('trim', explode('=', $line, 2));

        // Remove surrounding quotes if present
        if (
            (str_starts_with($value, '"') && str_ends_with($value, '"')) ||
            (str_starts_with($value, "'") && str_ends_with($value, "'"))
        ) {
            $value = substr($value, 1, -1);
        }

        $_ENV[$name] = $value;
        putenv("$name=$value");
    }
} else {
    exit('.env file not found at: ' . __DIR__ . '/.env');
}
