<?php declare(strict_types=1);

// --- NATIVE .ENV PARSER ---
$envPath = dirname(__DIR__) . '/.env';
if (file_exists($envPath)) {
    $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        
        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        // Safely trim whitespace and optional double quotes from the env value
        $value = trim($value, " \t\n\r\0\x0B\""); 
        
        if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
            putenv(sprintf('%s=%s', $name, $value));
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
    }
}

// Database Routing
define('DB_HOST', $_ENV['DB_HOST'] ?? 'localhost');
define('DB_USER', $_ENV['DB_USER'] ?? 'root');
define('DB_PASS', $_ENV['DB_PASS'] ?? '');
define('DB_NAME', $_ENV['DB_NAME'] ?? 'jobcardpro_db');

// Application Roots
// APPROOT remains dynamic to map the absolute server path automatically
define('APPROOT', dirname(__DIR__)); 
define('URLROOT', $_ENV['APP_URL'] ?? 'http://jobcardpro.local');
define('SITENAME', $_ENV['APP_NAME'] ?? 'Jobcard Manager Pro');

// Localization & Default Rates
date_default_timezone_set($_ENV['APP_TIMEZONE'] ?? 'Africa/Johannesburg');
define('DEFAULT_CURRENCY', $_ENV['APP_CURRENCY'] ?? 'ZAR');
define('VAT_RATE', isset($_ENV['APP_VAT_RATE']) ? (float)$_ENV['APP_VAT_RATE'] : 0.15);