Files
portal-api/app/Services/VirtualMachine/VmCredentialsEmailDataBuilder.php

75 lines
3.0 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\VirtualMachine;
use App\Models\ModuleVmware;
use App\Models\OrderItem;
use App\Models\Setting;
/**
* Builds the email payload for VPS credential emails — shared by the
* initial provisioning send (SendVmCredentialsEmailJob) and the admin
* "resend" action (ResendVmCredentialsEmailJob).
*/
class VmCredentialsEmailDataBuilder
{
public function build(ModuleVmware $vm, ?OrderItem $orderItem): array
{
$setting = Setting::where('key', 'setting')->first();
$settingValue = $setting ? json_decode((string) $setting->value) : null;
$months = (int) ($orderItem?->months ?? 0);
$osGroupName = $vm->os?->osGroup?->name ?? '';
$isWindows = str_contains(strtolower($osGroupName), 'windows');
$osUsername = $isWindows ? 'Administrator' : 'root';
return $this->safeUtf8([
'company_name' => $settingValue->company ?? 'Thế Giới Số',
'company_logo' => $settingValue->logo ?? '',
'client_name' => $vm->customer->fullname ?? '',
'product_name' => $orderItem?->getProductAttribute()?->name ?? 'Cloud VPS',
'product_billing' => $this->billingLabel($months),
'product_price' => $orderItem ? number_format((float) $orderItem->price, 0, ',', '.') : 'N/A',
'service_host' => $vm->ip ?? 'N/A',
'service_username' => $osUsername,
'service_port' => (string) ($vm->port ?? '22'),
'service_password' => $vm->plain_password ?? '(xem tai khoan quan ly)',
'os_name' => $vm->os ? ($osGroupName . ' ' . $vm->os->version) : 'Unknown OS',
'service_due_exp' => $vm->next_due_date
? date('d/m/Y', (int) $vm->next_due_date)
: 'N/A',
]);
}
private function billingLabel(?int $months): string
{
return match (true) {
$months === 1 => 'Hàng tháng',
$months === 12 => 'Hàng năm',
$months > 12 && $months % 12 === 0 => ($months / 12) . ' năm',
default => ($months ?? 0) . ' tháng',
};
}
/**
* Sanitize tất cả string trong array thành UTF-8 hợp lệ.
* Loại bỏ ký tự binary/invalid trước khi đẩy vào queue (tránh JSON encode lỗi).
*/
private function safeUtf8(array $data): array
{
return array_map(function ($value) {
if (!is_string($value)) return $value;
if (mb_check_encoding($value, 'UTF-8')) return $value;
$converted = mb_convert_encoding($value, 'UTF-8', mb_detect_encoding($value, ['UTF-8', 'ISO-8859-1', 'Windows-1252'], true) ?: 'ISO-8859-1');
return mb_check_encoding($converted, 'UTF-8')
? $converted
: preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|[^\x09\x0A\x0D\x20-\x{10FFFF}]/u', '', $value);
}, $data);
}
}