vb_book/app/Controllers/Invoice.php

1754 lines
83 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use App\Models\EventModel;
use App\Models\CustomerModel;
use App\Models\InvoiceModel;
use App\Models\BusinessModel;
use App\Models\BooksModel;
use App\Helpers\NotificationHelper;
use App\Helpers\date_picker;
use App\Models\PaymentStatusModel;
use App\Models\SubscriptionModel;
use Mpdf\Mpdf;
use Dompdf\Dompdf;
class Invoice extends BaseController
{
protected $paymentModel;
public function __construct()
{
$this->paymentModel = new PaymentStatusModel();
}
## For Invoice Listing..
public function index()
{
helper('session');
if (is_session_active()) {
$session_role = get_user_role();
$session_bid = get_business_id();
if (!empty($session_role) && $session_role !== "sadmin") {
$this->logger->info("Invoice: Listing In Admin BID = " . $session_bid);
$where = ['I.business_id' => (int)$session_bid, 'I.isactive' => 1, 'I.invoice_type' => 1];
} else {
$this->logger->info("Invoice: Listing In the Super-Admin ");
$where = ['I.business_id != ' => NULL, 'I.isactive != ' => NULL, 'I.invoice_type' => 1];
}
$model = new InvoiceModel();
$data['page_name'] = 'Online Invoice Details';
$data['invoice'] = $model->getJoinedData($where, ['I.invoice_date', 'DESC']);
$this->logger->info("Invoice: Listing Count ." . count($data['invoice']));
$this->render_page('invoice_list', $data);
} else {
return redirect()->to('login');
}
}
public function offline_invoice()
{
helper('session');
if (is_session_active()) {
$session_role = get_user_role();
$session_bid = get_business_id();
if (!empty($session_role) && $session_role !== "sadmin") {
$this->logger->info("Invoice: Listing In Admin BID = " . $session_bid);
$where = ['I.business_id' => (int)$session_bid, 'I.isactive' => 1, 'I.invoice_type' => 1];
} else {
$this->logger->info("Invoice: Listing In the Super-Admin ");
$where = ['I.business_id != ' => NULL, 'I.isactive != ' => NULL, 'I.invoice_type' => 1];
}
$model = new InvoiceModel();
$data['page_name'] = 'Offline Invoice Details';
$data['invoice'] = $model->getJoinedData($where, ['I.invoice_date', 'DESC']);
$this->logger->info("Invoice: Listing Count ." . count($data['invoice']));
$this->render_page('offline_invoice_list', $data);
} else {
return redirect()->to('login');
}
}
## To Load Invoice ADD/EDIT page...
public function new_book_invoice($id = '0')
{
helper('session');
helper('financial_year_helper');
$model = new InvoiceModel();
$where = ['business_id' => (int)get_business_id(),'isactive' =>1];
// Get customer names for the dropdown, events details, and books details
$data['customers'] = $model->getData('customers', $where);
$data['events'] = $model->getData('events', $where);
$data['financial_year'] = get_financial_year();
$data['invoice_number_formatting'] = $model->getData('invoice_number_formatting', $where);
$data['books'] = $model->getCategoryBooks(1); // Invocie type = 2 (invoice)
$data['customers'] = array_reverse($data['customers']);
if ($id === '0') {
$this->logger->info("Book Invoice: In Add Details");
$data['page_name'] = 'Add Book Invoice Details';
$data['invoice_type'] = '1';
$data['invoice_details'] = [];
$data['invoice_item_details'] = [];
} elseif ($id !== '0') {
$this->logger->info("Book Invoice: In Edit Details ID =" . $id);
$data['page_name'] = 'Edit Book Invoice Details';
$data['invoice_type'] = '1';
$data['invoice_details'] = $model->where(['invoice_id' => $id, 'isactive' => 1])->first();
$select = ["customer_address_id", "CONCAT(address_1,' ',address_2) as address"];
$where = ['address_type' => 2, 'customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$data['invoice_details']['customer_id']];
$data['customer_shipping_arr'] = $this->get_customer_address($where, $select);
$data['invoice_item_details'] = $this->get_invoice_item($id);
}
$country = new Customer();
$data['country_details'] = $country->get_country_details(); // print_r($data['invoice_details']);die;
$this->render_page('invoice_form', $data);
}
public function new_subscription_invoice($id = '0')
{
helper('session');
helper('financial_year_helper');
$data['financial_year'] = get_financial_year();
$model = new InvoiceModel();
$where = ['business_id' => (int)get_business_id()];
// Get customer names for the dropdown, events details, and subscription books details
$data['customers'] = $model->getData('customers', $where);
$data['events'] = $model->getData('events', array_merge($where, ['isactive' => 1]));
$data['books'] = $model->getCategoryBooks(2); // Invocie type = 2 (subscription)
$data['invoice_number_formatting'] = $model->getData('invoice_number_formatting', $where);
$data['customers'] = array_reverse($data['customers']);
if ($id === '0') {
$this->logger->info("Subscription Invoice: In Add Page");
$data['page_name'] = 'Add Subscription Invoice Details';
$data['invoice_type'] = '2';
$data['invoice_details'] = [];
$data['invoice_item_details'] = [];
} elseif ($id !== '0') {
$this->logger->info("Subscription Invoice: In Edit Page ID =" . $id);
$data['page_name'] = 'Edit Subscription Invoice Details';
$data['invoice_type'] = '2';
$data['invoice_details'] = $model->where(['invoice_id' => $id, 'isactive' => 1])->first();
$select = ["customer_address_id", "CONCAT(address_1,' ',address_2) as address"];
$where = ['address_type' => 2, 'customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$data['invoice_details']['customer_id']];
$data['customer_shipping_arr'] = $this->get_customer_address($where, $select);
$data['invoice_item_details'] = $this->get_invoice_item($id);
}
$this->render_page('invoice_form', $data);
}
## For Ajax Call To Fetch/Retrive Membership Details Only Based On Customer...
public function get_customer_membership_details()
{
$customer_id = $this->request->getPost('customer_id');
$data['customer_membership'] = $this->get_customer_membership("membership", (int)$customer_id);
$bookModel = new BooksModel();
$book_id = env('RENEWAL_SCHEME_ID');
$scheme = $bookModel->select('book_id,short_code,price')->where('book_id',$book_id)->where('isactive',1)->first();
$data['scheme'] = $scheme;
return $this->response->setJSON(['data' => $data]);
}
## For Ajax Call To Fetch/Retrive Billing Address Details Only Based On Customer...
public function get_customer_billing_details()
{
$id = $this->request->getPost('customer_id');
$where = ['customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$id];
$where['address_type'] = 1;
$data['customer_billing'] = $this->get_customer_address($where, []);
$select = ["customer_address_id", "CONCAT(address_1,' ',address_2) as address","first_name"];
$where['address_type'] = 2;
$data['customer_shipping'] = $this->get_customer_address($where, $select);
return $this->response->setJSON(['data' => $data]);
}
## For Ajax Call To Fetch/Retrive Shipping Address Details Only Based On Customer...
public function get_customer_shipping_details()
{
$customer_id = $this->request->getPost('customer_id');
$address_id = $this->request->getPost('shipping_address_id');
$where = ['customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$customer_id, 'address_type' => 2, 'customer_address_id' => (int)$address_id];
$data['customer_shipping'] = $this->get_customer_address($where, []);
return $this->response->setJSON(['data' => $data]);
}
## For Gethering Address Details...
public function get_customer_address($where, $select)
{
$model = new CustomerModel();
$model->setTable('customer_addresses');
if (empty($select)) {
$select = ["customer_addresses.customer_id", "customer_addresses.customer_address_id", "customer_addresses.first_name", "customer_addresses.last_name ", "customer_addresses.company", "customer_addresses.email", "customer_addresses.mobile_no", "customer_addresses.address_type", "customer_addresses.address_1", "customer_addresses.address_2", "customer_addresses.city", "customer_addresses.state", "customer_addresses.postal_code", "customer_addresses.country", "states.state_name", "countries.country_name"];
}
$address_details = $model->select($select)->join('states', 'states.state_short_name = customer_addresses.state AND customer_addresses.country = "IN"', 'left')->join('countries', 'countries.country_short_name = customer_addresses.country', 'left')->where($where)->findAll();
return $address_details;
}
public function get_customer_membership($category, $id)
{
$model = new InvoiceModel();
$result = $model->getMembershipListForCustomer($category, $id);
return $result;
}
## To insert or update the details of the invoice
// public function save_invoice()
// {
// // echo "<pre>";
// // print_r($this->request->getPost());die;
// $this->logger->info("Invoice: Insert/Update Details");
// try {
// ## Declarions
// helper('session');
// helper('financial_year_helper');
// $model = new InvoiceModel();
// $duedate = $this->request->getVar('due_date');
// $invdate = $this->request->getVar('invoice_date');
// $invoice_status = $this->request->getPost('status');
// $invoice_id = (!empty($this->request->getPost('invoice_id'))) ? $this->request->getPost('invoice_id') : "";
// $customer_id = (int)$this->request->getPost('customer_name');
// $invoiceType = $this->request->getPost('invoice_type');
// $msg_flag_name = ((int)$invoiceType === 1) ? "Invoice " : "Subscription ";
// $renewal = 0;
// if ((int)$invoiceType === 2 && $invoice_status == 'Approved') {
// $requestData = $this->request->getPost();
// $itemid = $requestData['invoice_child_id'];
// $count = count($itemid);
// $scheme_id = null;
// if ($count > 0) {
// for ($x = 0; $x < $count; $x++) {
// if (!empty($requestData['item_details'][$x])) {
// $scheme_id = (int)$requestData['item_details'][$x];
// }
// }
// }
// // $now = date('Y-m-d');
// // $get_exists_subscription_where = ['S.customer_id' => (int)$customer_id,'S.scheme_id' => $scheme_id,'I.status' => 'Approved','I.isactive' => 1,"S.to_subscription <= "=>$now];
// $get_exists_subscription_where = ['S.customer_id' => (int)$customer_id, 'S.scheme_id' => $scheme_id, 'I.status' => 'Approved', 'I.isactive' => 1];
// $get_exists_subscription_dtls = $model->existsSubscriptionDetails($get_exists_subscription_where);
// if ($get_exists_subscription_dtls) {
// // session()->setFlashdata('success', 'This Scheme Already Existing in this Customer.');
// $this->logger->info($msg_flag_name . ": This Scheme Already Existing in this Customer. ");
// $renewal = 1;
// }
// }
// $invdate_dbformat = (!empty($invdate)) ? \DateTime::createFromFormat('d/m/Y', $invdate)->format('Y-m-d') : NULL;
// $duedate_dbformat = (!empty($duedate)) ? \DateTime::createFromFormat('d/m/Y', $duedate)->format('Y-m-d') : NULL;
// ## Array Formation For Invoice Details..
// $data = [
// 'invoice_number' => $this->request->getPost('invoice_number'),
// 'invoice_type' => $this->request->getPost('invoice_type'),
// 'customer_id' => $customer_id,
// 'billing_address_id' => (int)$this->request->getPost('billing_address_id'),
// 'billing_address' => $this->request->getPost('billing_address'),
// 'shipping_address_id' => (int)$this->request->getPost('shipping_address_id'),
// 'shipping_address' => $this->request->getPost('shipping_address'),
// 'notes' => $this->request->getPost('notes'),
// 'invoice_date' => $invdate_dbformat,
// 'due_date' => $duedate_dbformat,
// 'subtotal' => (float)$this->request->getPost('sub_total'),
// 'tax' => (float)$this->request->getPost('invoice_tax'),
// 'dis_type' => $this->request->getPost('dis_type'),
// 'discount' => (float)$this->request->getPost('discount'),
// 'exact_total_amount' => (float)$this->request->getPost('exact_total_amount'),
// 'total_amount' => (int)$this->request->getPost('grand_total'),
// 'shipping_charge' => ((int)$invoiceType === 1) ? (float)$this->request->getPost('shippingCharges') : NULL,
// 'shipping_label' => ((int)$invoiceType === 1) ? $this->request->getPost('shippingChargesLabel') : NULL,
// 'order_number' => $this->request->getPost('order_number'),
// 'payment_method' => $invoice_status !== 'Draft' ? $this->request->getPost('payment_method') : NULL, // "Credit Card," "Cash on Delivery," "PayPal","PayTm","Gpay"
// 'payment_status' => 'Pending', //"Paid," "Pending," "Failed," "Refunded," "Canceled," "Authorized," and "Completed."
// 'payment_note' => $this->request->getPost('payment_note'),
// 'event_id' => (int)$this->request->getPost('event_id'),
// 'business_id' => (int)get_business_id(),
// 'status' => $invoice_status,
// 'isactive' => 1,
// ];
// ## Based on the invoice ID, we designated Insert or Update on Details...
// if (empty($invoice_id)) {
// $data['created_by'] = (int)get_logged_user_id();
// if ($model->insert($data, 'invoices')) {
// $invoice_id = $model->insertID();
// session()->setFlashdata('success', $msg_flag_name . 'has been added successfully.');
// $this->logger->info($msg_flag_name . ": has been added successfully. Inserted ID = " . $invoice_id);
// // If it's a subscription invoice, also store data in the 'subscription' table
// } else {
// session()->setFlashdata('error', $msg_flag_name . 'could not be added. Please try again.');
// $this->logger->error($msg_flag_name . ": Err Occur could not be added. Please try again.");
// }
// } else {
// $data['updated_by'] = (int)get_logged_user_id();
// if ($model->update($invoice_id, $data)) {
// // echo $model->getLastQuery();die;
// session()->setFlashdata('success', $msg_flag_name . 'has been updated successfully.');
// $this->logger->info($msg_flag_name . ": has been updated successfully. Updated ID = " . $invoice_id);
// } else {
// session()->setFlashdata('error', $msg_flag_name . 'update failed. Please try again.');
// $this->logger->error($msg_flag_name . ": Err Failed to update ID =" . $invoice_id);
// }
// }
// $requestData = $this->request->getPost();
// if ($this->request->getPost('next_id')) {
// ## Array Formation For Invoice Numbering Format Details..
// $update_invoice_numbering = [
// 'id' => 1,
// 'id_formating' => get_financial_year(),
// 'next_id' => (int)$this->request->getPost('next_id'),
// 'business_id' => (int)get_business_id(),
// 'updated_by' => get_logged_user_id()
// ];
// $this->update_number_formatting($update_invoice_numbering);
// }
// ## For Invoice Item Details Insert/Update..
// $this->save_invoice_item($invoice_id, $requestData, (int)$this->request->getVar('product'));
// ## Subscription..
// if ((int)$invoiceType === 2) {
// // Loop through invoice items and store them in the 'subscription' table
// $subscriptionModel = new InvoiceModel(); // Replace with your actual model
// $invoiceItems = $this->get_invoice_item($invoice_id);
// foreach ($invoiceItems as $item) {
// $product_id = $item['product'];
// $from_sub_date = $item['from_subscription'];
// $to_sub_date = $item['to_subscription'];
// $subscription_data = [
// 'customer_id' => (int)$customer_id,
// 'invoice_id' => $invoice_id,
// 'scheme_id' => $product_id,
// 'from_subscription' => $from_sub_date,
// 'to_subscription' => $to_sub_date,
// 'business_id' => get_business_id(),
// 'created_by' => get_logged_user_id(),
// 'is_renew' => $renewal
// ];
// if ($invoice_status == 'Draft') {
// $get_subscription_draft_dtl_where = ['S.customer_id' => $customer_id, 'I.status' => $invoice_status];
// // $get_subscription_draft_dtl_id = $model->InactiveSubscriptionDraftDetails($get_subscription_draft_dtl_where,get_logged_user_id());
// // $this->logger->info($msg_flag_name.": has been Inactived. Inv ID = ".implode(", ", $get_subscription_draft_dtl_id));
// $get_subscription_draft_dtl_id = $model->deleteSubscriptionDraftDetails($get_subscription_draft_dtl_where, get_logged_user_id());
// $this->logger->info($msg_flag_name . ": has been Deleted. Inv ID = " . implode(", ", $get_subscription_draft_dtl_id));
// // $subscriptionModel->insertSubscriptionData($subscription_data);
// } else {
// // Check if there is a draft entry for the customer_id and scheme_id
// $get_subscription_draft_dtl_where = [
// 'S.customer_id' => $customer_id,
// 'S.scheme_id' => $scheme_id, // Assuming scheme_id is available here
// 'I.status' => 'Draft'
// ];
// $get_subscription_draft_dtl_id = $model->deleteSubscriptionDraftDetails($get_subscription_draft_dtl_where, get_logged_user_id());
// $this->logger->info($msg_flag_name . ": Draft entry has been deleted. Inv ID = " . implode(", ", $get_subscription_draft_dtl_id));
// // Now insert the new entry
// }
// }
// $subscriptionModel->insertSubscriptionData($subscription_data);
// }
// ## Notification For Approve..
// $this->logger->info($msg_flag_name . ": ID = " . $invoice_id . ", Status =" . $invoice_status);
// if ($invoice_status == 'Approved' && $invoice_id != "") {
// $this->logger->info($msg_flag_name . ": in " . $invoice_status . ". ID = " . $invoice_id);
// $this->approve_notifications((int)$invoice_id);
// }
// } catch (\Exception $e) {
// $this->logger->error($msg_flag_name . ": Err Occur =" . $e->getMessage());
// session()->setFlashdata('error', 'Message: ' . $e->getMessage());
// }
// if ($invoiceType === '2') {
// $this->logger->info(session()->getFlashdata());
// // If the invoice_type is 2 (subscription invoice), redirect to the subscription list.
// return redirect()->route('subscribers_list'); // Adjust the route name as needed.
// } else {
// // For other invoice types, redirect to the invoice list.
// $this->logger->info(session()->getFlashdata());
// return redirect()->route('offline_invoice'); // Adjust the route name as needed.
// }
// }
public function save_invoice()
{
helper('session');
helper('financial_year_helper');
$this->logger->info("Invoice: Insert/Update Details");
try {
// Retrieve form data
$invoice_status = $this->request->getPost('status');
$invoice_id = (!empty($this->request->getPost('invoice_id'))) ? $this->request->getPost('invoice_id') : "";
$invoiceType = $this->request->getPost('invoice_type');
$msg_flag_name = ((int)$invoiceType === 1) ? "Invoice " : "Subscription ";
// Handle invoice creation or update
$invoice_id = $this->create_or_update_invoice($invoice_id, $msg_flag_name);
// Handle invoice items creation or update
$this->create_or_update_invoice_items($invoice_id);
$update_invoice_numbering = [
'id' => 1,
'id_formating' => get_financial_year(),
'next_id' => (int)$this->request->getPost('next_id'),
'business_id' => (int)get_business_id(),
'updated_by' => get_logged_user_id()
];
$this->update_number_formatting($update_invoice_numbering);
// Handle subscription if invoice type is subscription
if ((int)$invoiceType === 2) {
$membership = (!empty($this->request->getPost('membership_id'))) ? $this->request->getPost('membership_id') : "";
$membership_id = substr($membership,0,6);
log_message('error','Membership id : '.$membership != null && $membership != ''? $membership : "");
$this->create_or_update_subscription($invoice_id,$invoice_status, $msg_flag_name,$membership_id);
}
// Send notification if invoice is approved
$this->logger->info($msg_flag_name . ": ID = " . $invoice_id . ", Status =" . $invoice_status);
if ($invoice_status == 'Approved' && $invoice_id != "") {
log_message('info', '[PAYMENT] Approved ' . trim($msg_flag_name) . ' saved with payment — invoice ID ' . $invoice_id);
if(null!=($this->request->getPost('contact_method_mail'))){
$contact_method['msg_mail'] = 1;
}
if(null!=($this->request->getPost('contact_method_whatsapp'))){
$contact_method['msg_whatsapp'] = 1;
}
$this->logger->info($msg_flag_name . ": in " . $invoice_status . ". ID = " . $invoice_id);
$this->approve_notifications((int)$invoice_id,isset($contact_method)?$contact_method:null);
}
// Redirect to the appropriate route based on the invoice type
if ($invoiceType === '2') {
return redirect()->route('subscribers_list');
} else {
return redirect()->route('offline_invoice');
}
} catch (\Exception $e) {
$this->logger->error("Error Occurred: " . $e->getMessage());
log_message('error', '[PAYMENT] Invoice save failed: ' . $e->getMessage());
session()->setFlashdata('error', 'Message: ' . $e->getMessage());
}
}
public function create_or_update_invoice($invoice_id, $msg_flag_name)
{
$model = new InvoiceModel();
$invoice_status = $this->request->getPost('status');
$customer_id = (int)$this->request->getPost('customer_name');
$invoiceType = $this->request->getPost('invoice_type');
// Prepare invoice data
$data = $this->prepare_invoice_data($invoice_id, $msg_flag_name);
// Insert or update invoice based on ID
if (empty($invoice_id)) {
$data['created_by'] = (int)get_logged_user_id();
if ($model->insert($data, 'invoices')) {
$invoice_id = $model->insertID();
$this->logInvoicePayment('created', $data, (int) $invoice_id);
if($data['status'] == 'Approved'){
session()->setFlashdata('success', $msg_flag_name . 'has been added successfully.');
$this->logger->info($msg_flag_name . ": Added successfully. ID = " . $invoice_id);
}else{
session()->setFlashdata('success',$msg_flag_name . 'has been added to draft successfully');
}
} else {
session()->setFlashdata('error', $msg_flag_name . 'could not be added. Please try again.');
$this->logger->error($msg_flag_name . ": Could not be added.");
}
} else {
$data['updated_by'] = (int)get_logged_user_id();
if ($model->update($invoice_id, $data)) {
$this->logInvoicePayment('updated', $data, (int) $invoice_id);
session()->setFlashdata('success', $msg_flag_name . 'has been updated successfully.');
$this->logger->info($msg_flag_name . ": Updated successfully. ID = " . $invoice_id);
} else {
session()->setFlashdata('error', $msg_flag_name . 'update failed. Please try again.');
$this->logger->error($msg_flag_name . ": Failed to update ID = " . $invoice_id);
}
}
return $invoice_id;
}
public function prepare_invoice_data($invoice_id, $msg_flag_name)
{
$invdate = $this->request->getVar('invoice_date');
$duedate = $this->request->getVar('due_date');
$invoice_status = $this->request->getPost('status');
$invoiceType = $this->request->getPost('invoice_type');
// Convert dates to database format
$invdate_dbformat = (!empty($invdate)) ? \DateTime::createFromFormat('d/m/Y', $invdate)->format('Y-m-d') : NULL;
$duedate_dbformat = (!empty($duedate)) ? \DateTime::createFromFormat('d/m/Y', $duedate)->format('Y-m-d') : NULL;
// Prepare invoice data array
return [
'invoice_number' => $this->request->getPost('invoice_number'),
'invoice_type' => $invoiceType,
'customer_id' => (int)$this->request->getPost('customer_name'),
'billing_address_id' => (int)$this->request->getPost('billing_address_id'),
'billing_address' => $this->request->getPost('billing_address'),
'shipping_address_id' => (int)$this->request->getPost('shipping_address_id'),
'shipping_address' => $this->request->getPost('shipping_address'),
'notes' => $this->request->getPost('notes'),
'invoice_date' => $invdate_dbformat,
'due_date' => $duedate_dbformat,
'subtotal' => (float)$this->request->getPost('sub_total'),
'tax' => (float)$this->request->getPost('invoice_tax'),
'dis_type' => $this->request->getPost('dis_type'),
'discount' => (float)$this->request->getPost('discount'),
'exact_total_amount' => (float)$this->request->getPost('exact_total_amount'),
'total_amount' => (int)$this->request->getPost('grand_total'),
'shipping_charge' => ((int)$invoiceType === 1) ? (float)$this->request->getPost('shippingCharges') : NULL,
'shipping_label' => ((int)$invoiceType === 1) ? $this->request->getPost('shippingChargesLabel') : NULL,
'order_number' => $this->request->getPost('order_number'),
'payment_method' => $invoice_status !== 'Draft' ? $this->request->getPost('payment_method') : NULL,
'payment_status' => $invoice_status !== 'Draft'?'Paid':'Pending',
'payment_note' => $this->request->getPost('payment_note'),
'event_id' => (int)$this->request->getPost('event_id'),
'business_id' => (int)get_business_id(),
'status' => $invoice_status,
'isactive' => 1,
];
}
public function create_or_update_invoice_items($invoice_id)
{
$this->save_invoice_item($invoice_id, $this->request->getPost(), (int)$this->request->getVar('product'));
}
public function generate_membership_id($length = 6) {
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomIndex = random_int(0, $charactersLength - 1);
$randomString .= $characters[$randomIndex];
}
return $randomString;
}
public function create_or_update_subscription($invoice_id,$invoice_status, $msg_flag_name = null,$membership_id = null)
{
$model = new InvoiceModel();
$subModel = new SubscriptionModel();
$customer_id = (int)$this->request->getPost('customer_name');
$invoiceItems = $this->get_invoice_item($invoice_id);
$renewal = 0;
if (!empty($membership_id)){
$sub_id = $subModel->select('sub_id')->where('membership_id',$membership_id)->first();
$this->checkPaymentStatus($membership_id);
}
foreach ($invoiceItems as $item) {
$product_id = $item['product'];
$from_sub_date = $item['from_subscription'];
$to_sub_date = $item['to_subscription'];
//check if membership id is already set for the customer
$membership_id = $this->generate_membership_id(6);
// To check if the generated membership is already created for another customer
$result = $subModel->where('membership_id',$membership_id)->findAll();
if (count($result)>0){
$membership_id = $this->generate_membership_id(6);
}
// Prepare subscription data
$subscription_data = [
'customer_id' => $customer_id,
'invoice_id' => $invoice_id,
'scheme_id' => $product_id,
'from_subscription' => $from_sub_date,
'to_subscription' => $to_sub_date,
'business_id' => get_business_id(),
'created_by' => get_logged_user_id(),
'updated_by' => get_logged_user_id(),
'is_renew' => isset($sub_id)?$sub_id['sub_id']:$renewal,
'membership_id'=>$membership_id,
'status' =>1,
'isactive' =>$invoice_status === 'Approved' ? 1 : 0
];
$check_existing_customer_id = $subModel->where('invoice_id',$invoice_id)->findAll();
//dd($check_existing_customer_id);
// if($check_existing_customer_id){
// unset($data['created_by']);
// log_message('info',json_encode($subscription_data));
// $where = ['invoice_id'=>$invoice_id];
// $subModel->updateData($subscription_data,$where);//update the data
// }
// else{
// //insert the data
// unset($data['updated_by']);
$model->insertupdateSubscriptionData($subscription_data,$invoice_status);
// }
}
}
public function checkPaymentStatus($membership_id){
try {
$paymentRow = $this->paymentModel->where('membership_id', $membership_id)->where('payment_status','Not Received')->first();
if ($paymentRow) {
$this->paymentModel->update($paymentRow['id'], [
'status' => 999999,
'payment_status' => 'Approved',
'updated_by' => (int) get_logged_user_id(),
]);
log_message('info', '[PAYMENT] Staff recorded offline renewal for membership ' . $membership_id . ' — linked Paytm order ' . ($paymentRow['order_id'] ?? '') . ' marked as Approved by user ' . get_logged_user_id());
} else {
log_message('debug', '[PAYMENT] No pending Paytm payment found to approve for membership ' . $membership_id);
}
} catch (\Exception $e) {
log_message('warning', '[PAYMENT] Could not update payment status for membership ' . $membership_id . ': ' . $e->getMessage());
}
}
private function logInvoicePayment(string $action, array $invoiceData, int $invoiceId): void
{
$type = ((int) ($invoiceData['invoice_type'] ?? 0) === 2) ? 'Subscription' : 'Invoice';
$status = $invoiceData['status'] ?? 'Unknown';
$method = $invoiceData['payment_method'] ?? 'Not specified';
$amount = $invoiceData['exact_total_amount'] ?? ($invoiceData['total_amount'] ?? 0);
$number = $invoiceData['invoice_number'] ?? (string) $invoiceId;
$customerId = $invoiceData['customer_id'] ?? '';
if ($status === 'Draft') {
log_message('info', '[PAYMENT] ' . $type . ' draft saved — invoice ' . $number . ', customer ' . $customerId . ', amount Rs.' . $amount . '. Payment not recorded yet.');
return;
}
log_message('info', '[PAYMENT] ' . $type . ' ' . $action . ' — invoice ' . $number . ', customer ' . $customerId . ', amount Rs.' . $amount . ', method ' . $method . ', payment status ' . ($invoiceData['payment_status'] ?? ''));
}
## For Updating Events Details ..
public function update_number_formatting($update_events)
{
// `id``event_name``business_id``updated_by``updated_on``next_id`
$model = new InvoiceModel();
$model->setTable('invoice_number_formatting');
$where = ['isactive' => 1, 'id' => (int)$update_events['id'], 'business_id' => (int)$update_events['business_id'], 'next_id' => $update_events['next_id']];
$details = $model->where($where)->findAll();
if (empty($details)) {
$update_where = ['id' => (int)$update_events['id'], 'business_id' => (int)$update_events['business_id']];
$update_data = ['next_id' => $update_events['next_id'], 'updated_by' => $update_events['updated_by']];
$model->updateData('invoice_number_formatting', $update_data, $update_where);
}
log_message('debug',"inside update_number_formatting");
}
## To insert or update invoice item details based on invoice ID
public function save_invoice_item($id, $requestData)
{
## Get Invoice item details (to checking purpose exist or not based on invoice ID)
$getInvoiceItemDetails = $this->get_invoice_item($id);
## Declaration
$statement = "";
$model = new InvoiceModel();
$itemid = $requestData['invoice_child_id'];
## IF Any Missing value Means that values are Inactive here....
if (!empty($itemid)) {
$filteringInvoiceItemIds = [];
for ($y = 0; $y < count($getInvoiceItemDetails); $y++) {
$filteringInvoiceItemIds[$y] = $getInvoiceItemDetails[$y]['invoice_child_id'];
}
if (!empty($filteringInvoiceItemIds)) {
$A = $filteringInvoiceItemIds;
$B = $itemid;
$missingValues = array_diff($A, $B);
if (!empty($missingValues)) {
$where = ['isactive' => 1, 'invoice_id' => (int)$id];
// $model->inactiveMissingInvoiceItemDetails($where, $missingValues);
$model->deleteMissingInvoiceItemDetails($where, $missingValues);
$this->logger->info("Child Item Details : has been Deleted. Inv Child ID = " . implode(", ", $missingValues));
}
}
}
// echo "<br/>....................";
//var_dump($itemid);die();
$count = count($itemid);
log_message('info','the count is '.$count);
log_message('debug','request data = '.json_encode($requestData));
$invoiceitem_arr = [];
if ($count > 0) {
for ($x = 0; $x < $count; $x++) {
log_message('info','inside the for loop');
if (!empty($requestData['item_details'][$x])) {
log_message('debug','inside 1');
$invoiceitem_arr[$x]['invoice_id'] = $id;
$invoiceitem_arr[$x]['product'] = (int)$requestData['item_details'][$x];
$invoiceitem_arr[$x]['description'] = $requestData['description'][$x];
$invoiceitem_arr[$x]['quantity'] = (int)$requestData['quantity'][$x];
$invoiceitem_arr[$x]['tax'] = (float)$requestData['tax'][$x];
$invoiceitem_arr[$x]['unit_price'] = (float)$requestData['rate'][$x];
$invoiceitem_arr[$x]['subtotal'] = (float)$requestData['amount'][$x];
$invoiceitem_arr[$x]['discount_amount'] = (float)$requestData['discount_amount'][$x];
$invoiceitem_arr[$x]['discount_type'] = $requestData['discount_type'][$x];
if (!empty($requestData['from_subscription'])) {
$invoiceitem_arr[0]['from_subscription'] = \DateTime::createFromFormat('d/m/Y', $requestData['from_subscription'])->format('Y-m-d');
}
if (!empty($requestData['to_subscription'])) {
$invoiceitem_arr[0]['to_subscription'] = \DateTime::createFromFormat('d/m/Y', $requestData['to_subscription'])->format('Y-m-d');
}
$invoiceitem_arr[$x]['created_by'] = (int)get_logged_user_id();
$invoiceitem_arr[$x]['updated_by'] = (int)get_logged_user_id();
$invoiceitem_arr[$x]['isactive'] = 1;
$invoiceitem_arr[$x]['invoice_child_id'] = $itemid[$x];
}
else{
log_message('info','inside else');
}
}
log_message('info','this is inside the save_invoice_item'.json_encode($invoiceitem_arr));
$statement = $model->saveInvoiceItemDetails($invoiceitem_arr);
}
return $statement;
}
## To Retrive Invoice item details based on invoice ID
public function get_invoice_item($id)
{
$model = new InvoiceModel();
$model->setTable('invoiceitems');
$where = ['isactive' => 1, 'invoice_id' => $id];
$details = $model->where($where)->findAll();
return $details;
}
## To Inactive Invoice details based on invoice ID Including Invoice Item Details also
public function delete_invoice($id)
{
helper('session');
$session_uid = get_logged_user_id();
try {
$model = new InvoiceModel();
$where = ['isactive' => 1, 'business_id' => (int)get_business_id(), 'invoice_id' => (int)$id];
$existed = $model->where($where)->findAll();
$this->logger->Info("Invoice : Going to Inactive ID = " . $id);
if ($existed) {
$invoiceRow = $model->select('invoice_number, payment_method, payment_status, total_amount')
->where('invoice_id', (int) $id)->first();
$data['isactive'] = 0;
$data['updated_by'] = get_logged_user_id();
if ($model->update($id, $data)) {
session()->setFlashdata('success', 'Deleted successfully.');
$this->logger->info("Invoice: has been Inactived successfully. Inactived ID = " . $id);
if ($invoiceRow && ($invoiceRow['payment_status'] ?? '') === 'Paid') {
log_message('warning', '[PAYMENT] Paid invoice ' . ($invoiceRow['invoice_number'] ?? '') . ' was deleted (ID ' . $id . '), method ' . ($invoiceRow['payment_method'] ?? ''));
}
} else {
$this->logger->error("Invoice: Not able to Inactive ID =" . $id);
throw new \Exception("Data Not able to Deleted");
}
$getInvoiceItemDetails = $this->get_invoice_item($id);
if ($getInvoiceItemDetails) {
$update_where = ['invoice_id' => (int)$id];
$model->updateData('invoiceitems', $data, $update_where);
}
} else {
$this->logger->error("Invoice: Does Not Exist To Inactive, ID = " . $id);
throw new \Exception("Invoice Already Deleted");
}
} catch (\Exception $e) {
$this->logger->error("Invoice: Err Occur = " . $e->getMessage());
session()->setFlashdata('error', 'Message: ' . $e->getMessage());
}
return redirect()->route('offline_invoice');
}
## To Approve Invoice details based on invoice ID
public function approve_invoice($id)
{
try {
if (!$id) {
throw new \Exception("Invoice can't able to Approved. Because ID can't Found");
}
$model = new InvoiceModel();
helper('session');
$where = ['isactive' => 1, 'status' => 'Approved', 'invoice_id' => (int)$id];
$details = $model->where($where)->findAll();
if (empty($details)) { // Array Empty Means allow to Approve.
$invoiceRow = $model->select('invoice_number, customer_id, total_amount, exact_total_amount, payment_method, payment_status, invoice_type')
->where('invoice_id', (int) $id)->first();
$data = ['status' => 'Approved', 'updated_by' => get_logged_user_id()];
if ($model->update($id, $data)) {
if ($invoiceRow) {
$this->logInvoicePayment('approved', array_merge($invoiceRow, ['status' => 'Approved']), (int) $id);
}
$this->approve_notifications((int)$id);
session()->setFlashdata('success', 'Invoice has been Approved Successfully.');
$this->logger->info("Invoice: has been Approved successfully. ID = " . $id);
} else {
$this->logger->error("Invoice: Does Not Exist To Approved");
throw new \Exception("Invoice can't Approved");
}
} else {
$this->logger->error("Invoice: already Approved ID = " . $id);
throw new \Exception("Invoice already Approved");
}
} catch (\Exception $e) {
$this->logger->error("Invoice: Err Occur = " . $e->getMessage());
session()->setFlashdata('error', 'Message: ' . $e->getMessage());
}
// Redirect back to the invoice list
return redirect()->route('offline_invoice');
}
public function subscription_inactive()
{
$model = new InvoiceModel();
$details = $model->subscription_inactive();
$now = date('d-m-Y');
if (strtolower(gettype($details)) == "string") {
$this->logger->info("Subscription Inactive : " . $details);
$result = $details;
} else {
$this->logger->info("Subscription Inactive : " . count($details) . " Subscription Records " . json_encode($details));
$success_rating = isset($details['success_rating']) ? $details['success_rating'] : 0;
$error_rating = isset($details['error_rating']) ? $details['error_rating'] : 0;
$result = "Total " . count($details) . " Subscription Records.\n success rating = " . $success_rating . "\n fail rating = " . $error_rating . "\n Note : Check Your Log File";
}
return $now . " " . $result;
}
public function approve_notifications($invoice_id,$contact_method = null)
{
log_message('info',"Approve Notifications : ID " . $invoice_id);
$model = new InvoiceModel();
$where = ['I.business_id' => (int)get_business_id(), 'I.invoice_id' => $invoice_id, 'I.isactive' => 1];
$details = $model->getDetailForApproveNotifications($where);
$records = [];
$reference_number = "";
$invoice_serial_number = "";
$recipient_name = "";
$approval_date = "";
$approved_by = "";
$recipient_email = "";
$recipient_mobile = "";
$subtotal = "";
$tax = "";
$total_amount = "";
$payment_method = "";
$business_name = "";
$business_address = "";
$business_city = "";
$business_state = "";
$business_postal_code = "";
$business_email = "";
$business_mobile_no = "";
if (isset($details)) {
log_message('info',"Invoice: approve notification Request data type = " . gettype($details));
}
helper('notification');
$notification = new NotificationHelper();
foreach ($details['invoice'] as $rec) {
$reference_number = $rec['order_number'];
$invoice_serial_number = $rec['invoice_number'];
$recipient_name = $rec['customer_name'];
$approval_date = $rec['status'] == 'Approved' && $rec['updated_by'] !== NULL ? $rec['updated_on_format'] : $rec['created_on_format'];
$approved_by = $rec['status'] == 'Approved' && $rec['updated_by'] !== NULL ? $rec['updated_by_name'] : $rec['created_by_name'];
$recipient_email = $rec['customer_email'];
$recipient_mobile = $rec['customer_mobile'];
$subtotal = $rec['subtotal'];
$tax = $rec['tax'];
$invoiceDate = $rec['invoice_date'];
$total_amount = $rec['total_amount'];
$payment_method = $rec['payment_method'];
$business_name = $rec['business_name'];
$business_address = $rec['business_address'];
$business_city = $rec['business_city'];
$business_state = $rec['business_state'];
$business_postal_code = $rec['business_postal_code'];
$business_email = $rec['business_email'];
$business_mobile_no = $rec['business_mobile_no'];
}
if (!isset($recipient_email)){
log_message('error','Email Id not set for customer');
return;
}
$records['invoice_order_number'] = $reference_number;
$records['invoice_serial_number'] = $invoice_serial_number;
$records['recipient_name'] = $recipient_name;
$records['recipient_email'] = $recipient_email ? $recipient_email : $business_email;
$records['subtotal'] = $subtotal;
$records['tax'] = $tax;
$records['total_amount'] = $total_amount;
$records['payment_method'] = $payment_method;
$records['favicon'] = base_url("public/uploads/default.ico");
$records['browser_title'] = "bbb-bp | Approve Template";
$records['page_name'] = 'Approve Template';
// view('approve_template',$records);
// $this->logger->info("Approve : Request data = ".json_encode($records));
// view('approve_template',$records);
$records['template_name'] = 'approve_template';
$records['item'] = $details['item'];
// print_r($records['item']);die;
$lineitem_html = "";
foreach ($records['item'] as $inv) {
// print_r($item->title);die;
$lineitem_html .= '<p>' . $inv->title . ' x ' . $inv->quantity . ' => ' . $inv->subtotal . '</p>';
}
// print_r($title);die;
$records['subject'] = $invoice_serial_number . " - Invoice Notification";
$records['description'] = "<html>
<body>
<div class='custom-box' style=' border: 1px solid #ccc;
padding: 20px;
border-radius: 10px;
width: 300px; /* Adjust the width as needed */
margin: 20px auto; text-align: center;'>
<h2><img src='https://pbs.twimg.com/profile_images/1116902407332450304/QEQWyRq2_400x400.jpg'alt='Company Logo' style='max-width: 100px; margin-bottom: -20%;;'></h2>
<p style='color: red;
font-size: larger;'><b>THANKS FOR YOUR ORDER!!<b></p>
<p>Invoice Number:#$invoice_serial_number</p>
<p>Total Amount:$total_amount</p>
<!-- Download Invoice Button -->
<a href='" . base_url("download_invoice_pdf/" . md5($invoice_id)) . "' style='display: inline-block; padding: 10px; background-color: #4CAF50; color: #fff; text-decoration: none; border-radius: 5px; margin-top: 20px;'>Download Invoice</a>
<br>
<p>Thank you for choosing us!</p>
<ul style='list-style:none;font-size: 10px; text-align: center;margin-right:54px;'>
<li> $business_name</li>
<li>$business_address $business_city $business_state - $business_postal_code</li>
<li>Call Us: +91 $business_mobile_no</li>
<li>Email Us: $business_email</li>
</ul>
</div>
</body>
</html>";
// print_r($records['description']);die;
$url = base_url("download_invoice_pdf/" . md5($invoice_id));
$encodedUrl = urlencode($url);
if(isset($contact_method['msg_whatsapp'])){
$template = "Dear " . $recipient_name . ",\r\r\n\nYour Invoice has been generated.\n\nDetails:\r\n- Invoice Date: " . $invoiceDate . "\r\n- Invoice Number: " . $invoice_serial_number . "\r\n- Click here to download the Invoice: " . $url;
$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'];
}
$records['cc'] = getenv('BuisnessCCMail');
if(isset($contact_method['msg_mail'])){
log_message('info',"Approve notification Email Request data = " . json_encode($records));
$email_result = $notification->sendEmail($records);
log_message('info',"Approve notification Email Response = " . json_encode($email_result));
}
// $this->logger->info("Approve notification Whatsapp Request data = " . json_encode($params));
// $whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
// $this->logger->info("Approve notification Whatsapp Response = " . json_encode($whatsapp_result));
}
## To Generate Invoice PDF based on invoice ID
public function generate_invoice_pdf($id)
{
$model = new InvoiceModel();
$data = $model->getInvoiceData($id);
$invoiceItems = $model->getInvoiceItems($id, 'groupby');
foreach ($invoiceItems as $index => $singleItem) {
$productImgs = $model->getProductImgs($singleItem->product);
$invoiceItems[$index]->imgs = $productImgs;
}
$invoice_type = $data[0]->invoice_type;
// Create an mPDF object
ob_clean();
$mpdf = new Mpdf([
'mode' => '',
'format' => [148, 210], // Set custom width and height in millimeters
'default_font_size' => 0,
'default_font' => '',
'margin_left' => 2,
'margin_right' => 2,
'margin_top' => 6,
'margin_bottom' => 6,
'margin_header' => 6,
'margin_footer' => -30,
'orientation' => 'P',
]);
$mpdf->autoLangToFont = true;
$mpdf->autoScriptToLang = true;
// Set PDF properties
$mpdf->SetTitle('Invoice');
$mpdf->SetAuthor($data[0]->company_name);
$mpdf->SetCreator('');
$htmlFooter = '<div >
<img src="https://cdn.pixabay.com/photo/2012/04/26/14/17/blue-42596_960_720.png"style=margin-top:70px;/> </div>';
$mpdf->setHTMLFooter($htmlFooter);
// Generate the PDF content (HTML)
if ($data[0]->status === 'Draft') {
// Set the watermark text and options
$mpdf->SetWatermarkText('Draft');
$mpdf->showWatermarkText = true;
}
if ($data[0]->status === 'Cancelled') {
// Set the watermark text and options
$mpdf->SetWatermarkText('Cancelled');
$mpdf->showWatermarkText = true;
}
if ($data[0]->status === 'Void') {
// Set the watermark text and options
$mpdf->SetWatermarkText('Void');
$mpdf->showWatermarkText = true;
}
$BusinessModel = new BusinessModel();
$business = $BusinessModel->where('business_id',$data[0]->business_id)->first();
// Generate the PDF content (HTML) with data
$html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems,'business' => $business, 'invoice_type' => $invoice_type, 'invoiceTerms' => $data]);
// echo $html;die;
// Load HTML into the mPDF instance
// print_r($html);die;
$mpdf->WriteHTML($html);
// Output the PDF to the browser for download
// $mpdf->Output('invoice_' . date('Y-m-d H-i-s') . '.pdf', 'D');
//$mpdf->Output("invoice_" . $data[0]->invoice_number . '.pdf', 'D');
$filename = 'invoice_' . $data[0]->invoice_number.'.pdf'; // Filename based on invoice number
// $mpdf->Output($filename . '.pdf', 'D'); // Generate and download the PDF with the specified filename
$mpdf->Output($filename, 'D'); // Generate and download the PDF with the specified filename
// header('Content-Type: application/pdf');
// header('Content-Disposition: inline; filename="invoice_' . $data[0]->invoice_number . '.pdf"');
// header('Content-Transfer-Encoding: binary');
// header('Accept-Ranges: bytes');
// header('Cache-Control: private');
// header('Pragma: private');
exit();
// Set headers to force download with the correct filename
}
public function generate_invoice_pdf_preview($id)
{
// Load required model
$model = new InvoiceModel();
$BusinessModel = new BusinessModel();
$data = $model->getInvoiceData($id);
$business = $BusinessModel->where('business_id',$data[0]->business_id)->first();
$invoiceItems = $model->getInvoiceItems($id, 'groupby');
foreach ($invoiceItems as $index => $singleItem) {
$productImgs = $model->getProductImgs($singleItem->product);
$invoiceItems[$index]->imgs = $productImgs;
}
$invoice_type = $data[0]->invoice_type;
// Get status data
$status = $data[0]->status;
// Load view with data
$html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems, 'invoice_type' => $invoice_type,'business' => $business, 'invoiceTerms' => $data, 'status' => $status]);
// Return HTML content
echo $html;
}
public function generate_invoice_print_preview($id)
{
// Load required model
$model = new InvoiceModel();
$data = $model->getInvoiceData($id);
$BusinessModel = new BusinessModel();
$business = $BusinessModel->where('business_id',$data[0]->business_id)->first();
// print_r($data);die;
$invoiceItems = $model->getInvoiceItems($id, 'groupby');
foreach ($invoiceItems as $index => $singleItem) {
$productImgs = $model->getProductImgs($singleItem->product);
$invoiceItems[$index]->imgs = $productImgs;
}
$invoice_type = $data[0]->invoice_type;
// Get status data
$status = $data[0]->status;
// Load view with data
// $html = view('invoice_print_preview_template', ['data' => $data, 'invoiceItems' => $invoiceItems,'business'=>$business, 'invoice_type' => $invoice_type, 'invoiceTerms' => $data, 'status' => $status]);
$html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems, 'invoice_type' => $invoice_type,'business' => $business, 'invoiceTerms' => $data, 'status' => $status]);
// dd($html);die;
// Return HTML content
echo $html;
}
public function print_address($id)
{
// Fetch the invoice data based on $id
$model = new InvoiceModel();
$invoiceData = $model->getInvoiceData($id);
// print_r($invoiceData);die();
// Initialize an empty PDF with custom paper size (4x6 inches)
$config = [
'mode' => 'utf-8',
'format' => [101.6, 152.4],
'default_font_size' => 12,
'default_font' => 'Arial',
'margin_left' => 0,
'margin_right' => 0,
'margin_top' => 0,
'margin_bottom' => 0,
'margin_header' => 0,
'margin_footer' => 0,
'orientation' => 'P', // Portrait
];
$mpdf = new Mpdf($config);
$mpdf->SetTitle('Customer Address');
$mpdf->SetAuthor($invoiceData[0]->company_name);
$mpdf->SetCreator('');
// Generate the PDF content (HTML) with customer and address data
$html = view('address_pdf_template', ['invoiceData' => $invoiceData]);
// Load the mPDF library
// Set PDF properties
// Load HTML content into mPDF
$mpdf->WriteHTML($html);
// Output the PDF for download
$pdfFileName = 'customer_address_' . date('Y-m-d H-i-s') . '.pdf';
$mpdf->Output($pdfFileName, 'D');
}
public function print_address_landscape($id)
{
$model = new InvoiceModel();
$invoiceData = $model->getInvoiceData($id);
// print_r($invoiceData);die();
$config = [
'mode' => 'utf-8',
'format' => 'A5-L', // A5 landscape format
'default_font_size' => 12,
'default_font' => 'Arial',
'margin_left' => 10,
'margin_right' => 10,
'margin_top' => 10,
'margin_bottom' => 10,
'orientation' => 'L', // Landscape orientation
];
// $mpdf = new \Mpdf\Mpdf($config);
$mpdf = new Mpdf($config);
$mpdf->SetTitle('Customer Address');
$mpdf->SetAuthor($invoiceData[0]->company_name);
// Generate the PDF content (HTML) with customer and address data
$html = view('address_pdf_landscape_template', ['invoiceData' => $invoiceData]);
// echo $html;die;
$mpdf->WriteHTML($html);
// $pdfFileName = 'customer_address_' . date('Y-m-d_H-i-s') . '.pdf';
$pdfFileName = $invoiceData[0]->invoice_number.'.pdf';
$mpdf->Output($pdfFileName, 'D');
}
public function general_inv_rp()
{
$model = new InvoiceModel();
if ($this->request->is('get')) {
$data['report_data'] = $model->get_general_invoice_data();
$data['selected_data'] = "";
} else {
$dateParts = explode(' - ', $this->request->getVar('date'));
$fromDate = $dateParts[0];
$toDate = $dateParts[1];
// Update date conversion format using the global namespace
$fromDate = \DateTime::createFromFormat('d/m/Y', $dateParts[0])->format('Y-m-d');
$toDate = \DateTime::createFromFormat('d/m/Y', $dateParts[1])->format('Y-m-d');
// Debugging statements for date range
// var_dump($fromDate, $toDate);die;
$data['report_data'] = $model->get_general_invoice_data($fromDate, $toDate);
$data['selected_data'] = ($this->request->getVar('date')) ? $this->request->getVar('date') : '';
// var_dump( $data['selected_data']);die;
}
// Debugging statement for report data
// print_r($data['selected_data']);die;
$data['page_name'] = 'Sales Report';
$this->render_page('report_general_invoice', $data);
}
public function general_membership_inv_rp()
{
if ($this->request->getmethod() == 'get') {
$model = new InvoiceModel();
$data['report_data'] = $model->get_mem_invoice_data();
$this->logger->info("Membership Invoice Report ");
$data['page_name'] = 'Membership Invoice Report';
$this->render_page('report_mem_invoice', $data);
} else {
$dateParts = explode(' - ', $this->request->getVar('date'));
$fromDate = $dateParts[0];
$toDate = $dateParts[1];
$dateTime = \DateTime::createFromFormat('m/d/Y', $fromDate);
$dateTime1 = \DateTime::createFromFormat('m/d/Y', $toDate);
$model = new InvoiceModel();
$data['report_data'] = $model->get_mem_invoice_data($dateTime->format('Y-m-d'), $dateTime1->format('Y-m-d'));
$this->logger->info("Membership Invoice Report ");
$data['page_name'] = 'Membership Invoice Report';
$data['selected_data'] = $this->request->getVar('date');
$this->render_page('report_mem_invoice', $data);
}
}
public function expired_customer_report()
{
$model = new InvoiceModel();
if ($this->request->getmethod() == 'get') {
$data['expired_customers'] = $model->getExpiredCustomers();
$data['selected_data'] = "";
} else {
$dateParts = explode(' - ', $this->request->getVar('date'));
$dates = datePicker($dateParts);
// $fromDate = $dateParts[0];
// $toDate = $dateParts[1];
// $dateTime = \DateTime::createFromFormat('d/m/Y', $fromDate);
// $dateTime1 = \DateTime::createFromFormat('d/m/Y', $toDate);
$model = new InvoiceModel();
$data['expired_customers'] = $model->getExpiredCustomers($dates['dateTime']->format('Y-m-d'), $dates['dateTime1']->format('Y-m-d'));
$data['selected_data'] = $this->request->getVar('date');
$this->logger->info("Itemwise Report ");
}
if (empty($data['selected_data'])){
//dd($data['selected_data']);
$data['page_name'] = 'Membership Renewal Report (30 days)';
}else{
list($fromDate, $toDate) = explode(" - ", $data['selected_data']);
$data['page_name'] = 'Membership Renewal Report - <br>(From '.$fromDate.' To '.$toDate.')';
}
$this->render_page('report_expired_customers', $data);
}
public function itemwise_report()
{
$model = new InvoiceModel();
if ($this->request->getmethod() == 'get') {
$data['report_data'] = $model->itemwise_report_data();
$this->logger->info("Itemwise Report getMETHOD ");
$data['selected_data'] = "";
} else {
$value = $this->request->getPost('value');
if (isset($value)){
// Handle CSV export
$this->exportCsv();
$this->logger->info("Itemwise Report CSV ");
}
else{
// Handle date range filter
$this->logger->info("Itemwise Report getPOST ");
$dateParts = explode(' - ', $this->request->getVar('date'));
$dates = datePicker($dateParts);
// $fromDate = $dateParts[0];
// $toDate = $dateParts[1];
// $dateTime = \DateTime::createFromFormat('d/m/Y', $fromDate);
// $dateTime1 = \DateTime::createFromFormat('d/m/Y', $toDate);
$model = new InvoiceModel();
$data['report_data'] = $model->itemwise_report_data($dates['dateTime']->format('Y-m-d'), $dates['dateTime1']->format('Y-m-d'));
$data['selected_data'] = $this->request->getVar('date');
$this->logger->info('dsvawvsd');
$this->logger->info("Itemwise Report2 ");
}
}
$data['page_name'] = 'Bookswise Report';
$this->render_page('report_itemwise', $data);
}
public function userwise_eventwise_report(){
$model = new InvoiceModel();
if ($this->request->getMethod() == 'get'){
$data['report_data'] = $model->userwise_eventwise_report();
$data['selected_data'] = '';
$this->logger->info("Inside GEt method");
}
else{
$dateParts = explode(' - ', $this->request->getVar('date'));
$dates = datePicker($dateParts);
$model = new InvoiceModel();
$data['report_data'] = $model->userwise_eventwise_report($dates['dateTime']->format('Y-m-d'), $dates['dateTime1']->format('Y-m-d'));
$data['selected_data'] = $this->request->getVar('date');
$this->logger->info('dsvawvsd');
$this->logger->info("Itemwise Report2 ");
}
$data['page_name'] = 'User and Event wise Report';
$this->render_page('report_userwise_and_eventwise',$data);
}
public function received_payments_report(){
$model = new InvoiceModel();
if ($this->request->getMethod() == 'get'){
$data['payment_data'] = $model->getPaymentReport();
$data['selected_data'] = "";
$this->logger->info("Inside the get method");
}
else{
$dateParts = explode(' - ',$this->request->getVar(('date')));
$dates = datePicker($dateParts);
// $fromDate = $dateParts[0];
// $toDate = $dateParts[1];
// $dateTime = \DateTime::createFromFormat('d/m/Y',$fromDate);
// $dateTime1 = \DateTime::createFromFormat('d/m/Y',$toDate);
$data['payment_data'] = $model->getPaymentReport($dates['dateTime']->format('Y-m-d'), $dates['dateTime1']->format('Y-m-d'));
$data['selected_data'] = $this->request->getVar('date');
}
$data['page_name'] = 'Received Payments Report';
// log_message('info',json_encode($data));
$this->render_page('received_payments_report',$data);
}
public function itemwise_report_with_payment_method(){
$model = new InvoiceModel();
if ($this->request->getMethod() == 'get'){
$data['report_data'] = $model->itemwise_report_data_with_payment_method();
$data['selected_data'] = "";
$this->logger->info("Inside the get method");
}
else{
$dateParts = explode(' - ',$this->request->getVar(('date')));
$dates = datePicker($dateParts);
// $fromDate = $dateParts[0];
// $toDate = $dateParts[1];
// $dateTime = \DateTime::createFromFormat('d/m/Y',$fromDate);
// $dateTime1 = \DateTime::createFromFormat('d/m/Y',$toDate);
$data['report_data'] = $model->itemwise_report_data_with_payment_method($dates['dateTime']->format('Y-m-d'), $dates['dateTime1']->format('Y-m-d'));
$data['selected_data'] = $this->request->getVar('date');
}
$data['page_name'] = 'Sales By Books';
// dd($data);
$this->render_page('itemwise_report_with_payment_method',$data);
}
private function exportCsv()
{
$model = new InvoiceModel();
$reportData = $model->itemwise_report_data();
$csvFileName = 'itemwise_report.csv';
// Set appropriate headers for CSV download
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $csvFileName . '"');
header('Pragma: no-cache');
header('Expires: 0');
// Open a PHP output stream for writing CSV data
$output = fopen('php://output', 'w');
// Add UTF-8 BOM to the CSV file
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
// Write the CSV headers
fputcsv($output, ['Publisher Code', 'Book Name', 'Item Count', 'Total Cost']);
// Write the CSV data
foreach ($reportData as $row) {
foreach ($row->books as $book) {
$rowData = [
$row->publisher_code,
$book->book_name,
$book->item_count,
$book->total_cost,
];
// Convert each field to UTF-8 using iconv
$rowData = array_map(function ($field) {
return iconv('UTF-8', 'UTF-8//IGNORE', $field);
}, $rowData);
fputcsv($output, $rowData);
}
}
// Close the PHP output stream
fclose($output);
// Terminate the script to prevent further output
exit();
}
private function calculateTotalBookQuantity(&$reportData)
{
// Calculate the total book quantity for each publisher
foreach ($reportData as &$row) {
$totalBookQuantity = array_sum(array_column($row->books, 'quantity'));
$row->total_book_quantity = $totalBookQuantity;
}
}
public function book_publishwise_Report()
{
if ($this->request->getmethod() == 'get') {
$model = new InvoiceModel();
$data['report_data'] = $model->itemwise_report_data_with_publish_code();
$data['selected_data'] = "";
$this->logger->info("Itemwise Report ");
$data['page_name'] = 'Books Published';
// print_r($data);die;
$this->render_page('report_book_publish', $data);
} else {
$dateParts = explode(' - ', $this->request->getVar('date'));
$fromDate = $dateParts[0];
$toDate = $dateParts[1];
$dateTime = \DateTime::createFromFormat('d/m/Y', $fromDate);
$dateTime1 = \DateTime::createFromFormat('d/m/Y', $toDate);
$model = new InvoiceModel();
$data['report_data'] = $model->itemwise_report_data_with_publish_code($dateTime->format('Y-m-d'), $dateTime1->format('Y-m-d'));
$this->logger->info("Itemwise Report ");
$data['page_name'] = 'Books Published';
$data['selected_data'] = $this->request->getVar('date');
$this->render_page('report_book_publish', $data);
}
}
## Child Function Called in approve_notifications
public function download_invoice_pdf($md5Hash)
{
$model = new InvoiceModel();
$invoice_id = $model->getInvoiceIdByMd5($md5Hash);
if ($invoice_id) {
$this->generate_invoice_pdf($invoice_id);
} else {
echo "no code works";
}
}
public function saveBook()
{
// Retrieve book details from POST data
$bookName = $this->request->getPost('bookName');
$publication_date = $this->request->getPost('publication_date');
$publication_code = $this->request->getPost('publishers_code');
$isbn_code = $this->request->getPost('isbn_code');
$bookPrice = $this->request->getPost('bookPrice');
$publisher_name = $this->request->getPost('publisher');
// Load the model
$model = new BooksModel();
// Call the model function to save the book
$bookId = $model->saveBook($bookName, $bookPrice, $isbn_code, $publication_date, $publication_code, $publisher_name);
// Return a response (e.g., JSON response)
$response = array();
if ($bookId) {
$response['success'] = true;
$response['message'] = 'Book Added Successfully';
$response['book_id'] = $bookId; // Include the book ID in the response
$response['title'] = $bookName;
// $response['tax'] = $bookId;
$response['price'] = $bookPrice;
} else {
$response['success'] = false;
$response['message'] = 'Failed to save book.';
}
// Send JSON response
return $this->response->setJSON($response);
}
// Your controller method to handle updating status and reason
public function updateInvoiceStatus()
{
// Retrieve data from the request
$invoiceId = $this->request->getPost('invoice_id');
$voidReason = $this->request->getPost('void_reason');
// Perform any validation if needed
// Update the invoice status and void reason in the database
$model = new InvoiceModel(); // Assuming you have a model named InvoiceModel
$updated = $model->updateInvoiceStatus($invoiceId, $voidReason);
// Prepare the response
$response = [];
if ($updated) {
$response['success'] = true;
$response['message'] = 'Invoice status updated successfully.';
} else {
$response['success'] = false;
$response['message'] = 'Failed to update invoice status.';
}
if ($updated) {
}
// Return the response as JSON
return $this->response->setJSON($response);
}
public function updateInvoiceCancelStatus()
{
// Retrieve data from the request
$invoiceIds = $this->request->getPost('invoice_id');
$cancelReason = $this->request->getPost('cancel_reason');
// Perform any validation if needed
// Update the invoice status and cancel reason in the database
$model = new InvoiceModel(); // Assuming you have a model named InvoiceModel
$updated = $model->updateInvoiceCancelStatus($invoiceIds, $cancelReason);
// Prepare the response
$response = [];
if ($updated) {
$response['success'] = true;
$response['message'] = 'Invoice status updated successfully.';
// Redirect to the invoice_list page upon successful cancellation
// return redirect()->to('invoice_list');
} else {
$response['success'] = false;
$response['message'] = 'Failed to update invoice status.';
}
// Return the response as JSON
return $this->response->setJSON($response);
}
## update approval subscription details of the invoice
public function update_approval_subscription()
{
$response = [];
## Declarions
helper(['session', 'financial_year_helper']);
try{
// Initialize models and variables
$model = new InvoiceModel();
$invdate = $this->request->getVar('invoice_date');
$invoice_status = $this->request->getPost('status');
$invoice_id = $this->request->getPost('invoice_id');
$customer_id = (int)$this->request->getPost('customer_name');
$requestData = $this->request->getPost();
$invdate_dbformat = !empty($invdate) ? \DateTime::createFromFormat('d/m/Y', $invdate)->format('Y-m-d') : null;
$invoice_data = [
'invoice_number' => $requestData['invoice_number'],
'invoice_type' => $requestData['invoice_type'],
'customer_id' => $customer_id,
'billing_address_id' => (int)$requestData['billing_address_id'],
'billing_address' => $requestData['billing_address'],
'shipping_address_id' => (int)$requestData['shipping_address_id'],
'shipping_address' => $requestData['shipping_address'],
'notes' => $requestData['notes'],
'invoice_date' => $invdate_dbformat,
'subtotal' => (float)$requestData['sub_total'],
'tax' => (float)$requestData['invoice_tax'],
'dis_type' => isset($requestData['dis_type'])?$requestData['dis_type']:NULL,
'discount' => (float)$requestData['discount'],
'exact_total_amount' => (float)$requestData['exact_total_amount'],
'total_amount' => (int)$requestData['grand_total'],
'payment_note' => $requestData['payment_note'],
'event_id' => (int)$requestData['event_id'],
'business_id' => (int)get_business_id(),
'invoice_id' => $invoice_id,
'updated_by' => (int)get_logged_user_id()
];
$invoice_where = ['customer_id' => $customer_id, 'invoice_id' => $invoice_id];
$invoice_aff_row = $model->updateData('invoice', $invoice_data, $invoice_where);
if ($invoice_aff_row) {
$response['invoice']['message'] = 'Subscription Master (Invoice) Changes Updated successfully';
$this->logger->info("Update Approval Subscription Master (Invoice) has been updated successfully. Updated ID = " . $invoice_id);
} else {
$response['invoice']['message'] = 'Subscription Master (Invoice) There Is No Changes to Updated';
$this->logger->error("Update Approval Subscription Master (Invoice) Err Failed to update ID =" . $invoice_id);
}
## Invoice Line Item..
$invoice_child_id = $requestData['invoice_child_id'];
$count = count($invoice_child_id);
if ($count > 0) {
for ($x = 0; $x < $count; $x++) {
if (!empty($requestData['item_details'][$x])) {
$invoiceitem_arr[$x]['invoice_id'] = $invoice_id;
$invoiceitem_arr[$x]['product'] = (int)$requestData['item_details'][$x];
$invoiceitem_arr[$x]['description'] = $requestData['description'][$x];
$invoiceitem_arr[$x]['quantity'] = (int)$requestData['quantity'][$x];
$invoiceitem_arr[$x]['tax'] = (float)$requestData['tax'][$x];
$invoiceitem_arr[$x]['unit_price'] = (float)$requestData['rate'][$x];
$invoiceitem_arr[$x]['subtotal'] = (float)$requestData['amount'][$x];
$invoiceitem_arr[$x]['discount_amount'] = (float)$requestData['discount_amount'][$x];
$invoiceitem_arr[$x]['discount_type'] = $requestData['discount_type'][$x];
if (!empty($requestData['from_subscription'])) {
$invoiceitem_arr[0]['from_subscription'] = \DateTime::createFromFormat('d/m/Y', $requestData['from_subscription'])->format('Y-m-d');
}
if (!empty($requestData['to_subscription'])) {
$invoiceitem_arr[0]['to_subscription'] = \DateTime::createFromFormat('d/m/Y', $requestData['to_subscription'])->format('Y-m-d');
}
$invoiceitem_arr[$x]['created_by'] = (int)get_logged_user_id();
$invoiceitem_arr[$x]['updated_by'] = (int)get_logged_user_id();
$invoiceitem_arr[$x]['invoice_child_id'] = $invoice_child_id[$x];
}
}
$statement = $model->saveInvoiceItemDetails($invoiceitem_arr);
$response['item']['message'] = 'Subscription Item (Invoice Item)'.implode( ',' , $statement);
$this->logger->error("Update Approval Subscription Child (1st Child) =" .implode( ',' , $statement));
## Subscription..
for ($x = 0; $x < $count; $x++) {
$product_id =(int)$requestData['item_details'][$x];
$from_sub_date = \DateTime::createFromFormat('d/m/Y', $requestData['from_subscription'])->format('Y-m-d');
$to_sub_date = \DateTime::createFromFormat('d/m/Y', $requestData['to_subscription'])->format('Y-m-d');
$subscription_data = [
'customer_id' => $customer_id,
'invoice_id' => $invoice_id,
'scheme_id' => $product_id,
'from_subscription' => $from_sub_date,
'to_subscription' => $to_sub_date,
'business_id' => (int)get_business_id(),
'updated_by' => (int)get_logged_user_id()
];
$subscription_where = [
'customer_id' => $customer_id,
'invoice_id' => $invoice_id,
'isactive' => 1
];
}
$subs_aff_row = $model->updateData('subscription', $subscription_data, $subscription_where);
if ($subs_aff_row) {
$response['subscription']['message'] = 'Subscription has been updated successfully.';
$this->logger->info("Subscription updated successfully. ID = $invoice_id");
} else {
$response['subscription']['message'] = 'Subscription update failed. Please try again.';
$this->logger->error("Failed to update subscription. ID = $invoice_id");
}
}else{
$response['item']['message'] = 'Subscription Item (Invoice Item) There Is No Changes to Updated';
$response['subscription']['message'] = 'Subscription There Is No Changes to Updated';
}
$response['success'] = true;
$response['message'] = "Successfully Updated";
} catch (\Exception $e) {
$response['success'] = false;
$response['message'] = 'Error: ' . $e->getMessage();
$this->logger->error("Error updating subscription: " . $e->getMessage());
}
return $this->response->setJSON($response);
}
public function getActiveMembers(){
$Invoice_Model = new InvoiceModel();
$response['data'] = $Invoice_Model->getActiveMembers();
return $this->response->setJSON($response);
}
public function walkin_customer($id = '0'){
helper('session');
helper('financial_year_helper');
$model = new InvoiceModel();
$where = ['business_id' => (int)get_business_id()];
// Get customer names for the dropdown, events details, and books details
$data['customers'] = $model->getData('customers', $where);
$data['events'] = $model->getData('events', $where);
$data['financial_year'] = get_financial_year();
$data['invoice_number_formatting'] = $model->getData('invoice_number_formatting', $where);
$data['books'] = $model->getCategoryBooks(1); // Invocie type = 2 (invoice)
if ($id === '0') {
$this->logger->info("Book Invoice: In Add Details");
$data['page_name'] = 'Walkin Customers';
$data['invoice_type'] = '1';
$data['invoice_details'] = [];
$data['invoice_item_details'] = [];
} elseif ($id !== '0') {
$data['page_name'] = 'Edit Walkin Customers';
$data['invoice_type'] = '1';
$data['invoice_details'] = $model->where(['invoice_id' => $id, 'isactive' => 1])->first();
$select = ["customer_address_id", "CONCAT(address_1,' ',address_2) as address"];
$where = ['address_type' => 2, 'customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$data['invoice_details']['customer_id']];
$data['customer_shipping_arr'] = $this->get_customer_address($where, $select);
$data['invoice_item_details'] = $this->get_invoice_item($id);
}
$country = new Customer();
$data['country_details'] = $country->get_country_details();
$this->render_page('invoice_form', $data);
}
}