renderWhatsappContent($templateSid, $variables); $payload = [ 'status' => $this->statusToStore ? $this->statusToStore : $this->status, 'to' => $to, 'template_name' => $templateName, 'template_sid' => $templateSid, 'variables' => $variables, 'content' => $content, // The rendered message with variables substituted 'result' => $result, 'sent_at' => $success ? current_time('mysql') : null, 'error' => !$success ? ($result['message'] ?? 'Unknown error') : null, ]; // Add message_sid and conversation_id if available if ($success && isset($result['data'])) { if (isset($result['data']['sid'])) { $payload['message_sid'] = $result['data']['sid']; } if (isset($result['data']['message_id'])) { $payload['message_id'] = $result['data']['message_id']; } if (isset($result['data']['conversation_id'])) { $payload['conversation_id'] = $result['data']['conversation_id']; } } $notification = BookingNotification::create([ 'restaurant_id' => $this->restaurant->id, 'booking_id' => $this->id, 'type' => $type, 'type_id' => $type_id, 'payload' => $payload ]); $notification->save(); return $notification; } /** * Render the WhatsApp content by replacing variables in the template body * * @param string $templateSid The template SID * @param array $variables The variables to replace (can be keyed by name or number) * @return string|null The rendered content or null if template not found */ protected function renderWhatsappContent($templateSid, $variables = []) { if (empty($templateSid)) { return null; } // Get the cached template with body $template = WhatsappTemplate::getTemplateBySid($this->restaurant_id, $templateSid); if (!$template || empty($template['body'])) { // If template body not available, return a simple representation return $this->renderVariablesAsText($variables); } $body = $template['body']; // Replace variables in the template body // Templates can have variables like {{1}}, {{2}} or {{name}}, {{date}} foreach ($variables as $key => $value) { // Replace {{key}} format (both numeric and named) $body = str_replace('{{' . $key . '}}', $value, $body); } return $body; } /** * Render variables as a simple text representation when template body is not available * * @param array $variables * @return string */ protected function renderVariablesAsText($variables) { if (empty($variables)) { return ''; } $parts = []; foreach ($variables as $key => $value) { $parts[] = "{$key}: {$value}"; } return implode(' | ', $parts); } }