(int)get_business_id()]; $data['Donors'] = $model->getData('customers', $where); $data['page_name'] = 'Receipt Details'; $data['receipt'] = $model->where(["business_id"=>$session_bid])->findAll(); // echo '
';
            // print_r($data); die;

            $this->logger->info("Invoice: Listing Count ." . count($data['receipt']));
            $this->render_page('invoice_list', $data);
        } else {
            return redirect()->to('login');
        }
    }

    ## To Load Invoice ADD/EDIT page...
    public function new_receipt($id = '0')
    {
        helper('session');
        $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['causes']    = $model->getData('causes', $where);
        $data['invoice_number_formatting'] = $model->getData('invoice_number_formatting', $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';
            $data['receipt_details'] = $model->where(['receipt_id' => $id, 'isactive' => 1])->first();
        }

        // echo '
';    
        // print_r($data['invoice_number_formatting']);die;
        $this->render_page('invoice_form', $data);
    }
    

    ## 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('doner_id');

            $data = [
                'receipt_number' => $this->request->getPost('receipt_number'),
                'doner_id' => $customer_id,
                'notes'=>$this->request->getPost('notes'),
                'receipt_date' => (!empty($receipt_date)) ? date("Y-m-d", strtotime($receipt_date)) : NULL,
                'amount' => (int)$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'),
                '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();
                    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 {
                $data['updated_by'] = (int)get_logged_user_id();
                if ($model->update($receipt_id, $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,
                    '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_events);}
            
          
        } catch (\Exception $e) {
            $this->logger->error("Receipt: Err Occur =" . $e->getMessage());
            session()->setFlashdata('error', 'Message: ' . $e->getMessage());
        }
        return redirect()->route('receipt_list');

      
    

    }

    ## 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);
        }
    }

    ## 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 "
...................."; $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'); } ## 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', 'receipt_id' => (int)$id]; $details = $model->where($where)->findAll(); if (empty($details)) { // Array Empty Means allow to Approve. $data = ['status' => 'Approved', 'updated_by' => get_logged_user_id()]; if ($model->update($id, $data)) { $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('receipt_list'); } 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'] = "VBP Approve Information

Dear $recipient_name,

   We are pleased to inform you that your Invoice has been approved.

Details:


Best regards,