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

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',
    'DKIM_DOMAIN','DKIM_SELECTOR','DKIM_PRIVATE_KEY_PATH'
]);

// 1. Defaults from Environment
$transport   = env_val('MAIL_TRANSPORT', 'smtp');
$smtp_host   = env_val('SMTP_HOST');
$smtp_port   = (int) env_val('SMTP_PORT', 587);
$smtp_secure = env_val('SMTP_SECURE', 'tls'); // tls | ssl | null
$smtp_user   = env_val('SMTP_USER');
$smtp_pass   = env_val('SMTP_PASS');

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

$dkim_domain           = env_val('DKIM_DOMAIN');
$dkim_selector         = env_val('DKIM_SELECTOR');
$dkim_private_key_path = env_val('DKIM_PRIVATE_KEY_PATH');

// 2. Override from Database (if available)
if (file_exists(__DIR__ . '/../db/config.php')) {
    require_once __DIR__ . '/../db/config.php';
    if (function_exists('db')) {
        try {
            $pdo = db();
            // Check if settings table exists to avoid errors during fresh install/migration
            $checkTable = $pdo->query("SHOW TABLES LIKE 'settings'");
            if ($checkTable->rowCount() > 0) {
                $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'smtp_%'");
                $db_settings = [];
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $db_settings[$row['setting_key']] = $row['setting_value'];
                }

                if (!empty($db_settings['smtp_host'])) $smtp_host = $db_settings['smtp_host'];
                if (!empty($db_settings['smtp_port'])) $smtp_port = (int)$db_settings['smtp_port'];
                if (isset($db_settings['smtp_user'])) $smtp_user = $db_settings['smtp_user'];
                if (isset($db_settings['smtp_pass'])) $smtp_pass = $db_settings['smtp_pass'];
                if (isset($db_settings['smtp_secure'])) $smtp_secure = $db_settings['smtp_secure'];
                if (!empty($db_settings['smtp_from_email'])) $from_email = $db_settings['smtp_from_email'];
                if (!empty($db_settings['smtp_from_name'])) $from_name = $db_settings['smtp_from_name'];
            }
        } catch (Exception $e) {
            // Ignore DB errors (e.g. connection issues or during installation)
        }
    }
}

return [
    'transport'   => $transport,

    // SMTP
    'smtp_host'   => $smtp_host,
    'smtp_port'   => $smtp_port,
    'smtp_secure' => $smtp_secure,
    'smtp_user'   => $smtp_user,
    'smtp_pass'   => $smtp_pass,

    // From / Reply-To
    'from_email'  => $from_email,
    'from_name'   => $from_name,
    'reply_to'    => $reply_to,

    // DKIM (optional)
    'dkim_domain'           => $dkim_domain,
    'dkim_selector'         => $dkim_selector,
    'dkim_private_key_path' => $dkim_private_key_path,
];
