<?php
// Mail configuration sourced from environment variables or database.

if (!function_exists('env_val')) {
    function env_val(string $key, $default = null) {
        $v = getenv($key);
        return ($v === false || $v === null || $v === '') ? $default : $v;
    }
}

// Fallback: if critical vars are missing from process env, try to parse executor/.env
if (!function_exists('load_dotenv_if_needed')) {
    function load_dotenv_if_needed(array $keys): void {
        $missing = array_filter($keys, fn($k) => getenv($k) === false || getenv($k) === '');
        if (empty($missing)) return;
        static $loaded = false;
        if ($loaded) return;
        $envPath = realpath(__DIR__ . '/../../.env'); // executor/.env
        if ($envPath && is_readable($envPath)) {
            $lines = @file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
            foreach ($lines as $line) {
                if ($line[0] === '#' || trim($line) === '') continue;
                if (!str_contains($line, '=')) continue;
                [$k, $v] = array_map('trim', explode('=', $line, 2));
                $v = trim($v, "' ");
                if ($k !== '' && (getenv($k) === false || getenv($k) === '')) {
                    putenv("{$k}={$v}");
                }
            }
            $loaded = true;
        }
    }
}

load_dotenv_if_needed([
    'MAIL_TRANSPORT','SMTP_HOST','SMTP_PORT','SMTP_SECURE','SMTP_USER','SMTP_PASS',
    'MAIL_FROM','MAIL_FROM_NAME','MAIL_REPLY_TO','MAIL_TO'
]);

// Fetch from DB if available
$db_settings = [];
try {
    require_once __DIR__ . '/../db/config.php';
    $stmt = db()->query("SELECT * FROM smtp_settings WHERE id = 1");
    $db_settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
} catch (\Throwable $e) {
    // DB not ready or table missing
}

$transport   = env_val('MAIL_TRANSPORT', $db_settings['transport'] ?? 'smtp');
$smtp_host   = env_val('SMTP_HOST',      $db_settings['smtp_host'] ?? '');
$smtp_port   = (int) env_val('SMTP_PORT', $db_settings['smtp_port'] ?? 587);
$smtp_secure = env_val('SMTP_SECURE',    $db_settings['smtp_secure'] ?? 'tls');
$smtp_user   = env_val('SMTP_USER',      $db_settings['smtp_user'] ?? '');
$smtp_pass   = env_val('SMTP_PASS',      $db_settings['smtp_pass'] ?? '');

$from_email  = env_val('MAIL_FROM',      $db_settings['from_email'] ?? 'no-reply@localhost');
$from_name   = env_val('MAIL_FROM_NAME', $db_settings['from_name'] ?? 'App');
$reply_to    = env_val('MAIL_REPLY_TO',  $db_settings['reply_to'] ?? '');

return [
    'transport'   => $transport,
    'smtp_host'   => $smtp_host,
    'smtp_port'   => $smtp_port,
    'smtp_secure' => $smtp_secure,
    'smtp_user'   => $smtp_user,
    'smtp_pass'   => $smtp_pass,
    'from_email'  => $from_email,
    'from_name'   => $from_name,
    'reply_to'    => $reply_to,
];