<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Api extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session','form_validation','sms_gateway','sendMail');
// Load necessary models or libraries here if needed
$this->load->model(['frontend/Register_model', 'frontend/Subscribe_model', 'frontend/Home_model','admin/Product_model','admin/Product_interest_model','admin/Notification_model']);
}
public function commodity_list()
{
// Fetch commodity list from the model
$commodity_list = $this->Subscribe_model->commodities();
// Specify the ID to remove
$id_to_remove = "19"; // Replace with the actual ID to remove
// Remove the commodity with the specified ID
$commodity_list = array_filter($commodity_list, function($commodity) use ($id_to_remove) {
return $commodity['id'] !== $id_to_remove;
});
// Re-index the array to fix the array keys after filtering
$commodity_list = array_values($commodity_list);
$this->output
->set_content_type('application/json')
->set_output(json_encode($commodity_list));
}
public function product_list()
{
$product_list = $this->Product_interest_model->fetch();
$this->output
->set_content_type('application/json')
->set_output(json_encode($product_list));
}
public function product_master_list()
{
$product_list = $this->Product_model->fetch();
$this->output
->set_content_type('application/json')
->set_output(json_encode($product_list));
}
public function subscription_period()
{
$period_list = ['6_month','1_year','3_year','5_year'];
$this->output
->set_content_type('application/json')
->set_output(json_encode($period_list));
}
public function submit_form()
{
// Common validation rules
$this->form_validation->set_rules('book_email', 'E-mail ID', 'required|trim|valid_email');
$this->form_validation->set_rules('book_contact', 'Contact Number', 'required|trim|numeric|min_length[7]|max_length[15]');
$this->form_validation->set_rules('verify_otp', 'OTP', 'required|trim|exact_length[4]|numeric');
$this->form_validation->set_rules('book_name', 'Name', 'required|trim');
// Run validation
if ($this->form_validation->run() == FALSE) {
$response = array(
'status' => FALSE,
'message' => validation_errors()
);
echo json_encode($response);
return;
}
// Prepare data for saving
$services = $this->input->post('services');
$products = $this->input->post('commodities');
$save_data = array(
'book_name' => $this->input->post('book_name'),
'book_organisation' => $this->input->post('book_organisation'),
'book_designation' => $this->input->post('book_designation'),
'book_contact' => $this->input->post('contactNo'),
'book_email' => $this->input->post('book_email'),
'book_message' => $this->input->post('book_message'),
'book_prefered_time' => $this->input->post('book_prefered_time'),
'book_product_interest' => implode(', ', $this->getProductNames($services)),
'book_url' => $this->input->post('book_url'),
'book_ip_address' => $this->input->ip_address(),
'book_date' => date('Y-m-d H:i:s'),
);
// Use a transaction for multiple database operations
$this->db->trans_start();
// Check if email already exists if services contain '1' (assuming service '1' is related to subscription)
$message = ''; // Initialize the message for notifications
if (in_array('1', $services)) {
$email = $save_data['book_email'];
$email_exists = $this->Register_model->is_unique_check($email);
if ($email_exists) {
// Rollback transaction and set response if email already exists
$this->db->trans_rollback();
$response = array(
'status' => FALSE,
'message' => 'This email address is already registered.'
);
echo json_encode($response);
return;
} else {
// Save data to subscription register
$subscription_data = array(
'first_name' => $save_data['book_name'],
'organization' => $save_data['book_organisation'],
'designation' => $save_data['book_designation'],
'mobile' => $save_data['book_contact'],
'email' => $save_data['book_email'],
'created_at' => $save_data['book_date'],
'subscription_type' => '4',
'country' => '104',
'user_type' => 'Unregister',
'choose_type' => is_array($products) ? implode(', ', $products) : $products,
'free_trial' => $this->input->post('free_trial') ? '3days_trial' : '',
'start_reg' => date('Y-m-d'),
'end_reg' => date('Y-m-d', strtotime("+3 days"))
);
$save_result_subscription = $this->Register_model->insertSubscriptionRegister($subscription_data);
// Add the lead message if only service 1 is selected
if (count($services) == 1) {
$title = "New Leads";
$message = "New lead generated for " . implode(", ", $this->getProductNames($services)) . ".";
}
}
}
// If services array contains '2' or '3' (Assuming they are related to free demo)
if (in_array('2', $services) || in_array('3', $services)) {
// Save data to book demo table
$save_result_book_demo = $this->Home_model->insertBookDemo($save_data);
// Prepare demo related notification message
if (count($services) == 1) {
// Only service '2' or '3' selected, message is based on that service
$service_names = array();
if (in_array('2', $services)) {
$service_names[] = "New lead generated for " . implode(", ", $this->getProductNames($services)) . ".";
}
if (in_array('3', $services)) {
$service_names[] = "New lead generated for " . implode(", ", $this->getProductNames($services)) . ".";
}
$title = "New Demo Leads";
$message = implode(" and ", $service_names) . " .";
} else {
$title = "New Demo Leads";
// Both service '2' and '3' selected
$message = "New lead generated for " . implode(", ", $this->getProductNames($services)) . ".";
}
}
// If both services '1' and '2' or '3' are selected, combine messages
if (count($services) > 1) {
$title = 'New Leads';
// Combine the messages for both subscription and demo services
$combined_message = "New lead generated for " . implode(", ", $this->getProductNames($services)) . ". ";
$message = $combined_message;
}
// Send the notification
$this->Notification_model->add_notification($title, $message, 'admin', '1');
// Complete transaction
$this->db->trans_complete();
// Check if both save operations were successful
if ($this->db->trans_status() === FALSE) {
$response = array(
'status' => FALSE,
'message' => 'There was an issue with your submission. Please try again later.'
);
} else {
$response = array(
'status' => TRUE,
'save_data' => $save_data,
'services' => $this->input->post('services'),
'message' => 'Thank you for your interest. Our team will contact you shortly.'
);
}
// Return JSON response for AJAX request
if ($this->input->is_ajax_request()) {
echo json_encode($response);
} else {
// Handle non-AJAX submission (optional)
// $this->load->view('your_view', $data);
}
}
// Function to fetch product names based on IDs
private function getProductNames($product_ids)
{
$product_list = $this->Product_interest_model->fetch(); // Assuming this fetches the product data
// Map product IDs to product names
$product_names = [];
foreach ($product_list as $product) {
if (in_array($product['product_id'], $product_ids)) {
$product_names[] = $product['product_name'];
}
}
return $product_names;
}
// Function to send confirmation email
public function sendConfirmationEmail()
{
// Validate and retrieve POST data
$data = $this->input->post('save_data');
$services = $this->input->post('services');
if (!$data || !$services) {
$this->jsonResponse(false, 'Invalid input data.');
}
$toEmail = $data['book_email'];
$recipientName = $data['book_name'];
$filePath = null; // Optional main file, if you use it
// Generate subject dynamically
$product_names = $this->getProductNames($services);
// Determine the template and subject based on selected services
if (in_array('1', $services)) {
if (count($services) == 1) {
$template = 'rmpts';
$subject = 'Raw Materials Price Tracking Services -CostMasters';
$attachments = FCPATH . '/assets/frontend/files/CostMasters_RMPTS_presentation.pdf';
} elseif (in_array('2', $services) || in_array('3', $services)) {
$template = 'rmpts';
$subject = 'Raw Materials Price Tracking Services -CostMasters';
$attachments = FCPATH . '/assets/frontend/files/CostMasters_RMPTS_presentation.pdf';
}
} elseif (in_array('2', $services)) {
if (count($services) == 1) {
$template = 'ice';
$subject = 'Digitization of Zero Base Costing & Cost Management -CostMasters ICE';
$attachments = [
FCPATH . 'assets/frontend/files/CostMasters_ICE_Thanks.pdf',
FCPATH . 'assets/frontend/files/InformationRequired-ICE.pdf'
];
} elseif (in_array('3', $services)) {
$template = 'ice';
$subject = 'Digitization of Zero Base Costing & Cost Management -CostMasters ICE';
$attachments = [
FCPATH . 'assets/frontend/files/CostMasters_ICE_Thanks.pdf',
FCPATH . 'assets/frontend/files/InformationRequired-ICE.pdf'
];
}
} elseif (in_array('3', $services)) {
$template = 'rapidrfq';
$subject = 'Quick Introduction - CostMasters Rapid RFQ';
$attachments = [
FCPATH . 'assets/frontend/files/Rapid_RFQ_Presentation.pdf',
FCPATH . 'assets/frontend/files/RFQ_information_required.pdf'
];
}
// Load email template
$message = $this->load->view($template, ['data' => $data], true);
// Send email
$send_mail = $this->sendmail->sendEmailWithAttachments($toEmail, $recipientName, $subject, $message,$filePath,$attachments);
if ($send_mail) {
$this->jsonResponse(true, 'Email sent successfully.');
} else {
$this->jsonResponse(false, 'Failed to send email.', ['error' => $this->sendmail->getLastError()]);
}
}
// Utility function for JSON responses
private function jsonResponse($status, $message, $extraData = [])
{
$response = array_merge(['status' => $status, 'message' => $message], $extraData);
echo json_encode($response);
exit;
}
private function sendOtpEmail($toEmail)
{
// Generate OTP using a more secure method (random_int)
$otp = random_int(1000, 9999);
// Optionally log the OTP for debugging (remove in production)
log_message('debug', 'Generated Email OTP: ' . $otp);
// Store OTP in session (valid for 10 minutes)
$this->session->set_userdata('email_otp', $otp);
$this->session->set_userdata('email_otp_expiry', time() + 600); // 10 minutes validity
// Prepare email subject
$subject = 'Email Verification Code';
// Prepare data to pass to the view
$data = [
'otp' => $otp, // Pass the OTP to the email template
'expiry_time' => 10 // Example of passing expiration time
];
// Load email template and pass dynamic data
$msg = $this->load->view('email-otp', ['data' => $data], true);
try {
// Send the email
$send_mail = $this->sendmail->sendTo($toEmail, $toEmail, $subject, $msg);
// Check if email was sent successfully
if ($send_mail) {
// Return success (for debugging, include the OTP)
return ['success' => true, 'otp' => $otp];
} else {
// Log the error if email sending fails
log_message('error', 'Mailer Error: ' . $this->sendmail->ErrorInfo);
return ['success' => false, 'error' => 'Failed to send OTP email.'];
}
} catch (Exception $e) {
// Catch any exception and log it
log_message('error', 'Exception caught while sending OTP email: ' . $e->getMessage());
return ['success' => false, 'error' => 'An error occurred while sending OTP email.'];
}
}
public function send_otp_email()
{
if (!$this->input->is_ajax_request()) {
show_404(); // Handle only AJAX requests
}
$email = $this->input->post('email');
// Validate email
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->output->set_status_header(400);
echo json_encode(['error' => 'Invalid email. Please enter a valid email address.']);
return;
}
// Generate and send the OTP email
$result = $this->sendOtpEmail($email);
if ($result['success']) {
// Returning the OTP for debugging purposes
echo json_encode([
'status' => 'true',
'otp' => $result['otp'], // If needed, this could be removed in production
'message' => 'OTP sent successfully to your email.'
]);
} else {
$this->output->set_status_header(500);
echo json_encode(['status' => 'false', 'error' => $result['error']]);
}
}
public function send_otp()
{
// Ensure it's an AJAX request
if (!$this->input->is_ajax_request()) {
show_404(); // Handle only AJAX requests
}
// Get the contact number from POST data
$contact_no = $this->input->post('contactNo');
// Validate input
if (!$contact_no || !is_numeric($contact_no) || strlen($contact_no) !== 10) {
$this->output->set_status_header(400);
echo json_encode(array('error' => 'Invalid contact number.'));
return;
}
// Generate OTP
$otp = rand(1000, 9999);
// Store OTP in session or database for validation
$this->session->set_userdata('mobile_otp', $otp);
$this->session->set_userdata('contact_no', $contact_no);
$this->session->set_userdata('mobile_otp_expiry', time() + 600);
// Prepare SMS message
$message = $otp . ' is your OTP to access CostMasters RM portal. This OTP is valid for 10 mins. Do not disclose it to anyone.';
$senderId = 'CIRxCM';
// Assuming $this->sms_gateway is your SMS gateway library instance
$send = $this->sms_gateway->sendSms($contact_no, $message, $senderId);
// Check if SMS was sent successfully
if ($send) {
// Return success response
echo json_encode(array('status' => 'true', 'message' => 'OTP sent successfully.'));
} else {
// Return error response
$this->output->set_status_header(500);
echo json_encode(array('error' => 'Failed to send SMS.'));
}
}
// Helper function for consistent error response
private function send_error($status_code, $message)
{
$this->output->set_status_header($status_code);
echo json_encode(['status' => 'false', 'error' => $message]);
}
public function verify_otp()
{
if (!$this->input->is_ajax_request()) {
show_404(); // Restrict to AJAX requests only
}
$otp = $this->input->post('otp');
$contact_no = $this->input->post('contact_no');
$email = $this->input->post('email');
$country_code = $this->input->post('countryCode');
// Determine OTP type
if ($country_code === 'in') {
// Determine OTP type
if (!empty($contact_no) && preg_match('/^[6789]\d{9}$/', $contact_no)) {
$stored_otp = $this->session->userdata('mobile_otp');
$otp_expiry = $this->session->userdata('mobile_otp_expiry');
$type = 'mobile';
}
} elseif (!empty($email)) {
$stored_otp = $this->session->userdata('email_otp');
$otp_expiry = $this->session->userdata('email_otp_expiry');
$type = 'email';
} else {
echo json_encode([
'status' => 'false',
// 'msg' => $contact_no . $this->session->userdata('mobile_otp'),
'error' => 'Invalid request. Please provide OTP and either a valid mobile number or email.'
]);
return;
}
// OTP not found
if (!$stored_otp) {
echo json_encode(['status' => 'false', 'error' => 'No OTP found. Please request a new OTP.']);
return;
}
// OTP expiry check (10 minutes)
if (time() > $otp_expiry) {
if ($type === 'mobile') {
$this->session->unset_userdata('mobile_otp');
$this->session->unset_userdata('mobile_otp_expiry');
} else {
$this->session->unset_userdata('email_otp');
$this->session->unset_userdata('email_otp_expiry');
}
echo json_encode(['status' => 'false', 'error' => 'OTP has expired. Please request a new one.']);
return;
}
// OTP verification
if ($otp == $stored_otp) {
if ($type === 'mobile') {
$this->session->unset_userdata('mobile_otp');
$this->session->unset_userdata('mobile_otp_expiry');
} else {
$this->session->unset_userdata('email_otp');
$this->session->unset_userdata('email_otp_expiry');
}
echo json_encode(['status' => 'true', 'verified' => $type, 'message' => ucfirst($type) . ' OTP verified successfully.']);
} else {
// For debugging only — remove in production
// echo json_encode(['status' => 'false','otp' => $otp . " - " . $stored_otp,'error' => 'Invalid OTP.']);
echo json_encode(['status' => 'false', 'error' => 'Invalid OTP. Please try again.']);
}
}
}
|