donation/app/Controllers/Invoice.php
2024-03-14 07:20:49 +05:30

992 lines
44 KiB
PHP

<?php
namespace App\Controllers;
use App\Models\EventModel;
use App\Models\CustomerModel;
use App\Models\SettingsModel;
use App\Models\InvoiceModel;
use App\Models\BooksModel;
use App\Models\AuditHistoryModel;
use App\Models\UsersModel;
use App\Models\NotificationModel;
use App\Models\BusinessModel;
use App\Helpers\NotificationHelper;
use Mpdf\Mpdf;
use Dompdf\Dompdf;
use Dompdf\Options;
class Invoice extends BaseController
{
public function __construct()
{
$this->AuditHistoryModel = new AuditHistoryModel();
$this->UserModel = new UsersModel();
$this->Business_Model = new BusinessModel();
}
## For Invoice Listing..
public function index()
{
helper('session');
if (is_session_active()) {
$session_role = get_user_role();
$session_bid = get_business_id();
$model = new InvoiceModel();
$where = ['business_id' => (int)get_business_id()];
$data['Donors'] = $model->getData('donor', $where);
$data['page_name'] = 'Receipt Details';
$data['receipt'] = $model->where(["business_id"=>$session_bid])->findAll();
$data['temp_receipt_count'] = $model->where(["business_id"=>$session_bid, 'receipt_header' => 'Temporary Receipt'])->countAllResults();
foreach ($data['receipt'] as $key => $value) {
$data['receipt'][$key]['created_name'] = $this->UserModel->where('user_id', $value['created_by'])->get()->getRow()->first_name;
}
// echo json_encode($data['receipt']);die;
// echo '<pre>';
// print_r($data); die;
$this->logger->info("Invoice: Listing Count ." . count($data['receipt']));
$this->render_page('invoice_list', $data);
} else {
return redirect()->to('login');
}
}
public function donations_accepted()
{
try
{
helper('session');
if (is_session_active()) {
$session_role = get_user_role();
$session_bid = get_business_id();
$model = new InvoiceModel();
// $where = ['business_id' => (int)get_business_id()];
$data['list'] = $model->getData('donations_accepted',null);
$data['page_name'] = 'Donations Accepted';
// print_r($data);die();
$this->render_page('donations_accepted', $data);
} else {
return redirect()->to('login');
}
}
catch (\Throwable $e)
{
$this->logger->error("donations_accepted: Err Occur =" . $e->getMessage());
}
}
public function save_donations_accepted()
{
try
{
helper('session');
// print_r($this->request->getPost());die;
$model = new InvoiceModel();
$list = $model->getData('donations_accepted',null);
foreach ($list as $key => $value) {
if(in_array($value->id, $this->request->getPost('name')))
{
$where = ['id' => $value->id ];
$data['is_active'] = 1;
$upt_data = $model->updateData('donations_accepted', $data, $where);
}
else
{
$where = ['id' => $value->id];
$data['is_active'] = 0;
$upt_data = $model->updateData('donations_accepted', $data, $where);
}
}
session()->setFlashdata('success', 'Data has been added successfully.');
return redirect()->route('donations_accepted');
}
catch (\Throwable $e)
{
$this->logger->error("donations_accepted: Err Occur =" . $e->getMessage());
}
}
## To Load Invoice ADD/EDIT page...
public function new_receipt($id = '0')
{
helper('session');
$model = new InvoiceModel();
$bmodel = new BooksModel();
$setting_model = new SettingsModel();
$where = ['business_id' => (int)get_business_id() ];
$cus_where = ['business_id' => (int)get_business_id() , 'isactive' => 1];
$rec_where = ['business_id' => (int)get_business_id(), 'YEAR(created_on)' => date('Y')];
$receipt = $model->getData('receipt', $rec_where);
// receipt number
$settingData = $setting_model->select('*')->where($where)->findAll();
$count_receipt_no = (count($receipt) > 0) ? count($receipt) + $settingData[0]['start_no'] + 1 : $settingData[0]['start_no'] + 1;
// Calculate padding based on the count of digits in count_receipt_no
$padding_count = max(0, $settingData[0]['left_pad'] - strlen($count_receipt_no));
$padding = str_repeat('0', $padding_count);
$data['count_receipt_no'] = $settingData[0]['prefix_format'] . $padding . $count_receipt_no;
// Get customer names for the dropdown, events details, and books details
$data['currency'] = $setting_model->select('currency')->where($where)->findAll();
$data['customers'] = $model->getData('donor', $cus_where);
$data['causes'] = $bmodel->select('*')->where('business_id', (int)get_business_id())->where('isactive',1)->get()->getResult();
$data['campaign'] = $model->getData('campaign', $where);
$data['invoice_number_formatting'] = $model->getData('settings', $where);
if ($id === '0') {
$this->logger->info("Receipt: In Add Details");
$data['page_name'] = 'Add Receipt Details';
$data['receipt_details'] = [];
} elseif ($id !== '0') {
$this->logger->info(" Book Invoice: In Edit Details ID = " . $id);
$data['page_name'] = 'Edit Receipt Details';
if(get_user_role() == 'accounts')
{
$data['receipt_details'] = $model->where(['receipt_id' => $id])->first();
}
else
{
$data['receipt_details'] = $model->where(['receipt_id' => $id, 'isactive' => 1])->first();
}
}
$this->render_page('invoice_form', $data);
}
public function donor_cash_success()
{
helper('session');
$model = new InvoiceModel();
// echo $this->request->getPost('id');die;
$where = ['business_id' => (int)get_business_id(),'receipt_id' => $this->request->getPost('id') ];
$data['receipt_header'] = 'Receipt';
$data['isactive'] = 1;
$updata = $model->getData('receipt', $where);
$upt_data = $model->updateData('receipt', $data, $where);
//**********AUDIT HISTORY*************/
$myArray = array();
array_push($myArray, $data);
$olddata['receipt_header'] = $updata[0]->receipt_header;
$olddata['isactive'] = $updata[0]->isactive;
$myArray1 = array();
array_push($myArray1, $olddata);
/************************** */
$currentDateTime = date('Y-m-d H:i:s');
$audit_data = [
'module' => 'receipt',
'business_id' => (int)get_business_id(),
'is_edit' => 1,
'old_data' => json_encode($myArray1),
'current_data' => json_encode($myArray),
'updated_on' => $currentDateTime,
'updated_by' => (int)get_logged_user_id()
];
$this->AuditHistoryModel->save($audit_data);
/************************************* */
if($upt_data){ session()->setFlashdata('success', 'Data has been accepted successfully.');echo true; }
else echo false;
}
public function donor_cash_delete()
{
helper('session');
$model = new InvoiceModel();
$where = ['business_id' => (int)get_business_id(),'receipt_id' => $this->request->getPost('id') ];
$data['isactive'] = 0;
$data['receipt_header'] = 'Rejected';
$data['reason'] = $this->request->getPost('reason');
$updata = $model->getData('receipt', $where);
$upt_data = $model->updateData('receipt', $data, $where);
//**********AUDIT HISTORY*************/
/**get old data for history */
$olddata['receipt_number'] = $updata[0]->receipt_number;
$myArray = array();
array_push($myArray, $olddata);
/************************** */
$currentDateTime = date('Y-m-d H:i:s');
$audit_data = [
'module' => 'receipt',
'business_id' => (int)get_business_id(),
'is_delete' => 1,
// 'old_data' => json_encode($myArray1),
'current_data' => json_encode($myArray),
'updated_on' => $currentDateTime,
'updated_by' => (int)get_logged_user_id()
];
$this->AuditHistoryModel->save($audit_data);
/************************************* */
session()->setFlashdata('success', 'Data has been rejected successfully.');
return redirect()->route('receipt_list');
}
## For Ajax Call To Fetch/Retrive All Address Details Based On Customer...
public function load_details1()
{
$id = $this->request->getPost('selectedValue');
$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"];
$where['address_type'] = 2;
$data['customer_shipping'] = $this->get_customer_address($where, $select);
$data['customer_membership'] = $this->get_customer_membership("membership",(int)$id);
return $this->response->setJSON(['data' => $data]);
}
## For Ajax Call To Fetch/Retrive Shipping Address Details Only Based On Customer...
public function load_details2()
{
$customer_id = $this->request->getPost('customerValue');
$address_id = $this->request->getPost('selectedValue');
$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]);
}
// public function generate_serial_no(){}
## 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()
{
$this->logger->info("Invoice: Insert/Update Details");
try {
## Declarions
helper('session');
$model = new InvoiceModel();
$receipt_date = $this->request->getVar('receipt_date');
$receipt_id = (!empty($this->request->getPost('receipt_id'))) ? $this->request->getPost('receipt_id') : "";
$customer_id = (int)$this->request->getPost('donor_id');
$data = [
'receipt_number' => $this->request->getPost('receipt_number'),
'donor_id' => $customer_id,
'campaign_id' => (int)$this->request->getPost('campaign_id'),
'notes'=>$this->request->getPost('notes'),
'receipt_date' => (!empty($receipt_date)) ? date("Y-m-d", strtotime($receipt_date)) : NULL,
'amount' => $this->request->getPost('amount'),
'payment_mode' => $this->request->getPost('payment_mode'),
'payment_ref_no' => $this->request->getPost('payment_ref_no'),
'causes_id' => (int)$this->request->getPost('causes_id'),
'currency' => $this->request->getPost('currency'),
'business_id' => (int)get_business_id(),
'isactive' => 1
];
## Based on the invoice ID, we designated Insert or Update on Details...
if (empty($receipt_id)) {
$data['created_by'] = (int)get_logged_user_id();
if ($model->insert($data, 'invoices')) {
$receipt_id = $model->insertID();
//**********AUDIT HISTORY*************/
$myArray = array();
array_push($myArray, $data);
$currentDateTime = date('Y-m-d H:i:s');
$audit_data = [
'module' => 'receipt',
'business_id' => (int)get_business_id(),
'is_add' => 1,
'current_data' => json_encode($myArray),
'created_by' => (int)get_logged_user_id(),
'updated_on' => $currentDateTime,
'updated_by' => (int)get_logged_user_id()
];
$this->AuditHistoryModel->save($audit_data);
/************************************* */
session()->setFlashdata('success', 'Receipt has been added successfully.');
$this->logger->info("Receipt: has been added successfully. Inserted ID = " . $receipt_id);
} else {
session()->setFlashdata('error', 'Receipt could not be added. Please try again.');
$this->logger->error("Receipt: Err Occur could not be added. Please try again.");
}
} else {
/**get old data for history */
$where = ['business_id' => (int)get_business_id(), 'receipt_id' => $receipt_id];
$olddata = $model->getData('receipt', $where);
/************************** */
$data['updated_by'] = (int)get_logged_user_id();
if ($model->update($receipt_id, $data)) {
$newdata = $model->getData('receipt', $where);
//**********AUDIT HISTORY***********/
$currentDateTime = date('Y-m-d H:i:s');
$audit_data = [
'module' => 'receipt',
'business_id' => (int)get_business_id(),
'is_edit' => 1,
'old_data' => json_encode($olddata),
'current_data' => json_encode($newdata),
'updated_on' => $currentDateTime,
'updated_by' => (int)get_logged_user_id()
];
$this->AuditHistoryModel->save($audit_data);
/************************************* */
session()->setFlashdata('success', 'Receipt has been updated successfully.');
$this->logger->info("Receipt: has been updated successfully. Updated ID = " . $receipt_id);
} else {
session()->setFlashdata('error', 'Receipt update failed. Please try again.');
$this->logger->error("Receipt: Err Failed to update ID =" . $receipt_id);
}
}
if($this->request->getPost('next_id')){
## Array Formation For Events Details And Updating Events also Here..
$update_events = [
// 'id' => 1,
'start_no' => (int)$this->request->getPost('next_id'),
'business_id' => (int)get_business_id(),
'updated_by' => get_logged_user_id()
];
// print_r($update_events);
$this->update_number_formatting($update_events);}
// get donor whatsapp no and mail
$where = ['donor_id' => (int)$this->request->getPost('donor_id') ,'business_id' => (int)get_business_id()];
$donordata = $model->getData('donor', $where);
// generate recipt
$html = $this->generate_invoice_pdf($receipt_id, 'mail');
// echo $html;die;
// send mail
$notification = new NotificationHelper();
if($donordata[0]->email != null || $donordata[0]->email != '')
{
$records['recipient_email'] = $donordata[0]->email;
$records['subject'] = 'DONOR RECEIPT';
$records['description'] = $html;
$notification->sendEmail($records);
}
$notificationModel = new NotificationModel();
$bmodel = new BooksModel();
$donormodel = new CustomerModel();
$template_data = $notificationModel->select('*')->where('template_id',7)->findAll();
$cause = $bmodel->select('name')->where('causes_id',(int)$this->request->getPost('causes_id'))->findAll();
$d_name = $donormodel->select('first_name')->where('donor_id',$customer_id)->findAll();
$business = $this->Business_Model->select('*')->where('business_id',(int)get_business_id())->findAll();
$donor_name = $d_name[0]['first_name'];
$currency_amount = $this->request->getPost('amount');
$cause_name = $cause[0]['name'];
$receipt_number = $this->request->getPost('receipt_number');
$r_date = (!empty($receipt_date)) ? date("d-m-Y", strtotime($receipt_date)) : NULL;
$business_name = $business[0]['title'];
// Your original message
$message = $template_data[0]['message'];
// Replace placeholders with actual values
$message = str_replace(
array('{donor_name}', '{currency_amount}', '{cause_name}', '{receipt_name}', '{receipt_date}', '{bisuness_name}'),
array($donor_name, $currency_amount, $cause_name, $receipt_number, $receipt_date, $business_name),
$message
);
// Output the modified message
// echo $message;die;
// // WHATSAPP
$params = (object) Null;
// $params->number = (int)'91' . $donordata[0]->mobile_no;
$params->number = (int)'919677462018';
$params->type = "text";
$params->message = $message;
$params->instance_id = '65C9B978325A2';
$params->access_token = '65c715e797d16';
$whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
} catch (\Exception $e) {
$this->logger->error("Receipt: Err Occur =" . $e->getMessage());
session()->setFlashdata('error', 'Message: ' . $e->getMessage());
}
$success = true;
// Your existing code...
$invoice_id = $receipt_id; // Replace with the actual invoice_id
// Pass the invoice_id and success variable to the view
return $this->response->setJSON(['success' => true, 'invoice_id' => $invoice_id]);
// Load the view with the success variable
// return view('invoice_modal', ['success' => $success]);
// $this->load->view('invoice_modal', array('success' => $success));
return redirect()->route('receipt_list');
}
public function audit_history()
{
helper('session');
$model = new InvoiceModel();
$usermodel = new UsersModel();
$where = ['business_id' => (int)get_business_id()];
$data = $model->getData('audit_history', $where);
// echo $data[0]->current_data;die;
$diff = [];
foreach ($data as $audit_data) {
$arr1 = json_decode($audit_data->current_data, true);
$arr2 = json_decode($audit_data->old_data, true);
$temp_diff = [];
// Check each key-value pair in arr1
foreach ($arr1[0] as $key => $value) {
$con = $key != 'created_on' && $key != 'created_by' && $key != 'updated_on' && $key != 'updated_by';
if ($audit_data->is_edit == 1 && $arr2[0][$key] !== $value) {
$user = $usermodel->select('first_name,last_name')->where('user_id',$audit_data->updated_by)->findAll();
if($con){
$temp_diff[] = (object) [
'id' => $audit_data->id,
'key' => $key,
'old_value' => $value,
'new_value' => $arr2[0][$key],
'module' => $audit_data->module,
'mode' => 'Update',
'updated_by' => $user[0]['first_name'].' '.$user[0]['last_name'],
'updated_on' => $audit_data->updated_on
];
}
}
else if($con && $audit_data->is_add == 1){
// echo $key;die;
$user = $usermodel->select('first_name,last_name')->where('user_id',$audit_data->created_by)->findAll();
$temp_diff[] = (object) [
'id' => $audit_data->id,
'key' => '-',
'old_value' => '-',
'new_value' => 'New Receipt No "'.$arr1[0]['receipt_number'].'" Created',
'module' => $audit_data->module,
'mode' => 'Create',
'updated_by' => $user[0]['first_name'].' '.$user[0]['last_name'],
'updated_on' => $audit_data->created_on
];
break;
}
else if($con && $audit_data->is_delete == 1){
// echo $key;die;
$user = $usermodel->select('first_name,last_name')->where('user_id',$audit_data->updated_by)->findAll();
$temp_diff[] = (object) [
'id' => $audit_data->id,
'key' => '-',
'old_value' => '-',
'new_value' => 'Receipt No "'.$arr1[0]['receipt_number'].'" Deleted',
'module' => $audit_data->module,
'mode' => 'Delete',
'updated_by' => $user[0]['first_name'].' '.$user[0]['last_name'],
'updated_on' => $audit_data->created_on
];
break;
}
}
// Add temp_diff to $diff array if it's not empty
if (!empty($temp_diff)) {
$diff[] = $temp_diff;
}
}
// print_r($diff);
$response['page_name'] = 'History';
$response['data'] = $diff;
$this->render_page('audit_history', $response);
}
## 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('settings');
$where = ['isactive' => 1, 'business_id' => (int)$update_events['business_id'], 'start_no' => $update_events['start_no']];
$details = $model->where($where)->findAll();
if (empty($details)) {
$update_where = ['business_id' => (int)$update_events['business_id']];
$update_data = ['start_no' => $update_events['start_no'], 'updated_by' => $update_events['updated_by']];
$model->updateData('settings', $update_data, $update_where);
}
}
## 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, 'receipt_id' => (int)$id];
$model->inactiveMissingInvoiceItemDetails($where, $missingValues);
}
}
}
// echo "<br/>....................";
$count = count($itemid);
$invoiceitem_arr = [];
if ($count > 0) {
for ($x = 0; $x < $count; $x++) {
if(!empty($requestData['item_details'][$x])){
$invoiceitem_arr[$x]['receipt_id'] = $id;
$invoiceitem_arr[$x]['product'] = (int)$requestData['item_details'][$x];
$invoiceitem_arr[$x]['quantity'] = (int)$requestData['quantity'][$x];
$invoiceitem_arr[$x]['tax'] = (int)$requestData['tax'][$x];
$invoiceitem_arr[$x]['unit_price'] = (int)$requestData['rate'][$x];
$invoiceitem_arr[$x]['subtotal'] = (int)$requestData['amount'][$x];
$invoiceitem_arr[$x]['discount_amount'] = (int)$requestData['discount_amount'][$x];
$invoiceitem_arr[$x]['discount_type'] =$requestData['discount_type'][$x];
if (!empty($requestData['from_subscription'])) {
$invoiceitem_arr[0]['from_subscription'] = $requestData['from_subscription'];
}
if (!empty($requestData['to_subscription'])) {
$invoiceitem_arr[0]['to_subscription'] = $requestData['to_subscription'];
}
$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];
}
}
$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, 'receipt_id' => (int)$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(), 'receipt_id' => (int)$id];
$existed = $model->where($where)->findAll();
$this->logger->Info("Invoice : Going to Inactive ID = " . $id);
if ($existed) {
$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);
} 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 = ['receipt_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('receipt_list');
}
public function generate_invoice_pdf($id, $dest = null)
{
try {
// Fetch the receipt data based on $receipt_id
$model = new InvoiceModel();
$usermodel = new UsersModel();
$setting_model = new SettingsModel();
$business_model = new BusinessModel();
$where = ['business_id' => (int)get_business_id()];
$currency_data = $setting_model->select('currency')->where($where)->findAll();
$terms_data = $business_model->select('terms,signature')->where($where)->findAll();
$data = $model->getInvoiceData($id);
// Check if data is empty
if (!$data || !$currency_data) {
throw new Exception('Data not found or empty');
}
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isPhpEnabled', true);
$options->set('isRemoteEnabled', true);
$options->set('font_subsetting', true);
$options->set('tempDir', sys_get_temp_dir());
$options->set('defaultFont', 'DejaVuSans');
$options->set('chroot', base_url()."public/uploads");
$dompdf = new Dompdf($options);
define("DOMPDF_UNICODE_ENABLED", true);
$user = $usermodel->select('first_name')->where('user_id',$data[0]->created_by)->findAll();
$logoPath = base_url()."public/uploads/".$data[0]->business_logo;
if ($data[0]->business_logo && file_exists($logoPath)) {
$baseurl = $logoPath;
} else {
// Logo does not exist, handle this case accordingly
$baseurl = base_url()."public/uploads/default.png";
}
$html = view('invoice_pdf_template', [
'data' => $data[0],
'currency' => $data[0]->currency,
'currency_in_words' => $this->convertNumberToWords($data[0]->amount) ,
'baseurl' => $baseurl,
'signature' => $terms_data[0]['signature'],
'staff_name' => $user[0]['first_name'],
'Notes' => $terms_data[0]['terms']
]);
// echo $html;die;
$dompdf->loadHtml($html);
$dompdf->setPaper('letter', 'landscape');
$dompdf->render();
if($dest == 'mail') {
// Generate filename based on current date and time
// $filename = date('dmYHis') . '.pdf';
// // Save PDF file to a directory
// $outputFilePath = base_url() . 'pdf/' . $filename; // Assuming WRITEPATH is defined
// file_put_contents($outputFilePath, $dompdf->output());
// // Provide download link with the generated filename
// $downloadLink = base_url() . 'pdf/' . $filename;
// echo $downloadLink;die;
return $html;
}
$dompdf->stream('Receipt.pdf', ['Attachment' => 1]);
} catch (Exception $e) {
// Handle the exception
// For example, log the error, display a user-friendly message, or return an error response
echo 'Error: ' . $e->getMessage();
}
}
public function convertNumberToWords($number) {
$words = array(
0 => 'Zero',
1 => 'One',
2 => 'Two',
3 => 'Three',
4 => 'Four',
5 => 'Five',
6 => 'Six',
7 => 'Seven',
8 => 'Eight',
9 => 'Nine',
10 => 'Ten',
11 => 'Eleven',
12 => 'Twelve',
13 => 'Thirteen',
14 => 'Fourteen',
15 => 'Fifteen',
16 => 'Sixteen',
17 => 'Seventeen',
18 => 'Eighteen',
19 => 'Nineteen',
20 => 'Twenty',
30 => 'Thirty',
40 => 'Forty',
50 => 'Fifty',
60 => 'Sixty',
70 => 'Seventy',
80 => 'Eighty',
90 => 'Ninety'
);
// Special case for zero
if ($number == 0) {
return $words[0];
}
$num = (int)$number;
$result = '';
// Handle numbers greater than 1000
if ($num >= 1000) {
$thousands = floor($num / 1000);
$result .= $words[$thousands] . ' Thousand ';
$num %= 1000;
}
// Handle numbers between 100 and 999
if ($num >= 100) {
$hundreds = floor($num / 100);
$result .= $words[$hundreds] . ' Hundred ';
$num %= 100;
}
// Handle numbers between 20 and 99
if ($num >= 20) {
$tens = floor($num / 10) * 10;
$result .= $words[$tens] . ' ';
$num %= 10;
}
// Handle numbers between 1 and 19
if ($num > 0) {
$result .= $words[$num];
}
return $result;
}
// public function approve_notifications($receipt_id)
// {
// $model = new InvoiceModel();
// $where = ['I.business_id' => (int)get_business_id(), 'I.receipt_id' => $receipt_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)) {
// $this->logger->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['updated_on'];
// $approved_by = $rec['updated_by_name'];
// $recipient_email = $rec['customer_email'];
// $recipient_mobile = $rec['customer_mobile'];
// $subtotal = $rec['subtotal'];
// $tax = $rec['tax'];
// $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'];
// }
// $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 : "sanjeev.p@venbainfotech.com";
// $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'];
// $records['subject'] = $invoice_serial_number . " - Approval Notification";
// $records['description'] = "<html><head><title>VBP Approve Information</title></head><body>
// <p>Dear $recipient_name,</p>
// <p> &ensp;&ensp; We are pleased to inform you that your Invoice has been approved.</p>
// <p><strong>Details:</strong></p>
// <ul><li>Approval Date:" . $approval_date . "</li>
// <li>Approved By:" . $approved_by . "</li>
// <li>Reference ID:" . $reference_number . "</li>
// </ul><br>
// <p>Best regards,</p>
// <ul style='list-style: none;'>
// <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></body></html>";
// $template = "Dear " . $recipient_name . ",\r\r\n\nYour Invoice has been approved.\n\nDetails:\r\n- Approval Date: " . $approval_date . "\r\n- Approved By: " . $approved_by . "\r\n- Reference ID: " . $reference_number . "\r\n\nBest regards,\n".$business_name.",\n".$business_address." ".$business_city." ".$business_state." - ".$business_postal_code.".\nCall Us: +91 ".$business_mobile_no."\nEmail Us:".$business_email;
// $params = (object) Null;
// $params->number = (int)'91' . $recipient_mobile;
// $params->type = "text";
// $params->message = $template;
// $params->instance_id = WAAI_INSTANCE;
// $params->access_token = WAAI_TOKEN;
// $this->logger->info("receipt: approve notification Email Request data = ".json_encode($records));
// $email_result = $notification->sendEmail($records);
// $this->logger->info("receipt: approve notification Email Response = " . json_encode($email_result));
// $this->logger->info("receipt: approve notification Whatsapp Request data = ".json_encode($params));
// $whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
// $this->logger->info("receipt: approve notification Whatsapp Response = " . json_encode($whatsapp_result));
// }
// public function general_inv_rp()
// {
// if($this->request->getmethod() == 'get')
// {
// $model = new InvoiceModel();
// $data['report_data'] = $model->get_general_invoice_data();
// $this->logger->info("Invoice Report ");
// $data['page_name'] = 'General Invoice Report';
// $this->render_page('report_general_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_general_invoice_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') );
// $this->logger->info("Invoice Report ");
// $data['page_name'] = 'General Invoice Report';
// $data['selected_data'] = $this->request->getVar('date');
// $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 itemwise_report()
// {
// if($this->request->getmethod() == 'get')
// {
// $model = new InvoiceModel();
// $data['report_data'] = $model->itemwise_report_data();
// $this->logger->info("Itemwise Report ");
// $data['page_name'] = 'Itemwise Report';
// $this->render_page('report_itemwise', $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->itemwise_report_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') );
// $this->logger->info("Itemwise Report ");
// $data['page_name'] = 'Itemwise Report';
// $data['selected_data'] = $this->request->getVar('date');
// $this->render_page('report_itemwise', $data);
// }
// }
}