diff --git a/app/Config/Email.php b/app/Config/Email.php index 34f443b1..42560899 100755 --- a/app/Config/Email.php +++ b/app/Config/Email.php @@ -39,8 +39,10 @@ class Email extends BaseConfig /** * SMTP Password */ - // public string $SMTPPass = 'Sz9VueQ2iLgH'; + // public string $SMTPPass = 'Sz9VueQ2iLgH'; old zoho pwd public string $SMTPPass = 'xmxwgnccaekefasa'; + // public string $SMTPPass = 'FdnFgsqdKgkR'; new zoho pwd + /** * SMTP Port diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 646a6e8e..0a2e7ad2 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -210,6 +210,7 @@ $routes->get('/list_log','Payment::listLogs'); $routes->get('/download_log/(:any)','Payment::downloadLog/$1'); $routes->get('/view_log/(:any)','Payment::viewLog/$1'); +$routes->get("testSMS","Payment::testSMS"); // $routes->group("api", function ($routes) { diff --git a/app/Controllers/Notifications.php b/app/Controllers/Notifications.php index e7e44c89..ca04ad09 100755 --- a/app/Controllers/Notifications.php +++ b/app/Controllers/Notifications.php @@ -7,18 +7,28 @@ 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(){ + 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'){ + if ($records['mode'] == 'Email') { helper('notification'); $notification = new NotificationHelper(); $records['description'] = $records['maildescription']; @@ -35,30 +45,31 @@ class Notifications extends BaseController $receiving_status = 1; $history_msg = 'Email sent successfully'; } - $history_msg = (strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg)) ; + $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_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_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{ + $this->logger->error('Custom Notifications Email : historychildid = ' . $history_child_id); + } else { $records = $this->request->getVar(); - $doc_details = $this->request->getFile('media_doc'); + $doc_details = $this->request->getFile('media_doc'); $params = (object) Null; $parents_status = 0; - $receiving_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'] != ""){ + if ($records['mobile'] != "") { $string = $records['mobile']; $mobile_no_arr = explode(',', $string); $total_number_count = count($mobile_no_arr); @@ -74,7 +85,7 @@ class Notifications extends BaseController $this->render_page('notifications_form', $data); return; } - }else if ($records['categories'] == 'SEND_WAAI_URL') { + } else if ($records['categories'] == 'SEND_WAAI_URL') { if ($records['mobile'] == "") { session()->setFlashdata('error', 'Mobile Number Missing Please Try again..'); $data['page_name'] = 'Custom Notifications'; @@ -99,138 +110,138 @@ class Notifications extends BaseController $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" ; + } 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_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) { + 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 "
";print_r($success);echo ""; - $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)) { + $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 "
";print_r($success);echo ""; + $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 a character."; - $this->logger->error("Whatsapp : Reponse ==> ".$history_msg); + $history_msg = "Mobile Number = " . $mobile . " is invalid."; + $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); + } 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; } - $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); - } + } 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('
";// $response = "Hi, Started."; - if ($this->request->getmethod() == 'get') { + if ($this->request->getmethod() == 'get') { return $response; - }else{ + } else { return $this->response->setBody($response); - } - - -} + } public function update_expired_members() { $model = new SubscriptionModel(); - $currentDate = date('Y-m-d'); + $currentDate = date('Y-m-d'); $model->where('to_subscription <', $currentDate) - ->set(['status' => 0]) - ->update(); - log_message('error','inside the update function'); + ->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); + 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){ + 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)) - { + $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"."
"; + $response = ""; // $response = ""; 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))." )Hi, Started."; + $response .= "There is no customer expiring. Date = " . date('d/m/Y', strtotime($newDate)) . "
"; # 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){ + if ($window_time != '') { + if ($window_time >= 0) { $newDate = date('Y-m-d', strtotime("$providedDate + $window_time days")); - }else{ + } 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{ + } else { $dateData = $this->request->getGet('to_date'); - $newDate = date('Y-m-d',strtotime($dateData)); + $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 != ''){ + if ($window_time != '') { $modifiedQuery = str_replace('WINDOW_TIME', $window_time, $ExpCustomerDetail); - //print_r($modifiedQuery);die; - + //print_r($modifiedQuery);die; - } - else{ + + } 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 + // 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'); @@ -636,14 +645,14 @@ class Notifications extends BaseController $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))."
There are ".count($queryResult)." persons
"; - if(!empty($queryResult)){ + $this->logger->error("Customer expiring. till {$newDate} There are " . count($queryResult) . " persons"); + $response .= "Customer expiring list. ( Date = " . date('d/m/Y', strtotime($newDate)) . " )
There are " . count($queryResult) . " persons
"; + if (!empty($queryResult)) { usort($queryResult, function ($a, $b) { return $a['to_subscription'] <=> $b['to_subscription']; //Asc order }); @@ -659,30 +668,30 @@ class Notifications extends BaseController $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)) . ")
"; - + // Skip records with non-approved status if ($status !== 'Approved') { $response .= ($inx + 1) . ") Status = {$status}
"; $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_parents_data = ['campaign_id' => $campaign_id, 'status' => 0]; $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); $emailContent = $emailTemplateName[0]['message']; @@ -696,270 +705,309 @@ class Notifications extends BaseController ], $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_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'])) { + 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); + $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); + $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."
"; + $response .= ($inx + 1) . ") " . $history_msg . "
"; } 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); + $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); + $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
"; + $response .= ($inx + 1) . ") Failed to send email
"; } } else { - $check_existing = 0; - $check_email_date = ""; - - - if(!empty($existingEmailCheck)){ + $check_existing = 0; + $check_email_date = ""; - foreach ($existingEmailCheck as $i => $r) { - $check_email_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : ""; + + 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))."
"; + if ($check_email_date) { + $response .= ($inx + 1) . ") Email already send on - " . date('d/m/Y h:i A', strtotime($check_email_date)) . "
"; $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
"; $this->logger->error(($inx + 1) . ") No email template found
"); } - + // 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); + // $whatsappTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE WHATSAPP'); + // if (!empty($whatsappTemplateName)) { + // $existingWhatsAppCheck = $NotificationModel->checkAlreadyExistingInHistory($userMobileNumber, $customerId, $subscription_id); - $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); + // if (empty($existingWhatsAppCheck)) { - $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."
"; - } - 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
"; - } else { - // echo "Failed to extract remoteJid"; - $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Failed to extract remoteJid "); - $response .= ($inx+1).") Failed to send Whatsapp
"; - } + // $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 . "
"; + // } 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
"; + // } else { + // // echo "Failed to extract remoteJid"; + // $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Failed to extract remoteJid "); + // $response .= ($inx + 1) . ") Failed to send Whatsapp
"; + // } + // } + // } 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)) . "
"; + // $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
"; + // } + + // 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 = "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 . "
"; + } catch (Exception $e) { + + $this->logger->error("Error while sending SMS: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine()); } } else { - $check_whatsapp_date = ""; - if(!empty($existingWhatsAppCheck)){ - foreach ($existingWhatsAppCheck as $i => $r) { - $check_whatsapp_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : ""; - } + + $check_sms_date = ""; + foreach ($existingSMSCheck as $i => $r) { + $check_sms_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))."
"; - $this->logger->error(($inx + 1) . ") WhatsApp already sent to {$userMobileNumber}"); - $this->logger->error(($inx + 1) . ") WhatsApp already sent on {$check_whatsapp_date}"); + + if ($check_sms_date) { + $response .= ($inx + 1) . ") SMS already send on - " . date('d/m/Y h:i A', strtotime($check_sms_date)) . "
"; + $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 WhatsApp template found
"; + $response .= ($inx + 1) . ") No SMS template found
"; } - # Loop Closed + # Loop Closed } $response .= "Process Completed
"; + if ($dummyvariable == 0) { + echo "No Scheduled Data Founded" . "
"; exit(); } } // echo "Notification campaign Result Array in count = ".count($notification_campaign_result)."
"; //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']."
"; + if (count($notification_campaign_result)) { + foreach ($notification_campaign_result as $index => $single_campaign) { + if ($dummyvariable == 0) { + echo "Notification Campaign Name = " . $single_campaign['campaign_name'] . "
"; } #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)) - { + $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)) - { + if (count($customer_details)) { #step 2.1 - $history_parents_data = ['campaign_id' => $single_campaign['campaign_id'],'status' => 0]; + $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'] - : ''); + + 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'])){ + if (isset($customer['to_subscription'])) { $dateObj = date_create($customer['to_subscription']); $formatted_due_date = date_format($dateObj, 'd-m-Y'); - }else{ + } 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]; + $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']); + 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)); + 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); + $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); + $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') - { + if ($single_campaign['mode'] == 'Whatsapp') { $params = (object) Null; $url = SEND_WAAI_URL; $params->type = "text"; @@ -970,48 +1018,50 @@ class Notifications extends BaseController $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."
"; - $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); + $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']); + 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."
"; } + $statement = $model->update_notification_campaign_status(['status' => 1], $single_campaign['campaign_id']); + if ($dummyvariable == 0) { + echo "Final Campaign Status = " . $statement . "
"; + } $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."
"; } + $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 . "
"; + } $this->logger->error($history_parent_statement); - - } - } - } + } + } + } } #step 1 get scheduled notification details - function getScheduledNotificationDetails($tid,$cid) + function getScheduledNotificationDetails($tid, $cid) { $model = new NotificationModel(); - if($tid == 0&&$cid == 0){ + 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{ + } else { $templateIds = [$tid]; $model->setTable('notification_campaign'); - $notification_campaign_result = $model->whereIn('template_id', $templateIds)->where(['isactive'=>1,'campaign_id'=>$cid])->findAll(); + $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')); @@ -1031,7 +1081,7 @@ class Notifications extends BaseController { $model = new NotificationModel(); $model->setTable('templates'); - $where = ['template_id'=>$template_id,'isactive'=>1]; + $where = ['template_id' => $template_id, 'isactive' => 1]; $result = $model->where($where)->first(); return $result; } @@ -1040,33 +1090,30 @@ class Notifications extends BaseController function getCustomerDetails($group_ids) { $group_id_arr = unserialize($group_ids); - $this->logger->error("Auto Scheduled Customer Group CGID = ".implode(", ", $group_id_arr)); + $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) - { + 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); - } + $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) + function replaceTemplateWithDataPoints($originalTemplate, $dataPointsArray) { // print_r($dataPointsArray['customer_name']); // echo $originalTemplate; @@ -1078,7 +1125,7 @@ class Notifications extends BaseController $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"])) : ''; + $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"])) { @@ -1092,7 +1139,8 @@ class Notifications extends BaseController # Notification Acknowlegdement ################################################################ ## notification acknowlegdement - public function noifications_acknowlegdement(){ + public function noifications_acknowlegdement() + { $model = new NotificationModel(); $data['noifications_acknowlegdement'] = $model->get_noifications_acknowlegdement_data(); $data['page_name'] = 'Notifications Status'; diff --git a/app/Controllers/Payment.php b/app/Controllers/Payment.php index fbf87a1e..d3f63f51 100644 --- a/app/Controllers/Payment.php +++ b/app/Controllers/Payment.php @@ -10,6 +10,8 @@ use App\Models\SubscriptionModel; use App\Models\AuthenticationModel; use App\Models\PaymentStatusModel; +use App\Helpers\SendSMSHelper; + require_once('vendor/autoload.php'); define('PROJECT', 'vendor/paytm/paytm-pg'); @@ -17,10 +19,12 @@ define('PROJECT', 'vendor/paytm/paytm-pg'); class Payment extends BaseController { protected $paymentModel; + protected $sendSMSHelper; public function __construct() { helper('encdec_paytm'); $this->paymentModel = new PaymentStatusModel(); + $this->sendSMSHelper = new SendSMSHelper(); } public function index($membership_id = null) @@ -504,6 +508,19 @@ public function paymentStatus(){ } +public function testSMS(){ + $mobile_number = '916382156701'; + $name = "Srinivas"; + $expiryDate = "10/10/2025"; + $link = "https://bit.ly/44Iy4Zm"; + + // Exactly matching the approved template + $message = "Hi {$name}, your subscription for Pusthakam scheme is about to expire on {$expiryDate}. Renew now to continue enjoying our books for one more year. Tap here to renew: {$link} -Vijayabharatham Prasuram"; + + $status = $this->sendSMSHelper->sendSMS($message,$mobile_number); + echo $status; +} + } diff --git a/app/Helpers/SendSMSHelper.php b/app/Helpers/SendSMSHelper.php new file mode 100644 index 00000000..d1e68a7b --- /dev/null +++ b/app/Helpers/SendSMSHelper.php @@ -0,0 +1,120 @@ +apiKey = trim(getenv('SMS_API_KEY')); + $this->senderId = getenv('SMS_SENDER_ID'); + $this->templateType = getenv('SMS_TEMPLATE_TYPE'); + $this->logger = service('logger'); + $this->url = trim(getenv('SMS_BASE_URL')); + $this->renewalTemplateID = getenv('SMS_RENEWAL_TEMPLATE_ID'); + + $this->notificationModel = new NotificationModel(); + } + + public function sendSMS($message,$mobile_number,$campaignID = null,$membershipID = null){ + + $this->logger->error('SMS Helper : SMS Request Data type = '.($campaignID)); + $this->logger->error('SMS Helper : SMS Request Data = '.json_encode($message)); + $this->logger->error('SMS Helper : SMS Request Mobile Number = '.json_encode($mobile_number)); + + if (is_array($mobile_number)){ + + $mobile_number = implode(",",$mobile_number); + } + + $message_encode = ($message); + $this->logger->error('SMS Helper : SMS URLENCODED MESSAGE = '.$message_encode); + + $url = $this->constructSMSURL($message_encode,$mobile_number); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + // Set a timeout of 10 seconds + curl_setopt($ch, CURLOPT_TIMEOUT, 10); + + $output = curl_exec($ch); + if ($output === false) { + $this->logger->error('SMS Helper : SMS CURL Error = '.curl_error($ch)); + } else { + $this->logger->error('SMS Helper : SMS CURL Response = '.$output); + // return $output; + } + + + curl_close($ch); + $mobile_number = str_replace("91","",$mobile_number); + + if (!empty($campaignID)){ + $this->saveSMSHistory($output,$mobile_number,$message,$campaignID,$membershipID); + } + + $output_to_display = str_contains($output, 'success')? "SMS Sent Successfully" : "SMS Sending Failed"; + + return $output_to_display; + + } + public function constructSMSURL($message, $mobile_number){ + $this->logger->error('SMS Helper : SMS URL Construction'); + + $params = [ + 'APIKEY' => $this->apiKey, + 'MobileNo' => $mobile_number, + 'SenderID' => $this->senderId, + 'Message' => $message, + 'ServiceName' => $this->templateType, + 'DLTTemplateID' => $this->renewalTemplateID, + ]; + + $URL = $this->url.http_build_query($params); + $this->logger->error('SMS Helper : SMS URL = '.$URL); + return $URL; + + } + + public function saveSMSHistory($output,$mobile_number,$message,$campaignID = null,$membershipID){ + + $where = [ + 'mobile_no' => $mobile_number, + 'isactive' => 1 + ]; + + $insertStatus = $this->notificationModel->saveSmSHistory($where,$campaignID,$message, $output,$membershipID); + if ($insertStatus){ + $this->logger->error('SMS Helper : SMS History Inserted Successfully'); + }else{ + $this->logger->error('SMS Helper : SMS History Insertion Failed'); + } + + } + + +} \ No newline at end of file diff --git a/app/Models/NotificationModel.php b/app/Models/NotificationModel.php index 2a1bc6d9..e05881d0 100755 --- a/app/Models/NotificationModel.php +++ b/app/Models/NotificationModel.php @@ -1,6 +1,9 @@ -db->table('subscription as S' ) - ->join('customers as C', 'C.customer_id = S.customer_id', 'left') - ->join('category as CM', 'CM.id = S.scheme_id', 'left') - ->join('business as B', 'B.business_id = S.business_id', 'left') - ->join('book_categories as BC', 'BC.category_id = S.scheme_id', 'left') - ->join('books as BK', 'BC.book_id = BK.book_id', 'left') - ->select('concat("Your subscription going to expried in ",DATEDIFF(S.to_subscription, CURDATE())," days") as statement,DATEDIFF(S.to_subscription, CURDATE()) as countdays,CM.name,CONCAT_WS(" ", C.first_name, C.last_name) as customer_name,C.email as customer_email,C.mobile_no as customer_mobile,S.sub_id,S.scheme_id,S.customer_id,S.from_subscription,S.to_subscription,S.business_id,B.title as business_name,B.address as business_address,B.city as business_city,B.state as business_state,B.postal_code as business_postal_code,B.email as business_email,B.mobile_no as business_mobile_no,S.to_subscription,S.from_subscription,BK.title,BK.book_id') - // ->where('S.to_subscription >=', $now)->where('S.to_subscription <=',$lastWeek) - ->where('S.to_subscription =',date('Y-m-d', strtotime($date))) - ->groupBy('S.sub_id') - ->get()->getResultArray(); + return $this->db->table('subscription as S') + ->join('customers as C', 'C.customer_id = S.customer_id', 'left') + ->join('category as CM', 'CM.id = S.scheme_id', 'left') + ->join('business as B', 'B.business_id = S.business_id', 'left') + ->join('book_categories as BC', 'BC.category_id = S.scheme_id', 'left') + ->join('books as BK', 'BC.book_id = BK.book_id', 'left') + ->select('concat("Your subscription going to expried in ",DATEDIFF(S.to_subscription, CURDATE())," days") as statement,DATEDIFF(S.to_subscription, CURDATE()) as countdays,CM.name,CONCAT_WS(" ", C.first_name, C.last_name) as customer_name,C.email as customer_email,C.mobile_no as customer_mobile,S.sub_id,S.scheme_id,S.customer_id,S.from_subscription,S.to_subscription,S.business_id,B.title as business_name,B.address as business_address,B.city as business_city,B.state as business_state,B.postal_code as business_postal_code,B.email as business_email,B.mobile_no as business_mobile_no,S.to_subscription,S.from_subscription,BK.title,BK.book_id') + // ->where('S.to_subscription >=', $now)->where('S.to_subscription <=',$lastWeek) + ->where('S.to_subscription =', date('Y-m-d', strtotime($date))) + ->groupBy('S.sub_id') + ->get()->getResultArray(); } - public function getTemplateDetails(){ - return $this->db->table('templates as T' ) - ->join('users as U1', 'U1.user_id = T.created_by', 'left') - ->join('users as U2', 'U2.user_id = T.updated_by', 'left') - ->select('T.template_id,T.template_name,T.mode,T.created_on,T.created_by,T.updated_on,T.updated_by,DATE_FORMAT(T.created_on, "%d/%m/%Y %h:%i %p") AS formatted_created_on,CONCAT_WS(" ", U1.first_name, U1.last_name) as created_by_name,CONCAT_WS(" ", U2.first_name, U2.last_name) as updated_by_name,T.isactive') - // ->whereNotIn('T.template_name',array('EXPIRY NOTIFY TEMPLATE EMAIL','EXPIRY NOTIFY TEMPLATE WHATSAPP')) - ->get()->getResultArray(); + public function getTemplateDetails() + { + return $this->db->table('templates as T') + ->join('users as U1', 'U1.user_id = T.created_by', 'left') + ->join('users as U2', 'U2.user_id = T.updated_by', 'left') + ->select('T.template_id,T.template_name,T.mode,T.created_on,T.created_by,T.updated_on,T.updated_by,DATE_FORMAT(T.created_on, "%d/%m/%Y %h:%i %p") AS formatted_created_on,CONCAT_WS(" ", U1.first_name, U1.last_name) as created_by_name,CONCAT_WS(" ", U2.first_name, U2.last_name) as updated_by_name,T.isactive') + // ->whereNotIn('T.template_name',array('EXPIRY NOTIFY TEMPLATE EMAIL','EXPIRY NOTIFY TEMPLATE WHATSAPP')) + ->get()->getResultArray(); } - public function saveDetails($data,$pk_name,$t_name){ + public function saveDetails($data, $pk_name, $t_name) + { $id = $data[$pk_name]; $statement_string = ucfirst(str_replace('_', ' ', $t_name)); - if($id != ''){ + if ($id != '') { unset($data[$pk_name]); // Remove the id from the data to avoid updating it unset($data['created_by']); // bcoz here data Updating here. if ($this->db->table($t_name)->where($pk_name, $id)->update($data)) { $affectedRows = $this->db->affectedRows(); - $statement['success'] = $statement_string.' has been updated successfully.'; + $statement['success'] = $statement_string . ' has been updated successfully.'; $statement['error'] = ""; - $statement['log'] = $statement_string.": has been updated successfully. Updated ".$pk_name." = " .$id." Affected Rows = ".$affectedRows; + $statement['log'] = $statement_string . ": has been updated successfully. Updated " . $pk_name . " = " . $id . " Affected Rows = " . $affectedRows; $statement['insert_id'] = $id; - } else { $statement['success'] = ""; - $statement['error'] = $statement_string.' update failed. Please try again.'; - $statement['log'] = $statement_string.": Err Failed to update ID = " .$id ; + $statement['error'] = $statement_string . ' update failed. Please try again.'; + $statement['log'] = $statement_string . ": Err Failed to update ID = " . $id; $statement['insert_id'] = $id; } - }else{ + } else { unset($data['updated_by']); if ($this->db->table($t_name)->insert($data)) { $insertID = $this->db->insertID(); - $statement['success'] = $statement_string.' has been Inserted successfully.'; + $statement['success'] = $statement_string . ' has been Inserted successfully.'; $statement['error'] = ""; - $statement['log'] = $statement_string.": has been added successfully. Inserted ID = " .$insertID ; + $statement['log'] = $statement_string . ": has been added successfully. Inserted ID = " . $insertID; $statement['insert_id'] = $insertID; } else { $statement['success'] = ""; - $statement['error'] = $statement_string." could not be added. Please try again.."; - $statement['log'] = $statement_string.": Err could not be added. Please try again."; + $statement['error'] = $statement_string . " could not be added. Please try again.."; + $statement['log'] = $statement_string . ": Err could not be added. Please try again."; $statement['insert_id'] = ""; } } - return $statement; -} + return $statement; + } -public function getCampaignDetails(){ - $result = $this->db->table('notification_campaign as NC' ) - ->join('users as U1', 'U1.user_id = NC.created_by', 'left') - ->join('users as U2', 'U2.user_id = NC.updated_by', 'left') - ->join('templates as T', 'T.template_id = NC.template_id', 'left') - ->select('NC.campaign_id,NC.campaign_name,T.template_id,T.template_name,NC.mode,NC.created_on,NC.created_by,NC.updated_on,NC.updated_by,DATE_FORMAT(NC.created_on, "%d/%m/%Y %h:%i %p") AS formatted_created_on,CONCAT_WS(" ", U1.first_name, U1.last_name) as created_by_name,CONCAT_WS(" ", U2.first_name, U2.last_name) as updated_by_name,NC.isactive,NC.group_id,NC.scheduled_date,if(NC.scheduled_time IS NULL ,"",NC.scheduled_time) as scheduled_time') - ->whereNotIn('T.template_name',array('EXPIRY NOTIFY TEMPLATE EMAIL','EXPIRY NOTIFY TEMPLATE WHATSAPP')) - ->get()->getResultArray(); - - if (!empty($result)) { - foreach ($result as $i => $item) { - $group_id = unserialize($item['group_id']); - $group_names = []; - $group_query = []; - foreach ($group_id as $j) { - $cg_data = $this->db->table('customer_groups as CG') - ->select('CG.group_id, CG.group_name,CG.group_query, CG.isactive') - ->where(['CG.isactive' => 1, 'CG.group_id' => $j]) - ->get() - ->getRowArray(); - - if ($cg_data) { - $group_names[] = $cg_data['group_name']; - $group_query[] = $cg_data['group_query']; - // array_push($group_sql, $cg_data['group_query']); + public function getCampaignDetails() + { + $result = $this->db->table('notification_campaign as NC') + ->join('users as U1', 'U1.user_id = NC.created_by', 'left') + ->join('users as U2', 'U2.user_id = NC.updated_by', 'left') + ->join('templates as T', 'T.template_id = NC.template_id', 'left') + ->select('NC.campaign_id,NC.campaign_name,T.template_id,T.template_name,NC.mode,NC.created_on,NC.created_by,NC.updated_on,NC.updated_by,DATE_FORMAT(NC.created_on, "%d/%m/%Y %h:%i %p") AS formatted_created_on,CONCAT_WS(" ", U1.first_name, U1.last_name) as created_by_name,CONCAT_WS(" ", U2.first_name, U2.last_name) as updated_by_name,NC.isactive,NC.group_id,NC.scheduled_date,if(NC.scheduled_time IS NULL ,"",NC.scheduled_time) as scheduled_time') + ->whereNotIn('T.template_name', array('EXPIRY NOTIFY TEMPLATE EMAIL', 'EXPIRY NOTIFY TEMPLATE WHATSAPP','EXPIRY NOTIFY TEMPLATE SMS')) + ->get()->getResultArray(); + + if (!empty($result)) { + foreach ($result as $i => $item) { + $group_id = unserialize($item['group_id']); + $group_names = []; + $group_query = []; + foreach ($group_id as $j) { + $cg_data = $this->db->table('customer_groups as CG') + ->select('CG.group_id, CG.group_name,CG.group_query, CG.isactive') + ->where(['CG.isactive' => 1, 'CG.group_id' => $j]) + ->get() + ->getRowArray(); + + if ($cg_data) { + $group_names[] = $cg_data['group_name']; + $group_query[] = $cg_data['group_query']; + // array_push($group_sql, $cg_data['group_query']); + } + } + $result[$i]['group_name'] = !empty($group_names) ? implode(", ", $group_names) : ''; + $result[$i]['customer_group'] = !empty($group_query) ? $this->customerGroupQueryExecution($group_query) : ''; + $result[$i]['customer_group_count'] = !empty($result[$i]['customer_group']) ? count($this->customerGroupQueryExecution($group_query)) : 0; + } + } + return $result; + } + + public function customerGroupQueryExecution($queries) + { + + $results = []; + + // Execute the queries + foreach ($queries as $query) { + if (!empty($query)) { + $queryResult = $this->db->query($query)->getResult(); + $results[] = $queryResult; + } + } + // echo ""; + // print_r($results); + // echo ""; + // Create a new array to store the unique results based on customer_id + $uniqueCustomers = array(); + + foreach ($results as $innerArray) { + foreach ($innerArray as $customer) { + $customerId = $customer->customer_id; + + // Check if the customer_id already exists in $uniqueCustomers + if (!isset($uniqueCustomers[$customerId])) { + $uniqueCustomers[$customerId] = $customer; } } - $result[$i]['group_name'] = !empty($group_names) ? implode(", ", $group_names) : ''; - $result[$i]['customer_group'] = !empty($group_query) ? $this->customerGroupQueryExecution($group_query) : ''; - $result[$i]['customer_group_count'] = !empty($result[$i]['customer_group']) ? count($this->customerGroupQueryExecution($group_query)) : 0; } - } - return $result; -} -public function customerGroupQueryExecution($queries){ - - $results = []; - - // Execute the queries - foreach ($queries as $query) { - if(!empty($query)){ - $queryResult = $this->db->query($query)->getResult(); - $results[] = $queryResult;} + // Convert the $uniqueCustomers array back to a numerically indexed array + $uniqueCustomers = array_values($uniqueCustomers); + return $uniqueCustomers; + // echo ""; + // print_r($uniqueCustomers); + // echo ""; + // die; } - // echo ""; - // print_r($results); - // echo ""; - // Create a new array to store the unique results based on customer_id - $uniqueCustomers = array(); - - foreach ($results as $innerArray) { - foreach ($innerArray as $customer) { - $customerId = $customer->customer_id; - - // Check if the customer_id already exists in $uniqueCustomers - if (!isset($uniqueCustomers[$customerId])) { - $uniqueCustomers[$customerId] = $customer; - } - } - } - - // Convert the $uniqueCustomers array back to a numerically indexed array - $uniqueCustomers = array_values($uniqueCustomers); - return $uniqueCustomers; - // echo ""; - // print_r($uniqueCustomers); - // echo ""; - // die; - } -// $query = "INSERT IGNORE INTO notification_history_children (fkid,customer_id,receiving_entry,message,result,sent_time) -// VALUES (1, 1, 'somes@gmail2.com','mail msg',NULL,'2023-12-22 14:20:50'), -// (1, 1, '9638527411','whatapp msg',NULL,'2023-12-22 14:20:50')"; + // $query = "INSERT IGNORE INTO notification_history_children (fkid,customer_id,receiving_entry,message,result,sent_time) + // VALUES (1, 1, 'somes@gmail2.com','mail msg',NULL,'2023-12-22 14:20:50'), + // (1, 1, '9638527411','whatapp msg',NULL,'2023-12-22 14:20:50')"; // $result = $db->query($query)->getResultArray(); - public function getExpDate() -{ - $db = \Config\Database::connect(); + public function getExpDate() + { + $db = \Config\Database::connect(); - $query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE' AND isactive = 1"; + $query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE' AND isactive = 1"; - $result = $db->query($query)->getResultArray(); + $result = $db->query($query)->getResultArray(); - if (isset($result[0]["group_query"])) { - return $result[0]["group_query"]; - } else { - - error_log('group_query is not available in getExpDate()'); - - return ; - + if (isset($result[0]["group_query"])) { + return $result[0]["group_query"]; + } else { + + error_log('group_query is not available in getExpDate()'); + + return; + } } -} -public function getExpDate2(){ - $db = \Config\Database::connect(); + public function getExpDate2() + { + $db = \Config\Database::connect(); - $query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE_2' AND isactive = 1"; + $query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE_2' AND isactive = 1"; - $result = $db->query($query)->getResultArray(); + $result = $db->query($query)->getResultArray(); - if (isset($result[0]["group_query"])) { - return $result[0]["group_query"]; - } else { - - error_log('group_query is not available in getExpDate()'); - - return ; - + if (isset($result[0]["group_query"])) { + return $result[0]["group_query"]; + } else { + + error_log('group_query is not available in getExpDate()'); + + return; + } } -} - public function getTempName($name) - { - $db = \Config\Database::connect(); - $query = "SELECT * FROM templates WHERE isactive = 1 AND template_name = '".$name."'"; - $result = $db->query($query)->getResultArray(); - if (isset($result)) { - return $result; - } else { - - error_log('group_query is not available in getExpDate()'); - - return $query; - + public function getTempName($name) + { + $db = \Config\Database::connect(); + $query = "SELECT * FROM templates WHERE isactive = 1 AND template_name = '" . $name . "'"; + $result = $db->query($query)->getResultArray(); + if (isset($result)) { + return $result; + } else { + + error_log('group_query is not available in getExpDate()'); + + return $query; + } } -} - public function update_notification_campaign_status($data,$id){ - if($id != ''){ - $where = ['isactive' => 1, 'status' => 0 ,'campaign_id'=>(int)$id]; + public function update_notification_campaign_status($data, $id) + { + if ($id != '') { + $where = ['isactive' => 1, 'status' => 0, 'campaign_id' => (int)$id]; if ($this->db->table('notification_campaign')->where($where)->update($data)) { $affectedRows = $this->db->affectedRows(); - $statement = $affectedRows > 0 ? 'Notification Campaign Status has been updated successfully. Aff Row'.$affectedRows." NCID = " .$id : 'Notification Campaign Status Update failed. Bcoz Already Affected Count = '.$affectedRows.". NCID = " .$id ; + $statement = $affectedRows > 0 ? 'Notification Campaign Status has been updated successfully. Aff Row' . $affectedRows . " NCID = " . $id : 'Notification Campaign Status Update failed. Bcoz Already Affected Count = ' . $affectedRows . ". NCID = " . $id; } else { - $statement = "Notification Campaign Status Update failed. NCID = " .$id; + $statement = "Notification Campaign Status Update failed. NCID = " . $id; } - } - else{ + } else { $statement = "Notification Campaign Status Update failed. Bcoz Not Found NCID"; } return $statement; - } + } - public function save_notification_history_parents($data){ + public function save_notification_history_parents($data) + { $this->db->table('notification_history_parents')->insert($data); $insertID = $this->db->insertID(); return $insertID; } - public function update_notification_history_parent_status($data,$id,$campaign_id){ - if($id != ''){ - $where = ['id' => (int)$id, 'status' => 0 ,'campaign_id'=>(int)$campaign_id]; + public function update_notification_history_parent_status($data, $id, $campaign_id) + { + if ($id != '') { + $where = ['id' => (int)$id, 'status' => 0, 'campaign_id' => (int)$campaign_id]; if ($this->db->table('notification_history_parents')->where($where)->update($data)) { $affectedRows = $this->db->affectedRows(); - $statement = $affectedRows > 0 ? 'Notification history parent Status has been updated successfully. Aff Row'.$affectedRows." NHPID = " .$id : 'Notification history parent Status Update failed. Bcoz Already Affected Count = '.$affectedRows.". NHPID = " .$id ; + $statement = $affectedRows > 0 ? 'Notification history parent Status has been updated successfully. Aff Row' . $affectedRows . " NHPID = " . $id : 'Notification history parent Status Update failed. Bcoz Already Affected Count = ' . $affectedRows . ". NHPID = " . $id; } else { - $statement = "Notification history parent Status Update failed. NHPID = " .$id; + $statement = "Notification history parent Status Update failed. NHPID = " . $id; } - } - else{ + } else { $statement = "Notification history parent Status Update failed. Bcoz Not Found NHPID"; } return $statement; - } - + } - public function save_notification_history_child($data){ + + public function save_notification_history_child($data) + { // $this->db->ignore(true); // Enable "INSERT IGNORE" behavior // $this->db->table('notification_history_children')->insert($data); // $insertID = $this->db->insertID(); // Get the last inserted ID @@ -260,7 +268,7 @@ public function getExpDate2(){ // $this->db->query($insert_query); // $insertID = $this->db->insertID(); // Get the last inserted ID // return $insertID; - + $table = 'notification_history_children'; $insert_query = "INSERT IGNORE INTO $table (" . implode(', ', array_keys($data)) . ") VALUES (" . rtrim(str_repeat('?, ', count($data)), ', ') . ")"; $this->db->query($insert_query, array_values($data)); @@ -269,16 +277,18 @@ public function getExpDate2(){ return $insertID; } - public function save_custom_notification_history_child($data){ + public function save_custom_notification_history_child($data) + { $this->db->table('notification_history_children')->insert($data); $insertID = $this->db->insertID(); return $insertID; } - public function update_notification_history_child($data, $where){ - + public function update_notification_history_child($data, $where) + { + $id = isset($where['id']) ? $where['id'] : ""; - + if ($id != '') { $updateResult = $this->db->table('notification_history_children')->where($where)->update($data); // print_r($this->db->getLastQuery());die; @@ -291,7 +301,7 @@ public function getExpDate2(){ } else { $statement = 'Notification history children Update failed. Bcoz Not Found NHCID'; } - + return $statement; } @@ -324,31 +334,33 @@ public function getExpDate2(){ return $query->get()->getResultArray(); } - - public function getAllCustomerMobileNumber(){ - + + public function getAllCustomerMobileNumber() + { + $arr = $this->select('mobile_no') - ->where('mobile_no IS NOT NULL') - ->where('mobile_no !=', '') - ->groupBy('mobile_no') - ->having('COUNT(*) >', 1) - ->findAll(); - return count($arr)>0 ? $arr : []; - + ->where('mobile_no IS NOT NULL') + ->where('mobile_no !=', '') + ->groupBy('mobile_no') + ->having('COUNT(*) >', 1) + ->findAll(); + return count($arr) > 0 ? $arr : []; } - public function checkAlreadyExistingInHistory($email,$customerId,$subscriptionId){ - return $this->db->table('notification_history_children as nhc' ) - ->join('customers as C', 'C.customer_id = nhc.customer_id', 'left') - ->join('subscription as S', 'S.sub_id = nhc.subscription_id', 'left') - ->where('nhc.receiving_entity =',$email) - ->where('C.customer_id =',$customerId) - ->where('S.sub_id =',$subscriptionId) - ->where('nhc.sent_time >', date('Y-m-d', strtotime('-5 days'))) - ->where('nhc.receiving_status = ',1) - ->get()->getResultArray(); + public function checkAlreadyExistingInHistory($email, $customerId, $subscriptionId) + { + return $this->db->table('notification_history_children as nhc') + ->join('customers as C', 'C.customer_id = nhc.customer_id', 'left') + ->join('subscription as S', 'S.sub_id = nhc.subscription_id', 'left') + ->where('nhc.receiving_entity =', $email) + ->where('C.customer_id =', $customerId) + ->where('S.sub_id =', $subscriptionId) + ->where('nhc.sent_time >', date('Y-m-d', strtotime('-5 days'))) + ->where('nhc.receiving_status = ', 1) + ->get()->getResultArray(); } - public function get_email_data($f_date = null , $t_date = null){ + public function get_email_data($f_date = null, $t_date = null) + { $builder = $this->db->table('notification_history_parents as nhp'); $builder->select('nhp.*, nhc.*, nc.*,C.first_name,C.last_name,C.email, S.sub_id,S.membership_id, DATEDIFF(S.to_subscription, CURDATE()) AS countdays'); $builder->join('notification_history_children as nhc', 'nhc.fkid = nhp.id'); @@ -357,16 +369,62 @@ public function getExpDate2(){ $builder->join('subscription as S', 'S.sub_id = nhc.subscription_id'); $builder->where('DATE(nhp.start_date_time) >=', $f_date); $builder->where('DATE(nhp.start_date_time) <=', $t_date); - $builder->whereIn('nhp.campaign_id', [1, 2]); + $builder->whereIn('nhp.campaign_id', [1, 2,getenv("SMS_CAMPAIGN_ID")]); $builder->where('nc.isactive', 1); $query = $builder->get(); $results = $query->getResult(); - log_message('info',json_encode($results)); + log_message('info', json_encode($results)); return $results; } - + + public function saveSmSHistory($where, $messageType, $message, $result, $membershipID) + { + + try { + + $customer = $this->db->table('customers')->where($where)->get()->getRowArray(); + $subscriber = $this->db->table('subscription')->where('membership_id',$membershipID)->get()->getRowArray(); + + $customer_id = $customer['customer_id']; + $subscriptionId = $subscriber['sub_id']; + $campaign_id = $messageType; + $status = str_contains($result, 'success') ? 1 : 0; + + $data = [ + 'campaign_id' => $campaign_id, + 'status' => $status + ]; + + $this->db->table("notification_history_parents")->insert($data); + + $insertID = $this->db->insertID(); + + $child_data = [ + 'fkid' => $insertID, + 'customer_id' => $customer_id, + 'receiving_entity' => $where['mobile_no'], + 'receiving_status' => $status, + 'message' => $message, + 'subscription_id' => $subscriptionId, + 'result' => json_encode($result) + ]; + + $this->db->table("notification_history_children")->insert($child_data); + $insertID = $this->db->insertID(); + + return $insertID; + } catch (\Exception $e) { + // Handle the exception + log_message('error', 'Error in saveSmSHistory: ' . $e->getMessage()); + return false; + } + } + + public function getCampaignID($template_id){ + + $result = $this->db->table("notification_campaign")->where("template_id",$template_id)->get()->getRowArray()['campaign_id']; + + return $result; + } } - - - diff --git a/app/Views/report_itemwise.php b/app/Views/report_itemwise.php index 77e49abd..b1c0776d 100755 --- a/app/Views/report_itemwise.php +++ b/app/Views/report_itemwise.php @@ -8,8 +8,7 @@ .custom-thead th { text-align: center; /* Center-align the main table column headings */ } - - /* .nested-table-data th, +om /* .nested-table-data th, .nested-table-data td { text-align: center; /* Center-align the nested table data } */