(int)get_business_id()]; $data['Donors'] = $model->getData('donor', $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('donor', $where);
        $data['causes']    = $model->getData('causes', $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';
            $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('donor_id');

            $data = [
                'receipt_number' => $this->request->getPost('receipt_number'),
                'donor_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,
                    '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);}
            
          
        } 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('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 "
...................."; $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) { // Fetch the receipt data based on $receipt_id $model = new InvoiceModel(); $data = $model->getInvoiceData($id); // echo '
';
        // print_r($data);die;

        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isPhpEnabled', true);
        $options->set('isRemoteEnabled', true);
        $options->set('font_subsetting', true);

        $dompdf = new Dompdf($options);

        define("DOMPDF_UNICODE_ENABLED", true);
        $html = view('invoice_pdf_template', ['data' => $data[0]]);

        // echo $html; die;

        $dompdf->loadHtml($html, 'UTF-8');
        $dompdf->setPaper('letter', 'landscape');

        $dompdf->render();

        $output = $dompdf->output();

        $dompdf->stream('document.pdf', ['Attachment' => 1]);

    }


    // 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:

//
  • Approval Date:" . $approval_date . "
  • //
  • Approved By:" . $approved_by . "
  • //
  • Reference ID:" . $reference_number . "
  • //

//

Best regards,

//
    //
  • ".$business_name.",
  • //
  • ".$business_address." ".$business_city." ".$business_state." - ".$business_postal_code."
  • //
  • Call Us: +91 ".$business_mobile_no."
  • //
  • Email Us: ".$business_email."
  • "; // $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); // } // } }