diff --git a/Model.php b/Model.php index d777483..9c91137 100644 --- a/Model.php +++ b/Model.php @@ -33,6 +33,8 @@ protected function joins(object $Query): object /** * Create a Notification + * + * @param string $name * @param int $assignedTo * @param string $title * @param string $content @@ -40,14 +42,118 @@ protected function joins(object $Query): object * @param string $category * @return int */ - public function notify(int $assignedTo, string $title, string $content, string $link = null, string $category = "System"): int + public function notify(string $name, int $assignedTo, string $title, string $content, ?string $link = null, string $category = "System"): int { - return $this->create([ + // Import Global Variables + global $CONFIG, $REQUEST, $SMTP, $AUTH; + + // Initialize Status + $status = 0; + + // Import the Users Model + require_once $CONFIG->root() . '/lib/plugins/users/Model.php'; + + // Initialize the Users Model + $Model = new UsersModel(); + + // Retrieve the Assigned User + $user = $Model->fetch($assignedTo); + + // Retrieve the Notification Settings + $settings = $user['settings']['notifications'] ?? []; + + // Check if the notification settings exist + if (!isset($settings[$name])) { + $settings[$name] = [ + 'email' => false, + 'sms' => false, + 'push' => true + ]; + $Model->update($assignedTo, [ + 'settings' => json_encode(array_merge($user['settings'], [ + 'notifications' => $settings + ])) + ]); + } + + // Allowed Notifications + $allowed = $settings[$name] ?? []; + + // Set the Notification + $notification = [ 'assignedTo' => $assignedTo, 'title' => $title, 'content' => $content, 'link' => $link, 'category' => $category, - ]); + ]; + + // Check if we can create the notification + if(in_array('push', $allowed) && $allowed['push']){ + + // Created Notification + if($this->create($notification)){ + $status += 1; + } + } + + // Check if we can send the notification via email + if(in_array('email', $allowed) && $allowed['email']){ + + // Connect to the smtp server + $SMTP->connect(); + + // Check if the smtp server is connected + if($SMTP->isConnected()){ + + // Authenticate to the SMTP Server + $SMTP->authenticate(); + + // Check if the SMTP Server is authenticated + if($SMTP->isAuthenticated()){ + + // Write the email + $body = ''; + $body .= '
This is an automated '.$category.' notification.
'; + $body .= ''.$content.'
'; + if($link){ + $body .= ''; + $body .= 'View Details'; + $body .= '
'; + } + $body .= 'If you did not expect this message, please ignore it.
'; + + // Create a new message + $eml = $SMTP->message() + ->to($user['username']) + ->from($AUTH->user()->organization()->email ?? $CONFIG->get('smtp','username')) + ->subject($category.' - '.$title) + ->body($body) + ->var('greetings', "Sincerely,