donation/app/Controllers/Notifications.php
2024-06-18 06:37:52 +00:00

789 lines
40 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use App\Helpers\NotificationHelper;
use App\Models\NotificationModel;
class Notifications extends BaseController
{
################################################################
# Custom Email Notification
################################################################
public function mail_custom_notifications()
{
if ($this->request->is('post')) {
$records = $this->request->getVar();
helper('notification');
$notification = new NotificationHelper();
$data = $notification->sendEmail($records);
$parents_status = 0;
$receiving_status = 0;
if (isset($data['error'])) {
session()->setFlashdata('error', 'Message: ' . $data['error']);
$history_msg = $data;
}
if (isset($data['success'])) {
session()->setFlashdata('success', 'Message: ' . $data['success']);
$parents_status = 1;
$receiving_status = 1;
$history_msg = 'Email sent successfully';
}
$history_msg = (strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg)) ;
$NotificationModel = new NotificationModel();
$history_parents_data = ['campaign_id' => 0,'status' => $parents_status];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
$history_child_data = [ 'fkid' => $history_parent_id,
'donor_id' => 0,
'receiving_entity' => $records['recipient_email'],
'receiving_status' => $receiving_status,
'message' => $records['description'],
'result'=>strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg)];
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
$this->logger->info('Custom Notifications Email : historychildid = '.$history_child_id);
}
$records = [];
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
}
# mail custom notifications closed
################################################################
# Custom Whatsapp Notification
################################################################
public function whatsapp_custom_notifications()
{
if ($this->request->is('post')) {
$records = $this->request->getVar();
$params = (object) Null;
$parents_status = 0;
$receiving_status = 0;
$this->logger->info("Whatsapp : sending message instance id = " . '65C9B978325A2' . " - " . '65c715e797d16');
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..");
}
if ($records['mobile'] != "") {
$params->number = (int)'91' . $records['mobile'];
} else {
throw new \Exception("Mobile Number 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 = '65C9B978325A2';
$params->access_token = '65c715e797d16';
$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);
$receiving_status = $success['receiving_status'];
$parents_status = $success['receiving_status'];
$history_msg = strtolower(gettype($success)) == "string" ? $success : json_encode($success['reponse']);
session()->setFlashdata('success', 'Message : Success');
$this->logger->info("Whatsapp : Reponse = " . $success['message']);
} catch (\Exception $e) {
$this->logger->error("Whatsapp : Exception Message = " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
session()->setFlashdata('error', 'Message: Failed');
$history_msg = strtolower(gettype($success)) == "string" ? $success : json_encode($success['reponse']);
}
$NotificationModel = new NotificationModel();
$history_parents_data = ['campaign_id' => 0,'status' => $parents_status];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
$history_child_data = [ 'fkid' => $history_parent_id,
'donor_id' => 0,
'receiving_entity' => $records['mobile'],
'receiving_status' => $receiving_status,
'message' => $records['description'],
'result'=>$history_msg];
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
}
$records = [];
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
$this->logger->info('Custom Notifications Whatsapp : historychildid = '.$history_child_id);
}
# whatsapp custom notifications closed
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()
{
$session_bid = get_business_id();
$data['page_name'] = 'Template Details';
$model = new NotificationModel();
$data['template'] = $model->getTemplateDetails($session_bid);
$this->render_page('template_creation', $data);
// echo "templates";die;
}
##################################################################
# Template Creation Insertion/updation Process ReferWith : Sanjeev
##################################################################
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);
}
##############################################################################
# Template Creation Delection which means inactive Process ReferWith : Sanjeev
##############################################################################
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('donor_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(['templates.isactive' => 1])
->whereNotIn('templates.template_name',array('EXPIRAY_NOTIFY_TEMPLATE_EMAIL','EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP'))
->orderBy('templates.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';
$templatemessage = "";
if($this->request->getPost('mode') === "Email"){
$templatemessage = $this->request->getPost('templatemessage');
}else if($this->request->getPost('mode') === "Whatsapp"){
$templatemessage = $this->request->getPost('whatsapptemplatemessage');
}
$data = [
'template_id' => $id,
'template_name' => $this->request->getPost('templatename'),
'subject' => $subject,
'message' => $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');
}
//Campaign Creation
public function campaign_creation()
{ $session_bid = get_business_id();
$data['page_name'] = 'Campaign Details';
$model = new NotificationModel();
$data['campaign'] = $model->getCampaignDetails($session_bid);
$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_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');
$request_data = $this->request->getPost();
$isactive = $id == "" ? 1 : (isset($request_data['isactive']) && $request_data['isactive'] == 'on' ? 1 : 0);
$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') != "" ? $this->request->getPost('scheduled_time') : NULL,
'mode' => $this->request->getPost('mode'),
'group_id' => serialize($this->request->getPost('group_id')),
'isactive' => $isactive,
'created_by' => $session_uid,
'updated_by' => $session_uid
];
if ($id != "") {
$notify_mod = new NotificationModel();
$notify_mod->setTable('notification_campaign');
$where = ['campaign_id' => (int)$id];
$isactive_check = $notify_mod->where($where)->select('isactive')->first();
if ((int)$isactive_check['isactive'] === 0 && $isactive === 0) {
$statement['success'] = 'Notification Campaign already In-Active. can`t able to update.';
$statement['error'] = "";
$statement['log'] = "Notification Campaign: already inactive status.Can`t able to update, Notification Campaign Group ID = " . $id;
} else {
$statement = $model->saveDetails($data, 'campaign_id', 'notification_campaign');
}
} else {
$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 campaign_creation_delete($id)
{
try {
helper('session');
$session_uid = get_logged_user_id();
$model = new NotificationModel();
$model->setTable('notification_campaign');
$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');
}
################################################################
# Expiry Notification ReferWith : Hema
################################################################
public function getExpCustomerDetail($window_time = null)
{
# Step 1: add the days to retrive the data//
$providedDate = date('Y-m-d');
$newDate = date('Y-m-d', strtotime($providedDate . ' + ' . $window_time . ' days'));
$this->logger->info('EXPIRYDATE T-Date = '.$providedDate.', Given ' .$window_time.' Day, Calacuated Date based on Given days = '.$newDate);
# Step 2 :Get the customer detail//
$NotificationModel = new NotificationModel();
$ExpCustomerDetail = $NotificationModel->getExpDate(); // Retrieve the stored query
if (empty($ExpCustomerDetail)) {
$this->logger->info('No customer group found by the name of EXPIRYDATE');
return;
}
# Step 3: Replace the placeholder WINDOW_TIME with the user-provided value
$modifiedQuery = str_replace('WINDOW_TIME', $window_time, $ExpCustomerDetail);
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 customer expiring on date:{$newDate}");
return;
}
$emailTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_EMAIL);
foreach ($queryResult as $row) {
$userFirstName = $row['first_name'];
$userLastName = $row['last_name'];
$fullName = $userFirstName . ' ' . $userLastName;
$userMobileNumber = $row['mobile_no'];
$schemename = $row['title'];
$expirydate = $row['to_subscription'];
$customerId = $row['donor_id'];
if (empty($fullName)) {
$this->logger->info('There is no subcription Name');
continue;
}
# EXPIRAY_NOTIFY_TEMPLATE_EMAIL
$emailTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_EMAIL);
if (!empty($emailTemplateName)) {
$campaign_id = 1;
# Insertion on History Email Means Campaign ID 1 Hardcoded
$history_parents_data = ['campaign_id' => $campaign_id,'status' => 0];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
# Step 4: Prepare email content based on the template
$emailContent = $emailTemplateName[0]['message'];
$emailContent = str_replace("{USER_NAME}", $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,
];
$history_child_data = [ 'fkid' => $history_parent_id,
'donor_id' => $customerId,
'receiving_entity' => $row['email'],
'receiving_status' => 0,
'message' => $emailContent];
# Step 5: Insertion on History Child
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
# Step 6:Send email using NotificationHelper
$emailResult = $notification->sendEmail($emailData);
$this->logger->info("EXPIRAY NOTIFY TEMPLATE EMAIL Email CID = ".$customerId." ".json_encode($emailResult));
if (isset($emailResult['success'])) {
$history_msg = 'Email sent successfully';
$receiving_status = 1 ;
echo $history_msg;
} else {
$history_msg = (strtolower(gettype($emailResult)) == "string" ? $emailResult : json_encode($emailResult)) ;
$receiving_status = 0 ;
echo 'Failed to send email';
}
} else {
$history_msg = 'There is no email template found by the name of EXPIRAY_NOTIFY_TEMPLATE_EMAIL';
$receiving_status = 0 ;
$this->logger->info($history_msg);
continue;
}
# EXPIRAY_NOTIFY_TEMPLATE_EMAIL Closed
# EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP
$whatsappTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP);
if (!empty($whatsappTemplateName)) {
$campaign_id = 2;
if (empty($userMobileNumber)) {
$history_msg = 'There is no subscriber mobile number';
$this->logger->info($history_msg);
continue;
}
# Insertion on History Whatsapp Means Campaign ID 2 Hardcoded
$history_parents_data = ['campaign_id' => $campaign_id,'status' => 0];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
# Step 7: Prepare whatsapp content based on the template
$whatsappContent = $whatsappTemplateName[0]['message'];
$whatsappContent = str_replace("{USER_NAME}", $fullName, $emailContent);
$whatsappContent = str_replace("{SCHEME_NAME}", $schemename, $emailContent);
$whatsappContent = str_replace("{EXPIRY_DATE}", $expirydate, $emailContent);
# Step 8: Insertion on History Child for whatsapp
$history_child_data = [ 'fkid' => $history_parent_id,
'donor_id' => $customerId,
'receiving_entity' => $userMobileNumber,
'receiving_status' => 0,
'message' => $whatsappContent];
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
# Step 8: Send Whatsapp using NotificationHelper
$params = (object) Null;
$url = SEND_WAAI_URL;
$params->number = (int)'91' . $userMobileNumber;
$params->type = "text";
$params->message = $whatsappContent;
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$this->logger->info("EXPIRAY NOTIFY TEMPLATE WHATSAPP Request = " . json_encode($params));
$this->logger->info("EXPIRAY NOTIFY TEMPLATE WHATSAPP Request type b4 = " . gettype($params));
$whatsapp_result = $notification->sendWhatsAppMessage($url, "POST", $params);
$this->logger->info("EXPIRAY NOTIFY TEMPLATE WHATSAPP Reponse = " . $whatsapp_result['message']);
$receiving_status = $whatsapp_result['receiving_status'];
$history_msg = strtolower(gettype($whatsapp_result)) == "string" ? $whatsapp_result : json_encode($whatsapp_result['reponse']);
} else {
$receiving_status = 0;
$history_msg = 'There is no Whatsapp template found by the name of EXPIRAY NOTIFY TEMPLATE WHATSAPP ';
$this->logger->info($history_msg);
continue;
}
# EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP Closed
$history_child_where = ['fkid' => $history_parent_id,'id' => (int)$history_child_id];
$history_child_updatedata = ['receiving_status'=>$receiving_status,'result'=>$history_msg];
$history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata,$history_child_where);
$this->logger->info($history_child_statement);
$history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,$campaign_id);
$this->logger->info($history_parent_statement);
}
# Loop Closed
}
# getExpCustomerDetail fns Closed
################################################################
# Auto Scheduled Notification
################################################################
## notification campaign details
public function processScheduledNotifications(){
$this->logger->info("Auto Scheduled Notification Started");
$model = new NotificationModel();
#step 1 get scheduled notification details
$notification_campaign_result = $this->getScheduledNotificationDetails();
$this->logger->info("Auto Scheduled Campaign Details Count = ".count($notification_campaign_result));
if(!count($notification_campaign_result))
{
$this->logger->info("No Auto Scheduled Notification in DB,exiting...!");
$this->logger->info("Auto Scheduled Notification Ends");
exit();
}
//looping multiple notification campaign
if(count($notification_campaign_result))
{
foreach($notification_campaign_result as $index => $single_campaign)
{
#step 2 get template details
$template = $this->getTemplateDetails($single_campaign['template_id']);
$this->logger->info("Auto Scheduled Template Details TID = ".$single_campaign['template_id']);
if(count($template))
{
#step 2.1
$history_parents_data = ['campaign_id' => $single_campaign['campaign_id'],'status' => 0];
$history_parent_id = $model->save_notification_history_parents($history_parents_data);
$single_campaign['history_parent_id'] = $history_parent_id;
#step 3 execute the customer group query and return customer details
$customer_details = $this->getCustomerDetails($single_campaign['group_id']);
$sent_customer_details = [];
if(count($customer_details))
{
foreach($customer_details as $customer)
{
#step 4 replace templates palceholders with data points
$notificationContent = $this->replaceTemplateWithDataPoints($template['message'],$customer);
$history_child_data = [
'fkid' => $single_campaign['history_parent_id'],
'donor_id' => $customer['donor_id'],
'receiving_entity' => $single_campaign['mode'] == 'Email' ? $customer['email'] : $customer['mobile_no'],
'receiving_status' => 0,
'message' => $notificationContent];
$history_child_id = $model->save_notification_history_child($history_child_data);
//check wheather if notification send to the current customer already
if(!in_array($customer['donor_id'],$sent_customer_details))
{
$this->logger->info("Auto Scheduled Customer CID = ".$customer['donor_id'].", CN = ".$customer['customer_name']);
#step 5 send notification
$notification = new NotificationHelper();
if($single_campaign['mode'] == 'Email')
{
$email_response = $notification->sendEmail(array('recipient_email' => $customer['email'],'subject' => $template['subject'],'template_name' => $template['template_name'],'description' => $notificationContent));
$mail_log = isset($email_response['success']) ? 'Email sent successfully' : 'Failed to send email';
$receiving_status = isset($email_response['success']) ? 1 : 0;
$this->logger->info("Auto Scheduled Email CID = ".$customer['donor_id']." ".$mail_log);
$history_child_where = ['fkid' => $single_campaign['history_parent_id'],'id' => (int)$history_child_id];
$history_child_updatedata = ['receiving_status'=>$receiving_status, 'result'=>isset($email_response['success']) ? $mail_log : (strtolower(gettype($email_response)) == "string" ? $email_response : json_encode($email_response)) ];
$history_child_statement = $model->update_notification_history_child($history_child_updatedata,$history_child_where);
$this->logger->info($history_child_statement);
}
else
{
$params = (object) Null;
$url = SEND_WAAI_URL;
$params->type = "text";
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$params->message = $notificationContent;
$params->number = (int)'91' . $customer['mobile_no'];
$whatsapp_reponse = $notification->sendWhatsAppMessage($url, "POST", $params);
$this->logger->info("Auto Scheduled Whatsapp CID = ".$customer['donor_id']." ".$whatsapp_reponse['message']);
$history_child_where = ['fkid' => $single_campaign['history_parent_id'],'id' => (int)$history_child_id];
$history_child_updatedata = ['receiving_status'=>$whatsapp_reponse['receiving_status'],'result'=>strtolower(gettype($whatsapp_reponse)) == "string" ? $whatsapp_reponse : json_encode($whatsapp_reponse['reponse'])];
$history_child_statement = $model->update_notification_history_child($history_child_updatedata,$history_child_where);
$this->logger->info($history_child_statement);
}
array_push($sent_customer_details,$customer['donor_id']);
}
}
}
}
#step 6 update campaign status to 1
$statement = $model->update_notification_campaign_status(['status' => 1],$single_campaign['campaign_id']);
$this->logger->info($statement);
#step 7 update history parent status to 1
$history_parent_statement = $model->update_notification_history_parent_status(['status' => 1],$single_campaign['history_parent_id'],$single_campaign['campaign_id']);
$this->logger->info($history_parent_statement);
}
}
}
#step 1 get scheduled notification details
function getScheduledNotificationDetails()
{
$model = new NotificationModel();
$today = date('Y-m-d');
$model->setTable('notification_campaign');
$where = ['scheduled_date'=>$today];
$notification_campaign_result = $model->where($where)->findAll();
return $notification_campaign_result;
}
#step 2 get template details
function getTemplateDetails($template_id)
{
$model = new NotificationModel();
$model->setTable('templates');
$where = ['template_id'=>$template_id];
$result = $model->where($where)->first();
return $result;
}
#step 3 execute the customer group query and return customer details
function getCustomerDetails($group_ids)
{
$group_id_arr = unserialize($group_ids);
$this->logger->info("Auto Scheduled Customer Group CGID = ".implode(", ", $group_id_arr));
$customer_details = [];
if(count($group_id_arr))
{
foreach($group_id_arr as $group_id)
{
// echo "gid".$group_id;
$model = new NotificationModel();
$model->setTable('donor_groups');
$customer_group_result = $model->where(['group_id'=>$group_id])->findAll();
$db = \Config\Database::connect();
if(count($customer_group_result))
{
$sql = (string)$customer_group_result[0]['group_query'];
$query = $db->query($sql);
$sql_group_results = $query->getResultArray();
// print_r($sql_group_results);
$customer_details = array_merge($customer_details,$sql_group_results);
}
}
}
return $customer_details;
}
#step 4
function replaceTemplateWithDataPoints($originalTemplate,$dataPointsArray)
{
// print_r($dataPointsArray['customer_name']);
// echo $originalTemplate;
$notificationContent = $originalTemplate;
$notificationContent = str_replace("{USER_NAME}", $dataPointsArray["customer_name"], $notificationContent);
$notificationContent = str_replace("{SCHEME_NAME}", $dataPointsArray["scheme_name"], $notificationContent);
$notificationContent = str_replace("{EXPIRY_DATE}", $dataPointsArray["formatted_due_date"], $notificationContent);
return $notificationContent;
}
############## Auto Scheduled Notification Ends ################
}