<?php
/**
 * Correo saliente para recuperación de contraseña.
 * Las variables de entorno tienen prioridad. Si no existen, se usa la
 * configuración guardada por el Superadmin en Marca Blanca.
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/CryptoService.php';

$defaultHost = preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST'] ?? 'localhost');
$defaultHost = preg_replace('/^www\./i', '', $defaultHost);
$dbMail = [];

if (isset($pdo) && $pdo instanceof PDO) {
    try {
        $keys = ['mail_transport','mail_host','mail_port','mail_encryption','mail_username','mail_password_enc','mail_from_email','mail_from_name','mail_verify_peer'];
        $placeholders = implode(',', array_fill(0, count($keys), '?'));
        $stmt = $pdo->prepare("SELECT clave, valor FROM configuracion_sistema WHERE clave IN ($placeholders)");
        $stmt->execute($keys);
        $dbMail = $stmt->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
    } catch (Throwable $e) {
        error_log('No se pudo leer la configuración de correo: ' . $e->getMessage());
    }
}

$storedPassword = (string) ($dbMail['mail_password_enc'] ?? '');
$dbPassword = '';
if ($storedPassword !== '') {
    try {
        $dbPassword = CryptoService::decryptOrFail($storedPassword);
    } catch (Throwable $e) {
        error_log('No se pudo descifrar la contraseña SMTP: ' . $e->getMessage());
    }
}

$env = static fn(string $key): string|false => getenv($key);
$envBool = static function (string $key, bool $fallback): bool {
    $value = getenv($key);
    return $value === false ? $fallback : filter_var($value, FILTER_VALIDATE_BOOLEAN);
};

return [
    'transport' => $env('MAIL_TRANSPORT') !== false ? (string) $env('MAIL_TRANSPORT') : (string) ($dbMail['mail_transport'] ?? 'auto'),
    'host' => $env('MAIL_HOST') !== false ? (string) $env('MAIL_HOST') : (string) ($dbMail['mail_host'] ?? ''),
    'port' => (int) ($env('MAIL_PORT') !== false ? $env('MAIL_PORT') : ($dbMail['mail_port'] ?? 587)),
    'encryption' => strtolower((string) ($env('MAIL_ENCRYPTION') !== false ? $env('MAIL_ENCRYPTION') : ($dbMail['mail_encryption'] ?? 'tls'))),
    'username' => $env('MAIL_USERNAME') !== false ? (string) $env('MAIL_USERNAME') : (string) ($dbMail['mail_username'] ?? ''),
    'password' => $env('MAIL_PASSWORD') !== false ? (string) $env('MAIL_PASSWORD') : $dbPassword,
    'from_email' => $env('MAIL_FROM_ADDRESS') !== false ? (string) $env('MAIL_FROM_ADDRESS') : ((string) ($dbMail['mail_from_email'] ?? '') ?: ('no-reply@' . $defaultHost)),
    'from_name' => $env('MAIL_FROM_NAME') !== false ? (string) $env('MAIL_FROM_NAME') : ((string) ($dbMail['mail_from_name'] ?? '') ?: ($ui_title_system ?? 'Ave Fénix')),
    'timeout' => (int) ($env('MAIL_TIMEOUT') !== false ? $env('MAIL_TIMEOUT') : 15),
    'verify_peer' => $envBool('MAIL_VERIFY_PEER', ($dbMail['mail_verify_peer'] ?? '1') === '1'),
];
