donation/app/Controllers/Notifications.php

439 lines
20 KiB
PHP

<?php
namespace App\Controllers;
use App\Helpers\NotificationHelper;
use App\Models\NotificationModel;
class Notifications extends BaseController
{
## Email Section :
public function mail_custom_notifications()
{
$request = \Config\Services::request();
if ($request->is('post')) {
$records = $request->getVar();
$records['template_name'] = "";
helper('notification');
$notification = new NotificationHelper();
$data = $notification->sendEmail($records);
if (isset($data['error'])) {
session()->setFlashdata('error', 'Message: ' . $data['error']);
}
if (isset($data['success'])) {
session()->setFlashdata('success', 'Message: ' . $data['success']);
}
}
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
}
public function whatsapp_custom_notifications()
{
$request = \Config\Services::request();
if ($request->is('post')) {
$records = $request->getVar();
$params = (object) Null;
$this->logger->info("Whatsapp : sending message instance id = " . $_ENV['WAAI_INSTANCE'] ." - ". $_ENV['WAAI_TOKEN']);
try {
if ($records['categories'] == 'SEND_WAAI_GROUP_URL') {
if($records['group_id'] != ""){ $params->group_id = $records['group_id']; }
else{ throw new \Exception("Group Id Missing Please Try again.."); }
}else if ($records['categories'] == 'SEND_WAAI_URL') {
if($records['mobile'] != ""){ $params->number = (int)'91' . $records['mobile']; }
else{ throw new \Exception("Mobile Number Missing Please Try again.."); }
}else{
throw new \Exception("Please Choose your Category");
}
if ($records['type'] == 'media') {
if($records['media_url'] != ""){ $params->media_url = $records['media_url']; }
else{ throw new \Exception("Media Url Missing Please Try again.."); }
}
$url = constant($records['categories']);
$params->type = $records['type'] == "" ? "text" : $records['type'];
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$params->message = $records['description'];
$this->logger->info("Whatsapp : sending message request = " . json_encode($params));
$this->logger->info("Whatsapp : sending message request type b4 = " . gettype($params));
helper('notification');
$notification = new NotificationHelper();
$success = $notification->sendWhatsAppMessage($url, "POST", $params);
session()->setFlashdata('success', 'Message : ' . $success);
$this->logger->info("Whatsapp : Reponse = " . $success);
} catch (\Exception $e) {
$this->logger->error("Whatsapp : Exception Message = " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
session()->setFlashdata('error', 'Message: ' . $e->getMessage());
}
}
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
}
public function due_date_notifications()
{
$date = $this->request->getGet('date');
$model = new NotificationModel();
$details = $model->getSubscriptionDueDetail($date);
// echo "<pre>";
// print_r($details);
// echo "</pre>";
// die;
$records = [];
$recipient_name = "";
$recipient_email = "";
$recipient_mobile = "";
$subscription_name = "";
$business_name= "";
$to_subscription= "";
if (isset($details)) {
$this->logger->info("Notification : Duedate notification Request data type = ".gettype($details));
}
helper('notification');
$notification = new NotificationHelper();
foreach ($details as $rec) {
$recipient_name = $rec['customer_name'];
$recipient_email = $rec['customer_email'];
$recipient_mobile = $rec['customer_mobile'];
// $recipient_email = "sanjeev.p@venbainfotech.com";
// $recipient_mobile = 6369084112;
$business_name= $rec['business_name'];
$subscription_name = $rec['title'];
$to_subscription= $rec['to_subscription'];
}
$records['template_name'] = '';
$records['recipient_name'] = $recipient_name;
$records['recipient_email'] = $recipient_email ? $recipient_email : "sanjeev.p@venbainfotech.com";
$records['subject'] = $business_name ." - Due Date Reminder";
$records['description'] = "<!DOCTYPE html>
<html>
<head><title>Due Date Reminder</title></head>
<body>
<p>Hello ".$recipient_name.",</p>
<p>This is a reminder that the following subscription is due soon:</p>
<p><strong>Subscription Name:</strong>".$subscription_name." </p>
<p><strong>Due Date:</strong> ".$to_subscription."</p>
<p>Please make sure to complete this subscription on time.</p>
<p>Thank you.</p>
</body>
</html>";
$template = "Hello " . $recipient_name . ",\r\r\n\nThis is a reminder that the following subscription is due soon:\r\n- Subscription Name: " . $subscription_name . "\r\n Due Date: " . $to_subscription . "\r\n\nPlease make sure to complete this subscription on time.\n Thank you.";
$params = (object) Null;
$params->number = (int)'91' . $recipient_mobile;
$params->type = "text";
$params->message = $template;
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$this->logger->info("Notification : Duedate notification Email Request data = ".json_encode($records));
$email_result = $notification->sendEmail($records);
$this->logger->info("Notification : Duedate notification Email Response = " . json_encode($email_result));
$this->logger->info("Notification : Duedate notification Whatsapp Request data = ".json_encode($params));
$whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
$this->logger->info("Notification : Duedate notification Whatsapp Response = " . json_encode($whatsapp_result));
}
public function template_creation(){
$data['page_name'] = 'Template Details';
$model = new NotificationModel();
$data['template'] = $model->getTemplateDetails();
$this->render_page('template_creation', $data);
// echo "templates";die;
}
public function template_creation_form($id){
$data['group_details'] = $this->get_group_details();
$model = new NotificationModel();
if ($id === '0') {
$this->logger->info("Template Creation: In Add Page");
$data['page_name'] = 'Add Template';
$data['template_details'] = [];
} elseif ($id !== '0') {
$this->logger->info("Template Creation: In Edit Page ID =" . $id);
$data['page_name'] = 'Edit Template';
$model->setTable('templates');
$where = ['template_id'=>(int)$id];
$result = $model->where($where)->findAll();
$data['template_details'] = !empty($result[0]) ? $result[0] : [];
}
// print_r($data['template_details']);die();
$this->render_page('template_creation_form', $data);
}
public function template_creation_delete($id){
try {
helper('session');
$session_uid = get_logged_user_id();
$model = new NotificationModel();
$model->setTable('templates');
$where = ['template_id'=>(int)$id];
$result = $model->where($where)->findAll();
if ($result) {
$this->logger->Info("Template: Going to Inactive ID = ".$id);
$data = ['isactive' => 0 , 'updated_by' => $session_uid,'template_id'=>(int)$id];
$statement = $model->saveDetails($data,'template_id','templates');// just updating Inactive status only.
if ($statement['success']) {
session()->setFlashdata('success', $statement['success'] ? 'Deleted successfully.' : "" );
$this->logger->info($statement['log']);
} else if ($statement['error']) {
session()->setFlashdata('error', $statement['error']);
$this->logger->error($statement['log']);
}else{
throw new \Exception("Template: Err Occur on data the Template Inactive");
}
}
} catch (\Exception $e) {
$this->logger->error("Template: Err Occur = ".$e->getMessage()." File = ". $e->getFile() . " Line = " . $e->getLine());
session()->setFlashdata('error', 'Message: ' . $e->getMessage());
}
return redirect()->route('template_creation');
}
public function get_group_details()
{
$model = new NotificationModel();
$model->setTable('customer_groups');
// $details = $model->where('isactive',1)->orderBy('group_id', 'ASC')->findAll();
$where = ['isactive' => 1, 'group_name != ' => 'EXPIRYDATE'];
$details = $model->where($where)->orderBy('group_id', 'ASC')->findAll();
return $details;
}
public function get_template_details(){
$model = new NotificationModel();
$model->setTable('templates');
$details = $model->where('isactive',1)->orderBy('template_id', 'ASC')->findAll();
return $details;
}
public function template_creation_insert(){
$this->logger->info("Template: Inserting/Updating Details");
try {
## Declarions
helper('session');
$model = new NotificationModel();
$session_uid = get_logged_user_id();
$id = $this->request->getPost('template_id');
$subject = $this->request->getPost('subject') ? $this->request->getPost('subject') : NULL;
$isactive = $id != "" ? $this->request->getPost('isactive') : 'on';
$data = [
'template_id' => $id,
'template_name' => $this->request->getPost('templatename'),
'subject' => $subject,
'message' => $this->request->getPost('templatemessage'),
'mode' => $this->request->getPost('mode'),
'isactive' => (($isactive == 'on') ? 1 : 0),
'created_by' => $session_uid,
'updated_by' => $session_uid
];
$statement = $model->saveDetails($data,'template_id','templates');
if ($statement['success']) {
session()->setFlashdata('success', $statement['success']);
$this->logger->info($statement['log']);
} else if ($statement['error']) {
session()->setFlashdata('error', $statement['error']);
$this->logger->error($statement['log']);
}else{
throw new \Exception("Template: Err Occur");
}
}catch(\Exception $e) {
$this->logger->error("Template: Err Occur =".$e->getMessage());
session()->setFlashdata('error', 'Message: ' .$e->getMessage());
}
return redirect()->route('template_creation');
}
public function campaign_creation(){
$data['page_name'] = 'Campaign Details';
$model = new NotificationModel();
$data['campaign'] = $model->getCampaignDetails();
$this->render_page('campaign_creation', $data);
// echo "templates";die;
}
public function campaign_creation_form($id){
$data['group_details'] = $this->get_group_details();
$data['template_details'] = $this->get_template_details();
$model = new NotificationModel();
if ($id === '0') {
$this->logger->info("Campaign Creation: In Add Page");
$data['page_name'] = 'Add Campaign';
$data['campaign_details'] = [];
} elseif ($id !== '0') {
$this->logger->info("Campaign Creation: In Edit Page ID =" . $id);
$data['page_name'] = 'Edit Campaign';
$model->setTable('notification_campaign');
$where = ['campaign_id'=>(int)$id];
$result = $model->where($where)->findAll();
if (!empty($result)) {
foreach ($result as $i => $item) {
$result[$i]['group_id'] = unserialize($item['group_id']);
}
}
$data['campaign_details'] = !empty($result[0]) ? $result[0] : [];
}
$this->render_page('campaign_creation_form', $data);
}
public function campaign_creation_delete($id){
try {
helper('session');
$session_uid = get_logged_user_id();
$model = new NotificationModel();
$model->setTable('templates');
$where = ['campaign_id'=>(int)$id];
$result = $model->where($where)->findAll();
if ($result) {
$this->logger->Info("Campaign: Going to Inactive ID = ".$id);
$data = ['isactive' => 0 , 'updated_by' => $session_uid,'campaign_id'=>(int)$id];
$statement = $model->saveDetails($data,'campaign_id','notification_campaign');// just updating Inactive status only.
if ($statement['success']) {
session()->setFlashdata('success', $statement['success'] ? 'Deleted successfully.' : "" );
$this->logger->info($statement['log']);
} else if ($statement['error']) {
session()->setFlashdata('error', $statement['error']);
$this->logger->error($statement['log']);
}else{
throw new \Exception("Campaign: Err Occur on data the Template Inactive");
}
}
} catch (\Exception $e) {
$this->logger->error("Campaign: Err Occur = ".$e->getMessage()." File = ". $e->getFile() . " Line = " . $e->getLine());
session()->setFlashdata('error', 'Message: ' . $e->getMessage());
}
return redirect()->route('campaign_creation');
}
public function campaign_creation_insert(){
$this->logger->info("Campaign: Inserting/Updating Details");
try {
## Declarions
helper('session');
$model = new NotificationModel();
$session_uid = get_logged_user_id();
$id = $this->request->getPost('campaign_id');
$isactive = $this->request->getPost('isactive');
// print_r($this->request->getPost());die;
$data = [
'campaign_id' => $id,
'campaign_name' => $this->request->getPost('campaign_name'),
'template_id' => $this->request->getPost('template_id'),
'scheduled_date' => $this->request->getPost('scheduled_date'),
'scheduled_time' => $this->request->getPost('scheduled_time'),
'mode' => $this->request->getPost('mode'),
'group_id' => serialize($this->request->getPost('group_id')),
'isactive' => $id ? (($isactive == 'on') ? 1 : 0) : 1,
'created_by' => $session_uid,
'updated_by' => $session_uid
];
$statement = $model->saveDetails($data,'campaign_id','notification_campaign');
if ($statement['success']) {
session()->setFlashdata('success', $statement['success']);
$this->logger->info($statement['log']);
} else if ($statement['error']) {
session()->setFlashdata('error', $statement['error']);
$this->logger->error($statement['log']);
}else{
throw new \Exception("Campaign: Err Occur");
}
}catch(\Exception $e) {
$this->logger->error("Campaign: Err Occur =".$e->getMessage());
session()->setFlashdata('error', 'Message: ' .$e->getMessage());
}
return redirect()->route('campaign_creation');
}
public function getExpCustomerDetail($window_time = null)
{
// Step 1: add the days to retrive th e data//
$providedDate = date('Y-m-d');
$newDate = date('Y-m-d', strtotime($providedDate . ' + ' . $window_time . ' days'));
// Step 2 :Get the custoemr detail//
$NotificationModel = new NotificationModel();
$ExpCustomerDetail = $NotificationModel->getExpDate(); // Retrieve the stored query
if (empty($ExpCustomerDetail)) {
$this->logger->info('There is no query');
return;
}
//Step 3: Replace the placeholder WINDOW_TIME with the user-provided value
$modifiedQuery = str_replace('WINDOW_TIME', $window_time, $ExpCustomerDetail);
// print_r($modifiedQuery);die;
if (empty($modifiedQuery)) {
$this->logger->info('There is no sub query');
return;
}
$db = \Config\Database::connect();
$queryResult = $db->query($modifiedQuery)->getResultArray();
$notification = new NotificationHelper();
if (empty($queryResult)) {
$this->logger->info("There is no data against customer on given date:{$newDate}");
return;
}
foreach ($queryResult as $row) {
$templateName = $NotificationModel->getTempName();
if (empty($templateName)) {
$this->logger->info('There is no template found');
return;
}
$userFirstName = $row['first_name'];
$userLastName = $row['last_name'];
$fullName = $userFirstName . ' ' . $userLastName;
$schemename = $row['title'];
$expirydate = $row['to_subscription'];
if (empty($fullName)) {
$this->logger->info('There is no subcription Name');
return;
}
//Step 4: Prepare email content based on the template
$emailContent = $templateName[0]['message'];
$emailContent = str_replace("{User}", $fullName, $emailContent);
$emailContent = str_replace("{SCHEME_NAME}", $schemename, $emailContent);
$emailContent = str_replace("{EXPIRY_DATE}", $expirydate, $emailContent);
$emailData = [
'template_name'=>'',
'recipient_email' => $row['email'],
'subject' => 'Your Subscription Expiry Notification',
'description' =>$emailContent,
];
// Step 5:Send email using NotificationHelper
$emailResult = $notification->sendEmail($emailData);
if (isset($emailResult['success'])) {
echo 'Email sent successfully';
} else {
echo 'Failed to send email';
}
$templateName = $NotificationModel->getTempName();
}
}
}