resultRedirectFactory->create()->setPath('*/*/index'); try { $title = trim((string)$this->getRequest()->getParam('title')); $content = trim((string)$this->getRequest()->getParam('content')); $rawEmails = preg_split('/[\s,;]+/', (string)$this->getRequest()->getParam('customer_emails')); $emails = array_values(array_unique(array_filter(array_map('trim', $rawEmails ?: [])))); if ($title === '' || $content === '' || !$emails) { throw new LocalizedException(__('Title, content and at least one customer email are required.')); } $customerIds = $this->customers->create()->addFieldToFilter('email', ['in' => $emails])->getAllIds(); if (!$customerIds) { throw new LocalizedException(__('No matching customers were found.')); } $connection = $this->resource->getConnection(); $connection->beginTransaction(); $connection->insert($this->resource->getTableName('esun_customer_message'), [ 'title' => $title, 'content' => $content, 'message_type' => (string)$this->getRequest()->getParam('message_type', 'notice'), 'store_id' => (int)$this->getRequest()->getParam('store_id', 0), 'is_active' => 1, 'expires_at' => trim((string)$this->getRequest()->getParam('expires_at')) ?: null, ]); $messageId = (int)$connection->lastInsertId(); foreach ($customerIds as $customerId) { $connection->insert($this->resource->getTableName('esun_customer_message_recipient'), [ 'message_id' => $messageId, 'customer_id' => (int)$customerId, ]); } $connection->commit(); $this->messageManager->addSuccessMessage(__('The message was sent to %1 customer(s).', count($customerIds))); } catch (\Throwable $e) { if ($this->resource->getConnection()->getTransactionLevel() > 0) { $this->resource->getConnection()->rollBack(); } $this->messageManager->addErrorMessage( $e instanceof LocalizedException ? $e->getMessage() : __('The message could not be saved.') ); } return $result; } }