39038-vm/includes/NotificationService.php
2026-03-08 10:29:50 +00:00

77 lines
2.8 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../mail/MailService.php';
require_once __DIR__ . '/app.php';
class NotificationService
{
/**
* Send a notification for a specific event.
*
* @param string $eventName The event name (e.g., 'shipment_created')
* @param array $user The recipient user array (must contain 'email' and 'full_name')
* @param array $data Data to replace in placeholders (e.g., ['shipment_id' => 123])
* @param string|null $lang 'en' or 'ar'. If null, sends both combined.
*/
public static function send(string $eventName, array $user, array $data = [], ?string $lang = null)
{
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM notification_templates WHERE event_name = ?");
$stmt->execute([$eventName]);
$template = $stmt->fetch();
if (!$template) {
error_log("Notification template not found: $eventName");
return;
}
// Prepare data for replacement
$placeholders = [];
$values = [];
$data['user_name'] = $user['full_name'] ?? 'User';
foreach ($data as $key => $val) {
$placeholders[] = '{' . $key . '}';
$values[] = $val;
}
// Determine Subject and Body based on Lang
$subject = '';
$body = '';
$whatsapp = '';
if ($lang === 'en') {
$subject = $template['email_subject_en'];
$body = $template['email_body_en'];
$whatsapp = $template['whatsapp_body_en'];
} elseif ($lang === 'ar') {
$subject = $template['email_subject_ar'];
$body = $template['email_body_ar'];
$whatsapp = $template['whatsapp_body_ar'];
} else {
// Combined
$subject = $template['email_subject_en'] . ' / ' . $template['email_subject_ar'];
$body = $template['email_body_en'] . "\n\n---\n\n" . $template['email_body_ar'];
$whatsapp = $template['whatsapp_body_en'] . "\n\n" . $template['whatsapp_body_ar'];
}
// Replace
$subject = str_replace($placeholders, $values, $subject);
$body = str_replace($placeholders, $values, $body);
$whatsapp = str_replace($placeholders, $values, $whatsapp);
// Send Email
if (!empty($user['email'])) {
// Convert newlines to BR for HTML
$htmlBody = nl2br(htmlspecialchars($body));
MailService::sendMail($user['email'], $subject, $htmlBody, $body);
}
// Send WhatsApp if enabled
if (get_setting('whatsapp_enabled') === '1') {
// Log WhatsApp (Mock)
// In a real app, this would call Twilio/Meta API
error_log("WHATSAPP Notification to {$user['email']} (Phone N/A): $whatsapp");
}
}
}