vb_book/app/Controllers/Notifications.php
2025-04-30 17:46:27 +05:30

1151 lines
62 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use App\Helpers\NotificationHelper;
use App\Models\NotificationModel;
use App\Models\SubscriptionModel;
use DateTime;
use App\Helpers\SendSMSHelper;
use Exception;
class Notifications extends BaseController
{
protected $smsHelper;
public function __construct()
{
$this->smsHelper = new SendSMSHelper();
}
################################################################
# Custom Notification
################################################################
public function custom_notifications()
{
$data['page_name'] = 'Custom Notifications';
if ($this->request->is('post')) {
session()->setFlashdata('reset', true);
$records = $this->request->getVar();
if ($records['mode'] == 'Email') {
helper('notification');
$notification = new NotificationHelper();
$records['description'] = $records['maildescription'];
$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,
'customer_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->error('Custom Notifications Email : historychildid = ' . $history_child_id);
} else {
$records = $this->request->getVar();
$doc_details = $this->request->getFile('media_doc');
$params = (object) Null;
$parents_status = 0;
$receiving_status = 0;
$doc_path = APPPATH . '../public/uploads/';
$doc_name = '';
$errorMessages = [];
$this->logger->error("Whatsapp : sending message instance id = " . $_ENV['WAAI_INSTANCE'] . " - " . $_ENV['WAAI_TOKEN']);
if ($records['mobile'] != "") {
$string = $records['mobile'];
$mobile_no_arr = explode(',', $string);
$total_number_count = count($mobile_no_arr);
$sended_number_count = 0;
$not_sended_number_count = 0;
// Step 1 Categories Check
if ($records['categories'] == 'SEND_WAAI_GROUP_URL') {
if ($records['group_id'] != "") {
$params->group_id = $records['group_id'];
} else {
session()->setFlashdata('error', 'Group Id Missing Please Try again..');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
} else if ($records['categories'] == 'SEND_WAAI_URL') {
if ($records['mobile'] == "") {
session()->setFlashdata('error', 'Mobile Number Missing Please Try again..');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
} else {
session()->setFlashdata('error', 'Please Choose your Category..');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
// Step 2 Media Check, Document Also Convert into Media Here.
if ($records['type'] == 'media') {
if ($records['media_url'] != "") {
$params->media_url = $records['media_url'];
$params->type = "media";
} else {
session()->setFlashdata('error', 'Media Url Missing Please Try again..');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
} elseif ($records['type'] == 'document') {
$doc_details = $this->request->getFile('media_doc');
$doc_path = APPPATH . '../public/uploads/';
if (empty($doc_details)) {
session()->setFlashdata('error', 'Please select a file to upload.');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
if (!$doc_details->isValid() || $doc_details->getClientMimeType() !== 'image/jpeg') {
session()->setFlashdata('error', 'Please upload a valid JPEG image.');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
$doc_name = $doc_details->getName();
if ($doc_name === '') {
$this->logger->error("Err on upload: name not found");
session()->setFlashdata('error', 'Document name not found. Please try again.');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
$doc_details->move($doc_path, $doc_name);
$params->media_url = base_url() . 'public/uploads/' . $doc_name;
$params->type = "media";
$this->logger->error("Name After Upload: " . $doc_name);
} else {
$params->type = "text";
}
$NotificationModel = new NotificationModel();
$history_parents_data = ['campaign_id' => 0, 'status' => 0, 'field_value' => $records['mobile']];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
// print_r($mobile_no_arr);
if (!empty($mobile_no_arr)) {
foreach ($mobile_no_arr as $mobile) {
// try {
$exceptionOccurred = false;
// echo "----$mobile";
if (trim(strlen($mobile)) == 10) {
if (ctype_digit($mobile)) {
if ($mobile != "") {
$params->number = (int)'91' . $mobile;
$url = constant($records['categories']);
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$params->message = strip_tags(ltrim($records['description']));
$this->logger->error("Whatsapp : Request Type ==> Mobile Number = " . $mobile . " - " . gettype($params));
helper('notification');
$notification = new NotificationHelper();
$success = $notification->sendWhatsAppMessage($url, "POST", $params);
// echo "<pre>";print_r($success);echo "</pre>";
$receiving_status = $success['receiving_status'];
$parents_status = $success['receiving_status'];
$this->logger->error("Whatsapp : Reponse ==> Mobile Number = " . $mobile . " Waai Reponse = " . json_encode($success['reponse']));
$history_msg = strtolower(gettype($success)) == "string" ? $success : json_encode($success['reponse']);
// $tag = (int)$receiving_status === 1 ? 'success' : 'error' ;
// session()->setFlashdata($tag, 'Message : ' . $success['message']);
(int)$receiving_status === 1 ? $sended_number_count++ : $not_sended_number_count++;
} else {
$receiving_status = 0;
$parents_status = 0;
$history_msg = "Mobile Number = " . $mobile . " is invalid.";
$this->logger->error("Whatsapp : Reponse ==> " . $history_msg);
$not_sended_number_count++;
$errorMessages[] = $history_msg;
}
} elseif (ctype_alpha($mobile)) {
$receiving_status = 0;
$parents_status = 0;
$history_msg = "Mobile Number = " . $mobile . " is a character.";
$this->logger->error("Whatsapp : Reponse ==> " . $history_msg);
$not_sended_number_count++;
$errorMessages[] = $history_msg;
} else {
$receiving_status = 0;
$parents_status = 0;
$history_msg = "Mobile Number = " . $mobile . " is a combination of characters and numbers.";
$this->logger->error("Whatsapp : Reponse ==> " . $history_msg);
$not_sended_number_count++;
$errorMessages[] = $history_msg;
}
} else {
$history_msg = "Mobile Number = " . $mobile . " does not have 10 digits.";
$this->logger->error("Whatsapp : Reponse ==> " . $history_msg);
$not_sended_number_count++;
$errorMessages[] = $history_msg;
}
$history_child_data = [
'fkid' => $history_parent_id,
'customer_id' => 0,
'receiving_entity' => $mobile,
'receiving_status' => $receiving_status,
'message' => $records['description'],
'result' => $history_msg
];
$NotificationModel = new NotificationModel();
$history_child_id = $NotificationModel->save_custom_notification_history_child($history_child_data);
$this->logger->error('Custom Notifications Whatsapp : historychildid = ' . $history_child_id);
}
if (!empty($errorMessages)) {
$this->logger->error(implode("\n", $errorMessages));
session()->setFlashdata('error', implode('<br>', $errorMessages));
$errorMessages = [];
}
if ($sended_number_count > 0) {
$NotificationModel = new NotificationModel();
$history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1], $history_parent_id, 0);
$this->logger->error($history_parent_statement);
session()->setFlashdata("success", "Message : Sent Success (" . $sended_number_count . " / " . $total_number_count . " )");
$this->logger->error("Whatsapp : Final ==> " . $sended_number_count . " Sended out of " . $total_number_count . " ( Not sended numbers count " . $not_sended_number_count . " ) ");
}
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
} else {
session()->setFlashdata('error', 'Message : Mobile Not Founded');
$this->logger->error('Message : Mobile Not Founded');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
} else {
session()->setFlashdata('error', 'Message : Mobile Field Empty');
$this->logger->error('Message : Mobile Field Empty');
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
return;
}
}
}
$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->error("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->error("Notification : Duedate notification Email Request data = " . json_encode($records));
$email_result = $notification->sendEmail($records);
$this->logger->error("Notification : Duedate notification Email Response = " . json_encode($email_result));
$this->logger->error("Notification : Duedate notification Whatsapp Request data = " . json_encode($params));
$whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
$this->logger->error("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;
}
##################################################################
# 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->error("Template Creation: In Add Page");
$data['page_name'] = 'Add Template';
$data['template_id'] = (int)$id;
$data['template_details'] = [];
} elseif ($id !== '0') {
$this->logger->error("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_id'] = (int)$id;
$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->error("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->error($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(['templates.isactive' => 1])
->whereNotIn('templates.template_name', array('EXPIRY NOTIFY TEMPLATE EMAIL', 'EXPIRY NOTIFY TEMPLATE WHATSAPP'))
->orderBy('templates.template_id', 'ASC')->findAll();
return $details;
}
public function template_creation_insert()
{
$this->logger->error("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->error($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->error("Campaign Creation: In Add Page");
$data['page_name'] = 'Add Campaign';
$data['campaign_details'] = [];
} elseif ($id !== '0') {
$this->logger->error("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('notification_campaign');
$where = ['campaign_id' => (int)$id];
$result = $model->where($where)->findAll();
if ($result) {
$this->logger->error("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->error($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->error("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 != "") {
// id has value means updation process.
$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'] = '';
$statement['error'] = 'Notification Campaign already In-Active. can`t able to update.';
$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 {
// id has no value means insertion process.
$statement = $model->saveDetails($data, 'campaign_id', 'notification_campaign');
}
if ($statement['success']) {
$tid = $data['template_id'];
$cid = $data['campaign_id'] ? $data['campaign_id'] : $statement['insert_id'];
$this->scheduledNotifications($tid, $cid, 1);
session()->setFlashdata('success', $statement['success']);
$this->logger->error($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');
}
################################################################
# Expiry Notification ReferWith : Hema
################################################################
public function getExpCustomerDetail($window_time = null, $to_time = null)
{
// dd($window_time);
// $valid_dates = [0,1,7,15,30];
// if(!in_array($window_time,$valid_dates) ){
// return "Please enter a valid notification period. Accepted values are 0, 7, 15, or 30 days.";
// }
$NotificationModel = new NotificationModel();
$this->update_expired_members();
$response = "<pre>"; // $response = "<pre> Hi, Started. <br>";
# Step 1: add the days to retrive the data//
$providedDate = date('Y-m-d');
// if ($this->request->getmethod() == 'post') {
// $window_time = $this->request->getGet('params');
// }
// dd($window_time);
if ($window_time != '') {
if ($window_time >= 0) {
$newDate = date('Y-m-d', strtotime("$providedDate + $window_time days"));
} else {
$newDate = date('Y-m-d', strtotime("$providedDate $window_time days"));
}
$ExpCustomerDetail = $NotificationModel->getExpDate(); // Retrieve the stored query
// echo("Inside If");
// print_r(''.$ExpCustomerDetail);die();
} else {
$dateData = $this->request->getGet('to_date');
$newDate = date('Y-m-d', strtotime($dateData));
$ExpCustomerDetail = $NotificationModel->getExpDate2();
}
# Step 2 :Get the customer detail//
if (empty($ExpCustomerDetail)) {
$this->logger->error('No customer group found by the name of EXPIRYDATE');
return;
}
if ($window_time != '') {
$modifiedQuery = str_replace('WINDOW_TIME', $window_time, $ExpCustomerDetail);
//print_r($modifiedQuery);die;
} else {
$from_date2 = $this->request->getGet('from_date');
$to_date2 = $this->request->getGet('to_date');
$from_date = DateTime::createFromFormat('d/m/Y', $from_date2)->format('Y-m-d');
$to_date = DateTime::createFromFormat('d/m/Y', $to_date2)->format('Y-m-d');
// Add single quotes around the date values during the replacement
$modifiedQuery = str_replace('FROM_DATE', "'$from_date'", $ExpCustomerDetail);
$modifiedQuery = str_replace('TO_DATE', "'$to_date'", $modifiedQuery);
}
if (empty($modifiedQuery)) {
$this->logger->error('There is no sub query');
return;
}
# Step 3: Replace the placeholder WINDOW_TIME with the user-provided value
$db = \Config\Database::connect();
$queryResult = $db->query($modifiedQuery)->getResultArray();
$notification = new NotificationHelper();
if (empty($queryResult)) {
$this->logger->error("There is no customer expiring on date:{$newDate}");
$response .= "There is no customer expiring. Date = " . date('d/m/Y', strtotime($newDate)) . " </pre>";
return $this->response->setBody($response);
}
$emailTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE EMAIL');
$this->logger->error("Customer expiring. till {$newDate} There are " . count($queryResult) . " persons");
$response .= "Customer expiring list. ( Date = " . date('d/m/Y', strtotime($newDate)) . " )<br>There are " . count($queryResult) . " persons <br>";
if (!empty($queryResult)) {
usort($queryResult, function ($a, $b) {
return $a['to_subscription'] <=> $b['to_subscription']; //Asc order
});
}
foreach ($queryResult as $inx => $row) {
$subscription_id = $row['sub_id'];
$status = $row['status'];
$fullName = trim($row['first_name'] . ' ' . $row['last_name']);
$userMobileNumber = $row['mobile_no'];
$email = $row['email'];
$schemename = $row['title'];
$expirydate = $row['to_subscription'];
$customerId = $row['customer_id'];
$membership_id = $row['membership_id'];
$countdays = $row['countdays'];
if (empty($fullName)) {
$this->logger->error('No subscription name found for record #' . $inx);
continue;
}
$response .= ($inx + 1) . ") #{$customerId} - Person Name = {$fullName} / {$membership_id} --- (Expiry on " . date('d/m/Y', strtotime($expirydate)) . ")<br>";
// Skip records with non-approved status
if ($status !== 'Approved') {
$response .= ($inx + 1) . ") Status = {$status}<br>";
$this->logger->error("Record #{$inx}: status is not Approved");
continue;
}
// Email Notification
$emailTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE EMAIL');
if (!empty($emailTemplateName)) {
$existingEmailCheck = $NotificationModel->checkAlreadyExistingInHistory($email, $customerId, $subscription_id);
if (empty($existingEmailCheck)) {
$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);
$emailContent = $emailTemplateName[0]['message'];
$emailContent = str_replace(
['{USER_NAME}', '{SCHEME_NAME}', '{EXPIRY_DATE}', '{RENEWAL_LINK}'],
[
$fullName,
$schemename,
date('d-m-Y', strtotime($expirydate)),
'<a href="' . getenv("SMS_SUB_URL") . $membership_id . '" target="blank">' . getenv("SMS_SUB_URL") . $membership_id . '</a>',
],
$emailContent
);
$emailData = [
'template_name' => 'EXPIRY NOTIFY TEMPLATE EMAIL',
'recipient_email' => $email,
'subject' => 'Your Subscription Expiry Notification',
'description' => $emailContent,
];
$history_child_data = [
'fkid' => $history_parent_id,
'customer_id' => $customerId,
'receiving_entity' => $email,
'receiving_status' => 0,
'subscription_id' => $subscription_id,
'message' => $emailContent
];
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
$emailResult = $notification->sendEmail($emailData);
if (isset($emailResult['success']) && !empty($emailResult['success'])) {
$history_msg = 'Email sent successfully';
$history_child_updatedata = ['receiving_status' => 1, 'result' => $history_msg];
$history_child_where = ['fkid' => $history_parent_id, 'id' => (int)$history_child_id];
$history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata, $history_child_where);
$this->logger->error($history_child_statement);
$history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1], $history_parent_id, $campaign_id);
$this->logger->error($history_parent_statement);
$response .= ($inx + 1) . ") " . $history_msg . "<br>";
} else {
$history_msg = (strtolower(gettype($emailResult)) == "string" ? $emailResult : json_encode($emailResult));
$history_child_updatedata = ['receiving_status' => 0, 'result' => $history_msg];
$history_child_where = ['fkid' => $history_parent_id, 'id' => (int)$history_child_id];
$history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata, $history_child_where);
$this->logger->error($history_child_statement);
$history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1], $history_parent_id, $campaign_id);
$this->logger->error($history_parent_statement);
$response .= ($inx + 1) . ") Failed to send email <br>";
}
} else {
$check_existing = 0;
$check_email_date = "";
if (!empty($existingEmailCheck)) {
foreach ($existingEmailCheck as $i => $r) {
$check_email_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : "";
}
}
if ($check_email_date) {
$response .= ($inx + 1) . ") Email already send on - " . date('d/m/Y h:i A', strtotime($check_email_date)) . "<br>";
$this->logger->error(($inx + 1) . ") Email already sent to {$email}");
$this->logger->error(($inx + 1) . ") Email already sent on {$check_email_date}");
}
}
} else {
$response .= ($inx + 1) . ") No email template found<br>";
$this->logger->error(($inx + 1) . ") No email template found<br>");
}
// WhatsApp Notification
// $whatsappTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE WHATSAPP');
// if (!empty($whatsappTemplateName)) {
// $existingWhatsAppCheck = $NotificationModel->checkAlreadyExistingInHistory($userMobileNumber, $customerId, $subscription_id);
// if (empty($existingWhatsAppCheck)) {
// $campaign_id = 2;
// $history_parents_data = ['campaign_id' => $campaign_id, 'status' => 0];
// $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
// $whatsappContent = $whatsappTemplateName[0]['message'];
// $whatsappContent = str_replace(
// ['{USER_NAME}', '{SCHEME_NAME}', '{EXPIRY_DATE}', '{RENEWAL_LINK}'],
// [
// $fullName,
// $schemename,
// date('d-m-Y', strtotime($expirydate)),
// base_url() . 'subscription_renewal/' . $customerId,
// ],
// $whatsappContent
// );
// $params = (object)[
// 'number' => '91' . $userMobileNumber,
// 'type' => 'text',
// 'message' => $whatsappContent,
// 'instance_id' => $_ENV['WAAI_INSTANCE'],
// 'access_token' => $_ENV['WAAI_TOKEN'],
// ];
// $whatsappResult = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
// $history_child_data = [
// 'fkid' => $history_parent_id,
// 'customer_id' => $customerId,
// 'receiving_entity' => $userMobileNumber,
// 'receiving_status' => 0,
// 'subscription_id' => $subscription_id,
// 'message' => strip_tags(ltrim($whatsappContent))
// ];
// $history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
// $receiving_status = $whatsappResult['receiving_status'];
// $history_msg = strtolower(gettype($whatsappResult)) == "string" ? $whatsappResult : json_encode($whatsappResult['reponse']);
// $history_child_updatedata = ['receiving_status' => $receiving_status, 'result' => $history_msg];
// $history_child_where = ['fkid' => $history_parent_id, 'id' => (int)$history_child_id];
// $history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata, $history_child_where);
// $this->logger->error($history_child_statement);
// $history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1], $history_parent_id, $campaign_id);
// $this->logger->error($history_parent_statement);
// if (strtolower(gettype($whatsappResult)) == "string") {
// $response .= ($inx + 1) . ") " . $whatsappResult . "<br>";
// } else {
// $result = json_encode($whatsappResult['reponse']);
// $decodedResult = json_decode($result, true);
// if ($decodedResult && isset($decodedResult['message']['key']['remoteJid'])) {
// $remoteJid = $decodedResult['message']['key']['remoteJid'];
// $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Remote Jid = " . $remoteJid);
// $response .= ($inx + 1) . ") Whatsapp sent successfully <br>";
// } else {
// // echo "Failed to extract remoteJid";
// $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Failed to extract remoteJid ");
// $response .= ($inx + 1) . ") Failed to send Whatsapp <br>";
// }
// }
// } else {
// $check_whatsapp_date = "";
// if (!empty($existingWhatsAppCheck)) {
// foreach ($existingWhatsAppCheck as $i => $r) {
// $check_whatsapp_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : "";
// }
// }
// if ($check_whatsapp_date) {
// $response .= ($inx + 1) . ") WhatsApp already send on - " . date('d/m/Y h:i A', strtotime($check_whatsapp_date)) . "<br>";
// $this->logger->error(($inx + 1) . ") WhatsApp already sent to {$userMobileNumber}");
// $this->logger->error(($inx + 1) . ") WhatsApp already sent on {$check_whatsapp_date}");
// }
// }
// } else {
// $response .= ($inx + 1) . ") No WhatsApp template found<br>";
// }
// SMS Notification
$smsTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE SMS');
$this->logger->error("SMS Template Name : " . json_encode($smsTemplateName));
if (!empty($smsTemplateName)) {
$this->logger->error("Found SMS Template");
$existingSMSCheck = $NotificationModel->checkAlreadyExistingInHistory($userMobileNumber, $customerId, $subscription_id);
$this->logger->error("Existing SMS Check : " . json_encode($existingSMSCheck));
if (empty($existingSMSCheck)) {
try {
$template_message = $smsTemplateName[0]['message'];
$message = str_replace(
["{#USERNAME#}", "{#EXPIRY#}", "{#LINK#}"],
[$fullName, date('d-m-Y', strtotime($expirydate)), getenv("SMS_SUB_URL") . $membership_id],
$template_message
);
$campaign_id = $NotificationModel->getCampaignID($smsTemplateName[0]['template_id']);
$userMobileNumber = $userMobileNumber != null && $userMobileNumber != "" ?"91" . $userMobileNumber : "";
$sent_status = $this->smsHelper->sendSMS($message, $userMobileNumber, $campaign_id,$membership_id);
$this->logger->error("Sent Status : ".json_encode($sent_status));
$history_msg = $sent_status;
$response .= ($inx + 1) . ") " . $history_msg . "<br>";
} catch (Exception $e) {
$this->logger->error("Error while sending SMS: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
}
} else {
$check_sms_date = "";
foreach ($existingSMSCheck as $i => $r) {
$check_sms_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : "";
}
if ($check_sms_date) {
$response .= ($inx + 1) . ") SMS already send on - " . date('d/m/Y h:i A', strtotime($check_sms_date)) . "<br>";
$this->logger->error(($inx + 1) . ") SMS already sent to {$userMobileNumber}");
$this->logger->error(($inx + 1) . ") SMS already sent on {$check_sms_date}");
}
}
} else {
$response .= ($inx + 1) . ") No SMS template found<br>";
}
# Loop Closed
}
$response .= "Process Completed <br></pre>";
if ($this->request->getmethod() == 'get') {
return $response;
} else {
return $this->response->setBody($response);
}
}
public function update_expired_members()
{
$model = new SubscriptionModel();
$currentDate = date('Y-m-d');
$model->where('to_subscription <', $currentDate)
->set(['status' => 0])
->update();
log_message('error', 'inside the update function');
}
# getExpCustomerDetail fns Closed
################################################################
# Auto Scheduled Notification
################################################################
## notification campaign details
public function processScheduledNotifications()
{
$this->scheduledNotifications(0, 0, 0);
// parameter are template_id is zero , campaign_id is zero , dummy is zero
}
public function scheduledNotifications($tid, $cid, $dummyvariable)
{
$this->logger->error("Auto Scheduled Notification Started");
$model = new NotificationModel();
#step 1 get scheduled notification details
$notification_campaign_result = $this->getScheduledNotificationDetails($tid, $cid);
$this->logger->error("Auto Scheduled Campaign Details Count = " . count($notification_campaign_result));
if (!count($notification_campaign_result)) {
$this->logger->error("No Auto Scheduled Notification in DB,exiting...!");
$this->logger->error("Auto Scheduled Notification Ends");
if ($dummyvariable == 0) {
echo "No Scheduled Data Founded" . "<br>";
exit();
}
}
// echo "Notification campaign Result Array in count = ".count($notification_campaign_result)."<br>";
//looping multiple notification campaign
if (count($notification_campaign_result)) {
foreach ($notification_campaign_result as $index => $single_campaign) {
if ($dummyvariable == 0) {
echo "Notification Campaign Name = " . $single_campaign['campaign_name'] . "<br>";
}
#step 2 get template details
$template = $this->getTemplateDetails($single_campaign['template_id']);
$customer_details = $this->getCustomerDetails($single_campaign['group_id']);
$this->logger->error("Auto Scheduled Template Details TID = " . $single_campaign['template_id']);
if (count($template) && count($customer_details)) {
#step 3 execute the customer group query and return customer details
$sent_customer_details = [];
if (count($customer_details)) {
#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;
foreach ($customer_details as $customer) {
$customer['customer_name'] = isset($customer['customer_name'])
? $customer['customer_name']
: (isset($customer['first_name']) && isset($customer['last_name'])
? $customer['first_name'] . ' ' . $customer['last_name']
: '');
$customer['scheme_name'] = isset($customer['scheme_name']) ? $customer['scheme_name'] : (isset($customer['title']) ? $customer['title'] : "");
$formatted_due_date = "";
if (isset($customer['to_subscription'])) {
$dateObj = date_create($customer['to_subscription']);
$formatted_due_date = date_format($dateObj, 'd-m-Y');
} else {
$formatted_due_date = $customer['formatted_due_date'];
}
$customer['formatted_due_date'] = $formatted_due_date;
#step 4 replace templates palceholders with data points
$notificationContent = $this->replaceTemplateWithDataPoints($template['message'], $customer);
$history_child_data = [
'fkid' => $single_campaign['history_parent_id'],
'customer_id' => $customer['customer_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['customer_id'], $sent_customer_details)) {
$this->logger->error("Auto Scheduled Customer CID = " . $customer['customer_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->error("Auto Scheduled Email CID = " . $customer['customer_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->error($history_child_statement);
}
if ($single_campaign['mode'] == 'Whatsapp') {
$params = (object) Null;
$url = SEND_WAAI_URL;
$params->type = "text";
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$params->message = strip_tags(ltrim($notificationContent));
$params->number = (int)'91' . $customer['mobile_no'];
$whatsapp_reponse = $notification->sendWhatsAppMessage($url, "POST", $params);
$whatsapp_reponse_msg = strtolower(gettype($whatsapp_reponse)) == "string" ? $whatsapp_reponse : json_encode($whatsapp_reponse['reponse']);
// echo "Whatsapp Response = ".$whatsapp_reponse_msg."<br>";
$this->logger->error("Auto Scheduled Whatsapp CID = " . $customer['customer_id'] . " " . $whatsapp_reponse_msg);
$history_child_where = ['fkid' => $single_campaign['history_parent_id'], 'id' => (int)$history_child_id];
$history_child_updatedata = ['receiving_status' => $whatsapp_reponse['receiving_status'], 'result' => $whatsapp_reponse_msg];
$history_child_statement = $model->update_notification_history_child($history_child_updatedata, $history_child_where);
$this->logger->error($history_child_statement);
}
array_push($sent_customer_details, $customer['customer_id']);
}
}
}
// #step 6 update campaign status to 1
$statement = $model->update_notification_campaign_status(['status' => 1], $single_campaign['campaign_id']);
if ($dummyvariable == 0) {
echo "Final Campaign Status = " . $statement . "<br>";
}
$this->logger->error($statement);
#step 7 update history parent status to 1
$history_parent_statement = $model->update_notification_history_parent_status(['status' => 1], $history_parent_id, $single_campaign['campaign_id']);
if ($dummyvariable == 0) {
echo "Final Acknowlegdement = " . $history_parent_statement . "<br>";
}
$this->logger->error($history_parent_statement);
}
}
}
}
#step 1 get scheduled notification details
function getScheduledNotificationDetails($tid, $cid)
{
$model = new NotificationModel();
if ($tid == 0 && $cid == 0) {
$templateIds = [1, 2];
$model->setTable('notification_campaign');
$notification_campaign_result = $model->whereIn('template_id', $templateIds)->where('isactive', 1)->findAll();
} else {
$templateIds = [$tid];
$model->setTable('notification_campaign');
$notification_campaign_result = $model->whereIn('template_id', $templateIds)->where(['isactive' => 1, 'campaign_id' => $cid])->findAll();
}
// $today = date('Y-m-d');
// $currentTime = date('H:i:s');
// $endTime = date('H:i:s', strtotime('+30 minutes'));
// $where = ['scheduled_date' => $today,'isactive' => 1,
// 'scheduled_time >=' => $currentTime,
// 'scheduled_time <=' => $endTime
// ];
// $model->setTable('notification_campaign');
// $notification_campaign_result = $model->where($where)->findAll();
// echo $model->getLastQuery();
return $notification_campaign_result;
}
#step 2 get template details
function getTemplateDetails($template_id)
{
$model = new NotificationModel();
$model->setTable('templates');
$where = ['template_id' => $template_id, 'isactive' => 1];
$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->error("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('customer_groups');
$customer_group_result = $model->where(['group_id' => $group_id, 'isactive' => 1])->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;
if (isset($dataPointsArray["customer_name"])) {
$notificationContent = str_replace("{USER_NAME}", $dataPointsArray["customer_name"], $notificationContent);
}
if (isset($dataPointsArray["scheme_name"])) {
$notificationContent = str_replace("{SCHEME_NAME}", $dataPointsArray["scheme_name"], $notificationContent);
}
if (isset($dataPointsArray["formatted_due_date"])) {
$expiryon = $dataPointsArray["formatted_due_date"] ? date('d-m-Y', strtotime($dataPointsArray["formatted_due_date"])) : '';
$notificationContent = str_replace("{EXPIRY_DATE}", $expiryon, $notificationContent);
}
if (isset($dataPointsArray["customer_id"])) {
$notificationContent = str_replace("{RENEWAL_LINK}", base_url() . 'subscription_renewal/' . $dataPointsArray["customer_id"], $notificationContent);
}
return $notificationContent;
}
############## Auto Scheduled Notification Ends ################
################################################################
# Notification Acknowlegdement
################################################################
## notification acknowlegdement
public function noifications_acknowlegdement()
{
$model = new NotificationModel();
$data['noifications_acknowlegdement'] = $model->get_noifications_acknowlegdement_data();
$data['page_name'] = 'Notifications Status';
$this->render_page('noifications_acknowlegdement', $data);
}
############## Notification Acknowlegdement Ends ################
}