<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Invoice_controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        // Your own constructor code
        $this->load->model('invoice_model');
        $this->load->model('visits_model');
        $this->load->model('order_model');
        $this->load->model('business_model');
        $this->load->model('customer_model');
        $this->load->model('colors_model');
        $this->load->model('product_model');
        $this->load->model('sms_model');
        $this->load->model('accounting_model');
        $this->load->model('imsfiscal_model');
        
        if($this->session->userdata('role')==''){
            redirect('logout');
        }
    }
    
    function nice_print_r($array){
        echo "<pre>";
        print_r($array);
        echo "</pre>";
    }
    
    function get_package_invoices(){
        $data = $this->invoice_model->getPackageInvoices();
        echo json_encode($data);
    }
    
    function package_invoices_list(){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            checkroles(1,0,1);

            if(isset($_POST['invoice_ids'])){
                foreach ($_POST['invoice_ids'] as $row){
                    echo $row."---";
                }
                exit;
                //print_r($_POST['invoice_ids']); exit;
            }

            $data['nav'] = 'invoice';
            $data['subnav'] = 'package_invoices';

            $data['packages'] = $this->invoice_model->getPackageTypes();

            $data['logout']='No';
            
            $this->load->view('includes/header', $data);
            $this->load->view('package_invoice_list');
            $this->load->view('includes/footer');
        }
        
    }   
    
    function open_package_invoice(){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            checkroles(1,0,1);

            $data['nav'] = 'invoice';
            $data['subnav'] = 'package_invoices';
            $data['menu'] = 'hidden';

            if(isset($_POST['invoice_ids'])){

                $invoice_ids = $this->input->post('invoice_ids', TRUE);

                $data['invoice'] = $this->invoice_model->getpackageinvoicebyids($invoice_ids);

                $data['invoicedetails'] = $this->invoice_model->getpackageinvoicedetails($invoice_ids);
                //$this->nice_print_r($data['invoicedetails']); exit;
                $data['business']=$this->business_model->getbusinessdetails();

                $data['logout']='No';
                
                $this->load->view('includes/header', $data);
                $this->load->view('package_invoice_view');
                $this->load->view('includes/footer');

            } else{

                echo 'Please select one ore more invoices.';

            }
        }
    } 
    
    function mark_bad_debts(){
        
        $result = $this->invoice_model->markBadDebts();
        if($result){
            echo "success";
        }
        
    }
    
    function updateCashRegister(){
        $today = date('Y-m-d');        
        
        $result = $this->invoice_model->get_cash_register();
       
        if($this->session->userdata('role')=='Super User'){
            if($result){
                $update = $this->invoice_model->update_previous_register();
                if($update){
                    echo 'success'; exit;
                } else{
                    echo 'error'; exit;
                }
            } else {
                $insert = $this->invoice_model->insert_cash_register();
                if($insert){
                    echo 'success'; exit;
                } else{
                    echo 'error'; exit;
                }
            }
        } else if($result && $today != $this->input->post('calendar_date', TRUE) && $this->session->userdata('role')!=='Admin'){
            //don't update previous days!!! 
            //$update = $this->invoice_model->update_cash_register();
            //if($update){
            //    echo 'success'; exit;
            //} else{
                echo 'error'; exit;
            //}
        } else if($result && $today == $this->input->post('calendar_date', TRUE)){
            $update = $this->invoice_model->update_cash_register();
            if($update){
                echo 'success'; exit;
            } else{
                echo 'error'; exit;
            }
        } else if($result && $this->session->userdata('role')=='Admin'){
            $update = $this->invoice_model->update_cash_register();
            if($update){
                echo 'success'; exit;
            } else{
                echo 'error'; exit;
            }
        } else{
            $insert = $this->invoice_model->insert_cash_register();
            if($insert){
                echo 'success'; exit;
            } else{
                echo 'error'; exit;
            }
        }
        
    }
    
    function open_cash_register($date){
        
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['menu'] = 'hidden';
            $data['date'] = $date;

            $data['business']=$this->business_model->getbusinessdetails();


            $data['nodatatable']='nodatatable';
            $data['logout']='No';
            
            $this->load->view('includes/header', $data);
            $this->load->view('cashregister_view');
            $this->load->view('includes/footer');
        }
    }
    
    function getTodayCashInfo(){
        $today=$this->input->post('calendar_date', TRUE);
        $show_previous = $this->input->post('show_previous', TRUE);
        
        if($this->session->userdata('role')== "Reception" && $show_previous=="N" && $today !== date('Y-m-d')){
            echo json_encode("Not Allowed");
            return;
        }
        
        $data['invoice'] = $this->invoice_model->get_today_cash_info();
        $data['till'] = $this->invoice_model->get_yesterday_till_amount($today);
        $data['cash_register'] = $this->invoice_model->get_cash_register();
        $data['today_expenses'] = $this->invoice_model->get_today_expenses();
        $data['voucher'] = $this->invoice_model->get_cash_voucher();
        
        //print_r($data['voucher']); exit;
        
        $date = $this->input->post('calendar_date', TRUE);
        
        $data['today'] = 'no';
        
        if($date === date('Y-m-d')){
            $data['today'] = 'yes';
        }
        
        echo json_encode($data);
        
    }
    
    function open_recovery_invoice($invoiceid, $visitid){
       
        $data['nodatatable']='nodatatable';
        //storemanager,hr,reception...user serial
        checkroles(1,0,1);
        
        if(null == $invoiceid || $invoiceid==''){
            echo 'Invoice ID not received, Try Again!';
            exit();
        }
        
        $check_invoice = $this->invoice_model->check_invoice_recoverable($invoiceid);
        
        if($check_invoice->is_recovery === 'No'){
            redirect(base_url('existinginvoice/'.$invoiceid));
        }
        
        $data['nav'] = 'invoice';
        $data['subnav'] = 'recoveryinvoices';
        $data['menu'] = 'hidden';
        
        //Get the visit
        $data['visit']=$this->visits_model->getinvoicedvisitbyid($visitid);
        $data['visitid']=$visitid;
        //$this->nice_print_r($data['visit']); exit;
        
//        $ids=[]; 
//        foreach($data['visit'] as $service){
//            array_push($ids, $service['service_id']);            
//        }
        
        //Get all services
        $data['services']=$this->visits_model->getvisitservices($visitid);
        
        //Get next invoive number
        $data['invoiceno']=$this->invoice_model->getnextinvoicenumber();
        
        $data['customer'] = $this->customer_model->get_byid($check_invoice->customer_id);
        
        $data['business']=$this->business_model->getbusinessdetails();
        $data['taxes']=$this->business_model->getbusinesstaxes('service');
        
        // get invoice details
        $data['invoice']=$this->invoice_model->getinvoicebyid($invoiceid);
        $data['invoicedetails']=$this->invoice_model->getinvoicedetails($invoiceid);
        $data['invoicestaff']=$this->invoice_model->getinvoicestaff($invoiceid);
        $data['alreadypaid']=$this->invoice_model->alreadypaidinvoice($visitid);
        
//        $this->nice_print_r($data['invoice']); exit;
        
        $this->load->view('includes/header', $data);
        $this->load->view('invoice_recovery_view');
        $this->load->view('includes/footer');
    }
    
    function open_recovery_order_invoice($invoiceid, $orderid){
        $data['nodatatable']='nodatatable';
         //storemanager,hr,reception...user serial
        checkroles(1,0,1);
        
        
        if(null == $invoiceid || $invoiceid==''){
            echo 'Invoice ID not available, Try again!';
            exit();
        }
        
        $check_invoice = $this->invoice_model->check_invoice_recoverable($invoiceid);
        
        if($check_invoice->is_recovery === 'No'){
            redirect(base_url('existingorderinvoice/'.$invoiceid));
        }
        
        $data['nav'] = 'invoice';
        $data['subnav'] = 'recoveryinvoices';
        
        //$data['order'] = $this->order_model->getinvoicedorderbyid($orderid);
        
        //$ids=[];
        //foreach($data['order'] as $product){
        //    array_push($ids, $product['product_id']);
        //}

        //Get all products
        //$data['products']=$this->order_model->getorderproducts($ids, $orderid);

        //Get next invoice number
        $data['invoiceno']=$this->invoice_model->getnextinvoicenumber();

        $data['business']=$this->business_model->getbusinessdetails();
        $data['taxes']=$this->business_model->getbusinesstaxes('sale');
        
        // get invoice details
        $data['invoice']=$this->invoice_model->getinvoicebyid($invoiceid);
        $data['products']=$this->invoice_model->getinvoiceproducts($invoiceid);
        
        $data['menu'] = 'hidden';

        $this->load->view('includes/header', $data);
        $this->load->view('order_invoice_recovery_view');
        $this->load->view('includes/footer');
    }

    function open_new_invoice(){
        $data['nodatatable']='nodatatable';
       
        $data['nav'] = 'invoice';
        
        $visitid=$this->input->post('visit-id', TRUE);
        
        if(null!==$visitid && $visitid!==''){
            //Get the visit
            $data['visit']=$this->visits_model->getopenvisitbyid($visitid);
        }else{
            
             echo 'Visit ID not found';
             exit();
            
        }
        
        if($data['visit']){
            
            $data['staffs']=$this->visits_model->getvisitstaffs($visitid);
            $data['products']=$this->visits_model->getvisitserviceproducts($visitid);
                        
            $data['color_record'] = $this->colors_model->get_color_record($visitid);
            
            if(count($data['color_record']) > 0){
                $data['color_record'] = FALSE;
            } else{
                $data['color_record'] = TRUE;
            }
        
            $data['facial_record'] = $this->colors_model->get_facial_records($visitid);
            
            if(count($data['facial_record']) > 0){
                $data['facial_record'] = FALSE;
            } else{
                $data['facial_record'] = TRUE;
            }
            $this->load->model('eyelashes_model');
            $data['eyelashes_record'] = $this->eyelashes_model->get_eyelashes_records($visitid);
            
            if(count($data['eyelashes_record']) > 0){
                $data['eyelashes_record'] = FALSE;
            } else{
                $data['eyelashes_record'] = TRUE;
            }
            
            
            //$this->nice_print_r($data['visit']); 
            $data['customer'] = $this->customer_model->get_byid($data['visit'][0]['customer_id']);
            $data['customer_points'] = $this->customer_model->get_customer_loyalty($data['visit'][0]['customer_id']);
            
            $data['balance'] = $this->customer_model->customerbalance($data['visit'][0]['customer_id']);
            $data['advances'] = $this->visits_model->getopenvisitadvancesumbyid($visitid);
            $data['advance_comments'] = $this->visits_model->getopenvisitadvancecommentsbyid($visitid);
            
            //Get all services
            $data['services']=$this->visits_model->getvisitservices($visitid);

            if($data['services'][0]['loyalty_service']==="Y"){
                $this->load->model('service_model');
                $data['loyalty_service']= $this->service_model->get_loyalty_rate($data['services'][0]['id_business_services']);               
            }
            
            //Get next invoive number
            $data['invoiceno']=$this->invoice_model->getnextinvoicenumber();

            $data['business']=$this->business_model->getbusinessdetails();
            $data['taxes']=$this->business_model->getbusinesstaxes('service');

            $data['menu'] = 'hidden';
            
            $data['color_type_list'] = $this->colors_model->color_type_list();
            $data['color_numbers'] = $this->colors_model->get_all_color_number();
            $data['eyelashtypes'] = $this->eyelashes_model->eyelash_type_list();
            $data['WaterContent'] = $this->colors_model->get_WaterContent();
           
            $data['discount_types'] = $this->invoice_model->get_discounttypes();
            
            $data['discount_pw']=$this->invoice_model->get_discount_user_pw();
            
            $this->load->view('includes/header', $data);
            $this->load->view('invoice_view');
            $this->load->view('includes/footer');
            
        } else{
            echo 'Invoice already generated for this Visit';
        }
    }

    function openinvoice($invoiceid){
        //$invoiceid=$this->input->post('invoiceid');
        $data['nodatatable']='nodatatable';
        
        $data['nav'] = 'invoice';
        $data['subnav'] = 'todayinvoices';
        
        $data['menu'] = 'hidden';
       
        if(null !== $invoiceid && $invoiceid !== ''){
            //Get the invoice and pass as visit
            $data['invoice']=$this->invoice_model->getinvoicebyid($invoiceid);
        } else {
            echo 'Invoice ID not received, Try Again!';
            exit();
        }
        //print_r($data['invoice']); exit;
        
        if($data['invoice'][0]['reference_invoice_number'] !== ''){
            $invoiceno = $data['invoice'][0]['reference_invoice_number'];
            $invoice=$this->invoice_model->getinvoicebyno($invoiceno);
            $invoiceid = $invoice[0]['id_invoice'];
        }
        
        //Get all details and pass as services
        $data['invoicedetails']=$this->invoice_model->getinvoicedetails($invoiceid);
        $data['invoicestaff']=$this->invoice_model->getinvoicestaff($invoiceid);
               
        $data['business']=$this->business_model->getbusinessdetails();
        $data['taxes']=$this->invoice_model->getinvocietaxes($invoiceid);
        $data['logout']='No';
        
        $this->load->view('includes/header', $data);
        $this->load->view('exist_invoice_view');
        $this->load->view('includes/footer');
        
    }
    
    function openinvoiceemailtemplate($invoiceid){
        //$invoiceid=$this->input->post('invoiceid');
        $data['nodatatable']='nodatatable';
        
        $data['nav'] = 'invoice';
        $data['subnav'] = 'todayinvoices';
        
        $data['menu'] = 'hidden';
       
        //Get the invoice and pass as visit
        $data['invoice']=$this->invoice_model->getinvoicebyid($invoiceid);
        
        //print_r($data['invoice']); exit;
        
        if($data['invoice'][0]['reference_invoice_number'] !== ''){
            $invoiceno = $data['invoice'][0]['reference_invoice_number'];
            $invoice=$this->invoice_model->getinvoicebyno($invoiceno);
            $invoiceid = $invoice[0]['id_invoice'];
        }
        
        //Get all details and pass as services
        $data['invoicedetails']=$this->invoice_model->getinvoicedetails($invoiceid);
        
               
        $data['business']=$this->business_model->getbusinessdetails();
        $data['taxes']=$this->invoice_model->getinvocietaxes($invoiceid);
        
        $data['logout']='No';
        //$this->load->view('includes/header', $data);
        $this->load->view('exist_invoice_email_template', $data);
        //$this->load->view('includes/footer');
        
    }
    
    function updaterecoveryinvoice(){
        $result = $this->invoice_model->update_recovery_invoice();
        echo "success|".$result;
    }
    
    function updaterecoveryorderinvoice(){
        $result = $this->invoice_model->update_recovery_order_invoice();
        echo "success|".$result;
    }
    
    function updateinvoice(){
       
       if(null == $this->input->post('customerid') || $this->input->post('customerid')==0){
            echo 'error|Customer ID Not Received. Session may have expired. Try Again!';
            exit();
       }       
        
       $customer_phone = $this->input->post('customercell');
       
       //verify retained_amount_usage
       $verification = $this->customer_model->get_customer_loyalty($this->input->post('customerid'));
       
       $this->load->model('scheduled_tasks_model');
       $loyalty_text = $this->scheduled_tasks_model->get_loyalty_text();
       
       if(sizeof($verification)>0){
            
            if((float)$verification[0]['retained'] < ((float)$this->input->post('retained_amount_used') + (float)$this->input->post('remaining_retained'))){
                echo 'error|Another Invoice used the customer advance. Refresh Page!';
                exit();
            }
            $lused = (float)$this->input->post('loyaltyused');
            $lavailable = (float)$verification[0]['loyalty_points'];
            if($lavailable < ($lused-0.01)){
                echo 'error|Loyalty points being used '.$lused.' cannot be more then Remianing Points ('.$lavailable.'). Refresh Page!';
                exit();
            }   
       }
        
       $receipturl="";

       $invoice=$this->invoice_model->update_invoice();
       $this->session->unset_userdata('discount_session');
      
       $invoiceid= explode("|", $invoice);
        
        $business=$this->business_model->getbusinessdetails();
       
        $verification = $this->customer_model->get_customer_loyalty($this->input->post('customerid'));
        
        $receipts_intsalled = false;
        if(isset($business[0]['receipts_installed'])){ if($business[0]['receipts_installed']=='Yes'){ $receipts_intsalled = true; } }

        if($business[0]['loyalty_sms']=='Yes' && sizeof($verification)>0 && strlen($customer_phone)==11){
            //echo 'sms enabled';
            if($receipts_intsalled==FALSE){
                $newloyaltypoints = $verification[0]['loyalty_points'];
                $customername= $verification[0]['customer_name'];
                $customername = substr($customername, 0, strrpos($customername, " ")); 
                
                if($business[0]['business_name']=='mks'){
                    $msg='Thank u for your business of '.CURRENCY_CODE.'. '. $invoiceid[3].' at '.$business[0]['business_name'].'\n';
                    
                }else{
                    $msg='Hi '.$customername.',\nThank you for visiting '.$business[0]['business_name'].'.\n';
                    if($business[0]['loyalty_enable']=='Y'){
                        if((Int)$invoiceid[0]>0 && (Int)$invoiceid[1]>0  && $business[0]['show_points']=='Yes'){
                        //$newloyaltypoints =  (float)$newloyaltypoints+(float)$invoiceid[1];
                        $msg=$msg.'Points earned today '. round($invoiceid[1]) .'.\nTotal points '. round($newloyaltypoints).'.\n';
                        } 
                        if((Int)$invoiceid[0]>0 && (Int)$invoiceid[2]>0  && $business[0]['show_amount']=='Yes'){
                            //$newloyaltypoints =  (float)$newloyaltypoints+(float)$invoiceid[1];
                            $msg=$msg.'Bill '. $invoiceid[2].".\n";
                            $msg=$msg.'Paid '. $invoiceid[3].".\n";
                            if((int)$invoiceid[4]>0){
                                    $msg=$msg.'Balance '. $invoiceid[4].".\n";
                            }
                        }  
                    }
                }
                if($loyalty_text!==null && $loyalty_text!==''){
                    $msg=$msg.$loyalty_text->msg;
                }
                $msg = iconv('ISO-8859-1', 'UTF-8', $msg);
                $sendsms = $this->sms_model->send_sms(trim($msg), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business'], $invoiceid[0]); 
            } else { //get a mexyon receipts url
               // echo 'Sending Receipt Curl Data';
                $newloyaltypoints = $verification[0]['loyalty_points'];
                //$newloyaltypoints =  round((float)$newloyaltypoints + (float)$invoiceid[1]);
                $customername= $verification[0]['customer_name'];
                //$customername = substr($customername, 0, strrpos($customername, " ")); 
                $cn = explode(" ",$customername);
                
                $receipturl = $this->sms_model->send_sms($newloyaltypoints, $customer_phone, false, 'ReceiptsSMS', false, $business[0]['id_business'], $invoiceid[0]); 
                
                if($this->db->table_exists('wa_msg_list')){

                } else {
                    if( substr($receipturl, 0, 5) == 'https'){
                        $msg='Hi '.$cn[0].',\nClick to view your '.$business[0]['business_name'].' receipt\n';
                        $msg.=trim($receipturl);
                        $sendsms = $this->sms_model->send_sms(trim($msg), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business'], $invoiceid[0]); 
                    }else{
                        echo $receipturl;
                    }
                }
            }
        } 
        
        
        if($business[0]['admin_notifications']==='Yes' && (Int)$invoiceid[0] > 0){
            $admins = $this->business_model->get_business_admins();

            $thisInvoice = $this->invoice_model->getinvoicebyid($invoiceid[0]);
           
           // if((int)$thisInvoice[0]['cctip'] >0 || (int)$thisInvoice[0]['loyalty_used'] >0){
                $msg=$business[0]['business_name'];
                $msg=$msg.'\nInvoice#: '.$thisInvoice[0]['id_invoice'].'\nTime: '.$thisInvoice[0]['invoice_date'].'\nCustomer: '.$thisInvoice[0]['customer_name'];
                $msg=$msg.'\n Payable: '.number_format($thisInvoice[0]['net_amount']);
                if($thisInvoice[0]['payment_mode']=='Cash'){$msg=$msg.'\nCash: '.number_format($thisInvoice[0]['paid_cash']);}
                if($thisInvoice[0]['payment_mode']=='Card'){$msg=$msg.'\nCard: '.number_format($thisInvoice[0]['paid_card']);}
                if($thisInvoice[0]['payment_mode']=='Check'){$msg=$msg.'\nCheck: '.number_format($thisInvoice[0]['paid_check']);}
                if($thisInvoice[0]['payment_mode']=='Vocher'){$msg=$msg.'\nVoucher: '.number_format($thisInvoice[0]['paid_voucher']);}
                if((int)$thisInvoice[0]['balance']>0){$msg=$msg.'\nBalance: '.number_format($thisInvoice[0]['balance']);}
                $msg=$msg.'\nLoyaltyUsed: '.number_format($thisInvoice[0]['loyalty_used']);
                $msg=$msg.'\nTipCharged: '.number_format($thisInvoice[0]['cctip']);
                foreach ($admins as $admin){
                    if(null != $admin['user_mobile']){
                        if(strlen($admin['user_mobile'])===11){
                        //echo(utf8_encode(trim($msg)));
                        $msg = iconv('ISO-8859-1', 'UTF-8', $msg);
                        $sendsms = $this->sms_model->send_sms(trim($msg), $admin['user_mobile'], false, 'AdminSMS', false,  $business[0]['id_business']); 
                        }
                    }
                }
            //}   
        }


        $wa_phone = $customer_phone;
        if (preg_match('/^0(\d{10})$/', $customer_phone, $matches)) {
            $wa_phone = '+92' . $matches[1]; // Replace '0' with '+92'
        }

        if($receipts_intsalled==FALSE){
                
                
            if ($this->db->table_exists('wa_msg_list')) {
                
                $msg='Hi '.$customername.','.chr(10).'Thank you for visiting '.$business[0]['business_name'].'.'.chr(10);
                if($business[0]['loyalty_enable']=='Y'){
                    if((Int)$invoiceid[0]>0 && (Int)$invoiceid[1]>0  && $business[0]['show_points']=='Yes'){                    
                        $msg=$msg.'Points earned today '. round($invoiceid[1]) .'.'.chr(10).'Total points '. round($newloyaltypoints).'.'.chr(10);
                    } 
                    if((Int)$invoiceid[0]>0 && (Int)$invoiceid[2]>0  && $business[0]['show_amount']=='Yes'){                        
                        $msg=$msg.'Bill '. $invoiceid[2].".".chr(10);
                        $msg=$msg.'Paid '. $invoiceid[3].".".chr(10);
                        if((int)$invoiceid[4]>0){
                            $msg=$msg.'Balance '. $invoiceid[4].".".chr(10);
                        }
                    }  
                }

                $data = array(
                    'invoice_id'=>$invoiceid[0],
                    'text_msg'=> '😀 '.$msg,
                    'business_id'=>$this->session->userdata('businessid'),
                    'receiver'=> $wa_phone,
                    'msg_type'=> 'invoice'
                );
                $this->db->insert('wa_msg_list', $data);
            }

            echo "success|".$invoiceid[0];
        } else {
            if ($this->db->table_exists('wa_msg_list')) {
                
                $data = array(
                    'invoice_id'=>$invoiceid[0],
                    'text_msg'=>'😀 Thank you for Visiting '.$business[0]['business_name'].'.\nPlease click on the link below to view your receipt.\n',
                    'receipt_url'=>$receipturl,
                    'business_id'=>$this->session->userdata('businessid'),
                    'receiver'=> $wa_phone,
                    'msg_type'=> 'invoice'
                );
                $this->db->insert('wa_msg_list', $data);
            }

            echo "success|".$invoiceid[0]."|".$receipturl."|". substr($customer_phone, 1);
        }
    }
    
    
   function getimsjson(){
        $invoiceid = $this->input->post('invoiceid');
        $invoicetype = $this->input->post('invoicetype');
        $business=$this->business_model->getbusinessdetails();
        $mJson='{}';
        if(isset($business[0]['imsfiscal'])){
            $this->load->model('imsfiscal_model');
            if($business[0]['imsfiscal']=='Yes'){
                $ims_details = $this->imsfiscal_model->get_imsfiscal_details($invoicetype);
                if($ims_details->posid !== null && $ims_details->posid !== '' && $ims_details->ims_url!==null && $ims_details->ims_url!==''){
                    $mJson = $this->imsfiscal_model->imsfiscal_invoice_json($ims_details->posid, $invoiceid, $ims_details->ims_url, $ims_details->ims_token, $invoicetype, $business[0]['tax_mode']);
                    
                }
            }        
        }        
        
        echo $mJson;
        
    }
    
    
    function cancelinvoice(){
    
        $result=$this->invoice_model->cancel_invoice();
       
        echo $result;
       
    }
    
    function recoveryinvoices(){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            checkroles(1,0,1);

            $data['nav'] = 'invoice';
            $data['subnav'] = 'recoveryinvoices';

            $data['invoices']=$this->invoice_model->getrecoveryinvoices();

            $this->load->view('includes/header', $data);
            $this->load->view('invoice_recovery');
            $this->load->view('includes/footer');
        }
        
    } 

    function todayinvoices($customer_id=null, $today=''){
        //exit();
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            checkroles(1,0,1);

            $data['nav'] = 'invoice';
            $data['subnav'] = 'todayinvoices';
            $today = date('Y-m-d');
            
            if(null != $this->input->post('mDate') && $this->input->post('mDate')!=''){
                $today = $this->input->post('mDate') ;
            }
            
            if(null!=$this->input->post('customer_id')){$customer_id=$this->input->post('customer_id');}

            $data['invoices']=$this->invoice_model->gettodayinvoices(null, 'asc', 'all', false, $today, $customer_id);
            $data['business']=$this->business_model->getbusinessdetails();
            $data['today']=$today;
            
            $this->load->view('includes/header', $data);
            $this->load->view('invoice_list');
            $this->load->view('includes/footer');
        }
    }
    
    
    
    function appointments($appointment_date = NULL){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            checkroles(1,0,1);

            $data['nav'] = 'invoice';
            $data['subnav'] = 'appointments';

            $data['rows'] = $this->invoice_model->getappointments($appointment_date);

            $i=0;
            foreach($data['rows'] as $row){
                $result = $this->invoice_model->getappointmentsstaff($row->id_customer_visits, $row->id_visit_services);
                $staff_ids = "";
                $staff_names = "";
                foreach($result as $res){
                    $staff_ids .= $res->staff_id."|";
                    $staff_names .= $res->staff_name."|";
                }
                $data['rows'][$i]->staff_ids = rtrim($staff_ids, '|');
                $data['rows'][$i]->staff_names = rtrim($staff_names, '|');
                $i++;
            }

            //$this->nice_print_r($data['rows']); exit;
            $data['date'] = $appointment_date;
            $this->load->view('includes/header', $data);
            $this->load->view('appointments_list');
            $this->load->view('includes/footer');
        }
    }
    
    function open_order_invoice(){
        $data['nodatatable']='nodatatable';
        
        $orderid=$this->input->post('order-id', TRUE);
        
        
        if(null !== $orderid && $orderid !==''){
            //Get the order
            $data['order'] = $this->order_model->getopenorderbyid($orderid);
            
        } else {
            echo 'Order ID not received. Session may have expired. Try again!';
            exit();
        }
        
        
        if($data['order']){
            $ids=[];
            foreach($data['order'] as $product){
                array_push($ids, $product['product_id']);
            }

            //Get all products
            $data['products']=$this->order_model->getorderproducts($ids, $orderid);

            //Get Balance
            $data['balance'] = $this->customer_model->customerbalance($data['order'][0]['customer_id']);
            $data['customer_points'] = $this->customer_model->get_customer_loyalty($data['order'][0]['customer_id']);
            
            
            //Get next invoice number
            $data['invoiceno']=$this->invoice_model->getnextinvoicenumber();

            $data['business']=$this->business_model->getbusinessdetails();
            $data['taxes']=$this->business_model->getbusinesstaxes('sale');

            $data['menu'] = 'hidden';

            $this->load->view('includes/header', $data);
            $this->load->view('order_invoice_view');
            $this->load->view('includes/footer');
        } else{
            
            $invoiceid=  $this->order_model->getinvoicedorderbyid($orderid);
            
            redirect(base_url()."existingorderinvoice/".$invoiceid[0]['id_invoice']);
        }
    }
   
    function openorderinvoice($invoiceid){
        //$invoiceid=$this->input->post('invoiceid');
       
        $data['nodatatable']='nodatatable';
        
        
        if(null !== $invoiceid && $invoiceid !==''){
            //Get the invoice and pass as visit
            $data['invoice']=$this->invoice_model->getinvoicebyid($invoiceid);
        }else{
            echo 'Invoice ID not received. Session may have expired. Try Again!';
            exit();
        }
        
        if(null !== $data['invoice'][0]['org_invoice_id'] && $data['invoice'][0]['org_invoice_id']>0){
            
            $invoiceid = $data['invoice'][0]['org_invoice_id'];
            
        } else if($data['invoice'][0]['reference_invoice_number'] !== ''){
            
            $invoiceno = $data['invoice'][0]['reference_invoice_number'];
            $invoice=$this->invoice_model->getinvoicebyno($invoiceno);
            $invoiceid = $invoice[0]['id_invoice'];
            
        }
        
        //Get all details and pass as products
        $data['invoiceproducts']=$this->invoice_model->getinvoiceproducts($invoiceid);
        
               
        $data['business']=$this->business_model->getbusinessdetails();
        //$data['taxes']=$this->invoice_model->getinvocietaxes($invoiceid);
        
        $this->db->select('invoice_tax_name, sum(invoice_tax) as invoice_tax');
        $this->db->where('invoice_id', $invoiceid);
        $this->db->group_by('invoice_tax_name');
        $query =$this->db->get('invoice_taxes');
        
        $data['taxes'] = $query->result_array();
        
        $data['menu'] = 'hidden';
        $data['logout']='No';
        
        $this->load->view('includes/header', $data);
        $this->load->view('exist_order_invoice_view');
        $this->load->view('includes/footer');
        
    }
    
    function updateorderinvoice(){
        $orderid=$this->input->post('orderid', TRUE);
        $customer_phone = $this->input->post('customercell');
       
        if(null == $orderid || $orderid==0){
           echo 'error|This order was not found. Session may have expired. Try Again!';
           exit();
        }
        
        $this->load->model('scheduled_tasks_model');
        $loyalty_text = $this->scheduled_tasks_model->get_loyalty_text();
       
        //Get the order
        $data['order'] = $this->order_model->getopenorderbyid($orderid);
        if(!$data['order']){
            echo 'error|This order has already been invoice. Refresh Page!';
           exit();
            
        }
        $verification = $this->customer_model->get_customer_loyalty($this->input->post('customerid'));
        
        if((float)$verification[0]['retained'] <  ((float)$this->input->post('retained_amount_used') + (float)$this->input->post('remaining_retained'))){
           echo 'error|Another Invoice used the customer advance. Refresh Page!';
           exit();
        }
       
        if((float)$verification[0]['loyalty_points'] <  (float)$this->input->post('loyaltyused')){
           echo 'error|Loyalty points already used in some other invoice. Refresh Page!';
           exit();
        }   
        
       
        $result1 = $this->invoice_model->update_order_invoice();
        
        $invoiceid= explode("|", $result1);
        if($invoiceid[0]=='error'){
            echo $invoiceid[0].'|'.$invoiceid[1];
            exit();
        }
        
        
        ////sms////
        
        $business=$this->business_model->getbusinessdetails();
       
        if($business[0]['loyalty_sms']=='Yes' && sizeof($verification)>0 && strlen($customer_phone)==11){
            
            $newloyaltypoints = $verification[0]['loyalty_points'];
            $customername= $verification[0]['customer_name'];
            
            
            if($business[0]['business_name']=='mks'){
                $msg='Thank u for your business of '.CURRENCY_CODE.'. '. $invoiceid[3].' at '.$business[0]['business_name'].'\n';
                
            }else{            
                $msg='Hi '.$customername.',\nThank you for visiting '.$business[0]['business_name'].'.\n';
            }
            
            if($business[0]['loyalty_enable']=='Y'){
                if((Int)$invoiceid[0]>0 && (Int)$invoiceid[1]>0  && $business[0]['show_points']=='Yes'){
                   //$newloyaltypoints =  (float)$newloyaltypoints+(float)$invoiceid[1];
                   $msg=$msg.'You have earned '. $invoiceid[1] .' points today. Your total points are '. $newloyaltypoints.'\n';
                } 
                if((Int)$invoiceid[0]>0 && (Int)$invoiceid[2]>0  && $business[0]['show_amount']=='Yes'){
                   //$newloyaltypoints =  (float)$newloyaltypoints+(float)$invoiceid[1];
                   $msg=$msg.'Your total bill amount is '. $invoiceid[2]."\n";
                   $msg=$msg.'You paid '. $invoiceid[3]."\n";
                   if((int)$invoiceid[4]>0){
                        $msg=$msg.'Your balance is '. $invoiceid[4]."\n";
                   }
                   
                }              
            }
           if($loyalty_text!==null && $loyalty_text!==''){
                $msg=$msg.$loyalty_text->msg;
            }
            //echo utf8_encode(trim($msg)), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business'];
            //exit();
            $msg = iconv('ISO-8859-1', 'UTF-8', $msg);
            $sendsms = $this->sms_model->send_sms(trim($msg), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business']); 
            //$updatelog = $this->invoice_model->invoice_sms_update($invoiceid[0], $sendsms);
        }
        
        if($business[0]['admin_notifications']==='Yes' && (Int)$invoiceid[0] > 0){
            $admins = $this->business_model->get_business_admins();
            
            $thisInvoice = $this->invoice_model->getinvoicebyid($invoiceid[0]);
            $msg=$business[0]['business_name'];
            $msg=$msg.'\nInvoice#: '.$thisInvoice[0]['id_invoice'].'\n Time: '.$thisInvoice[0]['invoice_date'].'\n Customer: '.$thisInvoice[0]['customer_name'];
            $msg=$msg.'\n Payable: '.number_format($thisInvoice[0]['net_amount']);
            if($thisInvoice[0]['payment_mode']=='Cash'){$msg=$msg.'\n Cash: '.number_format($thisInvoice[0]['paid_cash']);}
            if($thisInvoice[0]['payment_mode']=='Card'){$msg=$msg.'\n Card: '.number_format($thisInvoice[0]['paid_card']);}
            if($thisInvoice[0]['payment_mode']=='Check'){$msg=$msg.'\n Check: '.number_format($thisInvoice[0]['paid_check']);}
            if($thisInvoice[0]['payment_mode']=='Vocher'){$msg=$msg.'\n Voucher: '.number_format($thisInvoice[0]['paid_voucher']);}
            if((int)$thisInvoice[0]['balance']>0){$msg=$msg.'\n Balance: '.number_format($thisInvoice[0]['balance']);}
            $msg=$msg.'\nLoyaltyUsed: '.number_format($thisInvoice[0]['loyalty_used']);
            $msg=$msg.'\nTipCharged: '.number_format($thisInvoice[0]['cctip']);
            foreach ($admins as $admin){
                if(null != $admin['user_mobile']){
                    if(strlen($admin['user_mobile'])===11){
                        $msg = iconv('ISO-8859-1', 'UTF-8', $msg);
                        $sendsms = $this->sms_model->send_sms(trim($msg), $admin['user_mobile'], false, 'AdminSMS', false,  $business[0]['id_business']); 
                    }
                }
            }
        }
      //  echo "success|".$invoiceid[0];
        //IMS Fiscal
//         if(isset($business[0]['imsfiscal'])){
//            $this->load->model('imsfiscal_model');
//            if($business[0]['imsfiscal']=='Yes'){
//                $ims_details = $this->imsfiscal_model->get_imsfiscal_details();
//                if($ims_details->posid !== null && $ims_details->posid !== '' && $ims_details->ims_url!==null && $ims_details->ims_url!==''){
//                    $this->imsfiscal_model->imsfiscal_invoice_sale($ims_details->posid, $invoiceid[0], $ims_details->ims_url, $ims_details->ims_token, 1, $business[0]['tax_mode']);
//                }
//            }        
//        }
        
        
        echo "success|".$invoiceid[0]."|".$this->input->post('customerid');
    }
    
    
    
    function discount_login() {
        $result = $this->invoice_model->discount_login();
        if ($result) {
            echo json_encode($result);
            die;
        }else{
            echo "error";
            die;
        }
    }
    
    function invoice_service_product($serviceid,$visit_id){
        $data['service_products'] = $this->invoice_model->invoice_service_product($serviceid);
        $data['products'] = $this->visits_model->getopenvisitbyid($visit_id);
        $data['services']=$this->visits_model->getvisitservices($visit_id);
        echo(json_encode($data));
    }
    
    function invoice_service_product_update(){
        $result = $this->invoice_model->invoice_service_product_update();
        if($result) echo "success";
    }
   
    function print_booking($visitid){
        $data['nodatatable']='nodatatable';
        $data['nav'] = 'invoice';

        
        //Get the visit
       // $data['visit']=$this->visits_model->getadvancevisitbyid($visitid);
        
        $sql="SELECT * from users
                        join user_roles on user_roles.user_id = users.id_users
                        where user_roles.role_id = 2";
        $query = $this->db->query($sql);        
        
        $data['cashiers'] = $query->result_array();        
        
        $sql = "select customer_visits.*, id_customers, customer_name, customer_cell, 
                date_format(visit_service_start, '%d-%m-%Y %H:%i') as visit_service_start, 
                date_format(visit_service_end,'%d-%m-%Y')  as visit_service_end,
                customer_visits.discount,
                date_format(customer_visits.created_on, '%d-%m-%Y') as booking_date,
                customer_visits.created_by, customer_visits.visit_status,
                package_category.id_package_category, package_category.service_category,
                package_type.id_package_type, package_type.service_type,
                sum(package_services.service_rate) as service_rate, customer_visits.discount
                from customer_visits 
                join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
                join package_services on visit_services.id_service_category = package_services.package_category_id and visit_services.service_id = package_services.service_id
                join package_category on package_category.id_package_category = package_services.package_category_id
                join package_type on package_type.id_package_type = package_category.package_type_id
                join customers on customers.id_customers = customer_visits.customer_id
                where id_customer_visits = ".$visitid."
                group by id_customer_visits";
        $query = $this->db->query($sql);        
        
        $data['visit'] = $query->result_array();
        
        
        if($data['visit']){
            
            $sql = "SELECT max(visit_services.visit_service_end) as departure_time
                    FROM customer_visits 
                    join visit_services on visit_services.customer_visit_id = customer_visits.id_customer_visits
                    where id_customer_visits = ".$visitid.";";
            $query = $this->db->query($sql);        
        
            $data['departure_time'] = $query->row();
             
            
            $sql = "SELECT booking_visits.* FROM customer_visits
            join booking_visits on booking_visits.visit_id=customer_visits.id_customer_visits
            where visit_id=".$visitid;
            $query = $this->db->query($sql);                
            $b = $query->row();
            $data['bookingid']=$b->booking_id;
            
            
            $data['business']=$this->business_model->getbusinessdetails();
            $data['advances'] = $this->visits_model->getopenvisitadvancesumbyid($visitid);
            $this->load->model('packages_model');
            $data['package'] = $this->packages_model->getpackageamount($data['visit'][0]['id_package_type']);
            
            $data['menu'] = 'hidden';
            $data['logout']='No';
            
            $this->load->view('includes/header', $data);
            $this->load->view('print_booking_view');
            $this->load->view('includes/footer');
            
        } else{
            echo 'Booking not found!';
        }
        
    }
    
    public function print_advance($visitid){
        $data['nav'] = 'invoice';
        $data['nodatatable']='nodatatable';

        //Get the visit
        $data['visit']=$this->visits_model->getadvancevisitbyid($visitid);
        
        if($data['visit']){
            
            $data['staffs']=$this->visits_model->getvisitstaffs($visitid);
            
            //$this->nice_print_r($data['visit']); 
            $data['customer'] = $this->customer_model->get_byid($data['visit'][0]['customer_id']);
            $data['balance'] = $this->customer_model->customerbalance($data['visit'][0]['customer_id']);
            //Get all services
            $data['services']=$this->visits_model->getvisitservices($visitid);
            $data['business']=$this->business_model->getbusinessdetails();
            $data['advances'] = $this->visits_model->getopenvisitadvancebyid($visitid);   
            
            $data['menu'] = 'hidden';
            $data['logout']='No';
            $this->load->view('includes/header', $data);
            $this->load->view('print_advance_view');
            $this->load->view('includes/footer');
            
        } else{
            echo 'Advance not booked!';
        }
    }

    function getmaxinvoice(){
        
        $result = $this->invoice_model->getmaxinvoice();

        echo json_encode($result);
        
    }
    
    // function httpRequest($url)
    // {
       
        // $args;
        // $pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
        // preg_match($pattern,$url,$args);
        // $in = "";
        // $fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
        // if (!$fp)
        // {
        //    return("$errstr ($errno)");
        // }
        // else
        // {
        //     $out = "GET /$args[3] HTTP/1.1\r\n";
        //     $out .= "Host: $args[1]:$args[2]\r\n";
        //     $out .= "User-agent: PHP Web SMS client\r\n";
        //     $out .= "Accept: */*\r\n";
        //     $out .= "Connection: Close\r\n\r\n";

        //     fwrite($fp, $out);
        //     while (!feof($fp))
        //     {
        //        $in.=fgets($fp, 128);
        //     }
        // }
        // fclose($fp);
        // return($in);
    // } 
    
    // function send_sms($msg, $phone, $debug=false)
    // {
    //     $username='';
    //     $password='';   
    //     $smsurl='';

    //     $this->load->model('sms_model');    
    //     $sms_cred = $this->sms_model->get_sms_cred();
        
    //     if(!$sms_cred==Null){
    //         $username   = $sms_cred[0]['username']; 
    //         $password   = $sms_cred[0]['password'];
    //         $smsurl     = "http://".$sms_cred[0]['domain'].":80/api/?"; // change smsdomain.com to your provided; 

    //         $url  = 'username='.$username;
    //         $url  .= '&password='.$password;
    //         $url  .= '&receiver='.urlencode($phone);
    //         $url  .= '&msgdata='.urlencode($msg);
    //         $urltouse =  $smsurl.$url;
           
    //         //Open the URL to send the message
    //           $response =  $this->httpRequest($urltouse);
    //          return $response;    
    //     } else {
    //         return 'SMS Service is not setup!';
    //     }
    // }
    
    
    public function custom_invoices(){
        
        if ($this->session->userdata('role') === '' || $this->session->userdata('role') === 'Sh-Users') {
            $this->load->view('login_view');  
             
        } else {
            //storemanager,hr,reception...user serial
            checkroles(0, 0, 0);

            $data['nav'] = 'business';
            $data['subnav'] = 'accounting';

            $data['business'] = $this->business_model->get_business_details();
    
            $this->load->view('includes/header', $data);
            $this->load->view('accounting/custom/custom_invoices');
            $this->load->view('includes/footer');
        }
       
    }
    public function checkdiscountpw(){
        
        $mpw = $this->input->post('mypassword');
        echo md5($mpw);
    }
    
    public function test_ims(){
        
        $this->load->model('imsfiscal_model');
        
        $ims_details = $this->imsfiscal_model->get_imsfiscal_details('service');
        if($ims_details->posid !== null && $ims_details->posid !== '' && $ims_details->ims_url!==null && $ims_details->ims_url!==''){
            $this->imsfiscal_model->imsfiscal_invoice_service($ims_details->posid, 4184, $ims_details->ims_url, $ims_details->ims_token, 1, 'after');
        }
              
        
    }
    
    
    
    function createretailinvoice(){
        $orderid=$this->input->post('orderid', TRUE);
        $customer_phone = $this->input->post('customercell');
       
        if(null == $orderid || $orderid==0){
           echo 'error|This order was not found. Session may have expired. Try Again!';
           exit();
        }
        
       $this->load->model('scheduled_tasks_model');
       $loyalty_text = $this->scheduled_tasks_model->get_loyalty_text();
       
        //Get the order
        $data['order'] = $this->order_model->getopenorderbyid($orderid);
        if(!$data['order']){
            echo 'error|This order has already been invoice. Refresh Page!';
           exit();
            
        }
        $verification = $this->customer_model->get_customer_loyalty($this->input->post('customerid'));
        
        if((float)$verification[0]['retained'] <  ((float)$this->input->post('retained_amount_used') + (float)$this->input->post('remaining_retained'))){
           echo 'error|Another Invoice used the customer advance. Refresh Page!';
           exit();
       }
       
       if((float)$verification[0]['loyalty_points'] <  (float)$this->input->post('loyaltyused')){
           echo 'error|Loyalty points already used in some other invoice. Refresh Page!';
           exit();
       }   
        
       
        $result1 = $this->invoice_model->create_order_invoice();
        
        $invoiceid= explode("|", $result1);
        if($invoiceid[0]=='error'){
            echo $invoiceid[0].'|'.$invoiceid[1];
            exit();
        }
        
        
        ////sms////
        
        $business=$this->business_model->getbusinessdetails();
       
        if($business[0]['loyalty_sms']=='Yes' && sizeof($verification)>0 && strlen($customer_phone)==11){
            
            $newloyaltypoints = $verification[0]['loyalty_points'];
            $customername= $verification[0]['customer_name'];
            
            
            if($business[0]['business_name']=='mks'){
                $msg='Thank u for your business of '.CURRENCY_CODE.'. '. $invoiceid[3].' at '.$business[0]['business_name'].'\n';
                
            }else{            
                $msg='Hi '.$customername.',\nThank you for visiting '.$business[0]['business_name'].'.\n';
            }
            
            if($business[0]['loyalty_enable']=='Y'){
                if((Int)$invoiceid[0]>0 && (Int)$invoiceid[1]>0  && $business[0]['show_points']=='Yes'){
                   //$newloyaltypoints =  (float)$newloyaltypoints+(float)$invoiceid[1];
                   $msg=$msg.'You have earned '. $invoiceid[1] .' points today. Your total points are '. $newloyaltypoints.'\n';
                } 
                if((Int)$invoiceid[0]>0 && (Int)$invoiceid[2]>0  && $business[0]['show_amount']=='Yes'){
                   //$newloyaltypoints =  (float)$newloyaltypoints+(float)$invoiceid[1];
                   $msg=$msg.'Your total bill amount is '. $invoiceid[2]."\n";
                   $msg=$msg.'You paid '. $invoiceid[3]."\n";
                   if((int)$invoiceid[4]>0){
                        $msg=$msg.'Your balance is '. $invoiceid[4]."\n";
                   }
                   
                }              
            }
           if($loyalty_text!==null && $loyalty_text!==''){
                $msg=$msg.$loyalty_text->msg;
            }
            //echo utf8_encode(trim($msg)), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business'];
            //exit();
            $msg = iconv('ISO-8859-1', 'UTF-8', $msg);
            $sendsms = $this->sms_model->send_sms(trim($msg), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business']); 
            //$updatelog = $this->invoice_model->invoice_sms_update($invoiceid[0], $sendsms);
        }
        
        if($business[0]['admin_notifications']==='Yes' && (Int)$invoiceid[0] > 0){
            $admins = $this->business_model->get_business_admins();
            
            $thisInvoice = $this->invoice_model->getinvoicebyid($invoiceid[0]);
            $msg=$business[0]['business_name'];
            $msg=$msg.'\nInvoice#: '.$thisInvoice[0]['id_invoice'].'\n Time: '.$thisInvoice[0]['invoice_date'].'\n Customer: '.$thisInvoice[0]['customer_name'];
            $msg=$msg.'\n Payable: '.number_format($thisInvoice[0]['net_amount']);
            if($thisInvoice[0]['payment_mode']=='Cash'){$msg=$msg.'\n Cash: '.number_format($thisInvoice[0]['paid_cash']);}
            if($thisInvoice[0]['payment_mode']=='Card'){$msg=$msg.'\n Card: '.number_format($thisInvoice[0]['paid_card']);}
            if($thisInvoice[0]['payment_mode']=='Check'){$msg=$msg.'\n Check: '.number_format($thisInvoice[0]['paid_check']);}
            if($thisInvoice[0]['payment_mode']=='Vocher'){$msg=$msg.'\n Voucher: '.number_format($thisInvoice[0]['paid_voucher']);}
            if((int)$thisInvoice[0]['balance']>0){$msg=$msg.'\n Balance: '.number_format($thisInvoice[0]['balance']);}
            
            foreach ($admins as $admin){          
                if(null != $admin['user_mobile']){      
                    if(strlen($admin['user_mobile'])===11){     
                        $msg = iconv('ISO-8859-1', 'UTF-8', $msg);               
                        $sendsms = $this->sms_model->send_sms(trim($msg), $admin['user_mobile'], false, 'AdminSMS', false,  $business[0]['id_business']); 
                    }    
                }            
            }
        }
        
        echo "success|".$invoiceid[0]."|".$this->input->post('customerid');
    }
    
    



    // ========================> jun-14-2024 Start <======================== 
    function open_order_invoice_for_pos(){
        $data['nodatatable']='nodatatable';
        $orderid=$this->input->post('order-id', TRUE);
        if(null !== $orderid && $orderid !==''){
            //Get the order
            $data['order'] = $this->order_model->getopenorderbyid($orderid);
            
        } else {
            echo 'Order ID not received. Session may have expired. Try again!';
            exit();
        }
        if($data['order']){
            $ids=[];
            foreach($data['order'] as $product){
                array_push($ids, $product['product_id']);
            }

            //Get all products
            $data['products']=$this->order_model->getorderproducts($ids, $orderid);

            //Get Balance
            $data['balance'] = $this->customer_model->customerbalance($data['order'][0]['customer_id']);
            $data['customer_points'] = $this->customer_model->get_customer_loyalty($data['order'][0]['customer_id']);
            
            
            //Get next invoice number
            $data['invoiceno']=$this->invoice_model->getnextinvoicenumber();

            $data['business']=$this->business_model->getbusinessdetails();
            $data['taxes']=$this->business_model->getbusinesstaxes('sale');

            $data['menu'] = 'hidden';
            $data['orderid']=$orderid;
            // $this->load->view('includes/header');
            $this->load->view('restaurant/order_invoice_view_for_pos', $data);
           //$this->load->view('includes/footer');
        } else{
            
            $invoiceid=  $this->order_model->getinvoicedorderbyid($orderid);
            
            redirect(base_url()."existingorderinvoice/".$invoiceid[0]['id_invoice']);
        }
    }
      function open_order_invoice_for_print_pos_bill(){
        $data['nodatatable']='nodatatable';
        $orderid=$this->input->post('order-id', TRUE);
        if(null !== $orderid && $orderid !==''){
            //Get the order
            $data['order'] = $this->order_model->getopenorderbyid($orderid);

        } else {
            echo 'Order ID not received. Session may have expired. Try again!';
            exit();
        }
        if($data['order']){
            $ids=[];
            foreach($data['order'] as $product){
                array_push($ids, $product['product_id']);
            }

            //Get all products
            $data['products']=$this->order_model->getorderproducts($ids, $orderid);  

            //Get Balance
            $data['balance'] = $this->customer_model->customerbalance($data['order'][0]['customer_id']);
            $data['customer_points'] = $this->customer_model->get_customer_loyalty($data['order'][0]['customer_id']);
            
            
            //Get next invoice number
            $data['invoiceno']=$this->invoice_model->getnextinvoicenumber();

            $data['business']=$this->business_model->getbusinessdetails();
            $data['taxes']=$this->business_model->getbusinesstaxes('sale');

            $data['menu'] = 'hidden';
            $data['orderid']=$orderid;
            $this->load->view('includes/header',$data);
            $this->load->view('order_invoice_view_for_print_pos_bill');
            $this->load->view('includes/footer');
        } else{
            $invoiceid=  $this->order_model->getinvoicedorderbyid($orderid);
            redirect(base_url()."existingorderinvoice/".$invoiceid[0]['id_invoice']);
        }
    } 



    function open_recovery_order_invoice_for_pos($invoiceid, $orderid){
        $data['nodatatable']='nodatatable';
         //storemanager,hr,reception...user serial
        checkroles(1,0,1);
        
        
        if(null == $invoiceid || $invoiceid==''){
            echo 'Invoice ID not available, Try again!';
            exit();
        }
        
        $check_invoice = $this->invoice_model->check_invoice_recoverable($invoiceid);
        
        if($check_invoice->is_recovery === 'No'){
            redirect(base_url('existingorderinvoice/'.$invoiceid));
        }
        
        $data['nav'] = 'invoice';
        $data['subnav'] = 'recoveryinvoices';
        
        //$data['order'] = $this->order_model->getinvoicedorderbyid($orderid);
        
        //$ids=[];
        //foreach($data['order'] as $product){
        //    array_push($ids, $product['product_id']);
        //}

        //Get all products
        //$data['products']=$this->order_model->getorderproducts($ids, $orderid);

        //Get next invoice number
        $data['invoiceno']=$this->invoice_model->getnextinvoicenumber();

        $data['business']=$this->business_model->getbusinessdetails();
        $data['taxes']=$this->business_model->getbusinesstaxes('sale');
        
        // get invoice details
        $data['invoice']=$this->invoice_model->getinvoicebyid($invoiceid); 

        $this->db->select('id_invoice_products, business_id, invoice_id, staff_id, staff_name, product_name, brand_name, 
        SUM(invoice_qty) AS invoice_qty, SUM(discounted_price) AS discounted_price, 
        SUM(paid) AS paid, SUM(final_price) AS final_price, SUM(taxes) AS taxes,
        discount_type, discount, service_addition, invoice_product_date, price, invoice_discount,
        commission, product_id, category, batch, batch_id, cog_amount');
        $this->db->where('invoice_products.invoice_id', $invoiceid);
        $this->db->group_by('invoice_products.product_id'); 
        $query = $this->db->get('invoice_products'); 
        $invoiceproducts =$query->result_array();  
        $data['products']=$invoiceproducts;
        
        $data['menu'] = 'hidden';
        $this->load->view('restaurant/order_invoice_recovery_view_for_pos',$data);
        $this->load->view('includes/footer');
    } 

    function openorderinvoice_for_pos($invoiceid){
        //$invoiceid=$this->input->post('invoiceid');
       
        $data['nodatatable']='nodatatable';
        
        
        if(null !== $invoiceid && $invoiceid !==''){
            //Get the invoice and pass as visit
            $data['invoice']=$this->invoice_model->getinvoicebyid($invoiceid);
        }else{
            echo 'Invoice ID not received. Session may have expired. Try Again!';
            exit();
        }
        
        if(null !== $data['invoice'][0]['org_invoice_id'] && $data['invoice'][0]['org_invoice_id']>0){
            
            $invoiceid = $data['invoice'][0]['org_invoice_id'];
            
        } else if($data['invoice'][0]['reference_invoice_number'] !== ''){
            
            $invoiceno = $data['invoice'][0]['reference_invoice_number'];
            $invoice=$this->invoice_model->getinvoicebyno($invoiceno);
            $invoiceid = $invoice[0]['id_invoice'];
            
        }
        
        //Get all details and pass as products 
                
                $this->db->select('id_invoice_products, business_id, invoice_id, staff_id, staff_name, product_name, brand_name, 
                SUM(invoice_qty) AS invoice_qty, SUM(discounted_price) AS discounted_price, 
                SUM(paid) AS paid, SUM(final_price) AS final_price, SUM(taxes) AS taxes,
                discount_type, discount, service_addition, invoice_product_date, price, invoice_discount,
                commission, product_id, category, batch, batch_id, cog_amount');
                $this->db->where('invoice_products.invoice_id', $invoiceid);
                $this->db->group_by('invoice_products.product_id'); 
                $query = $this->db->get('invoice_products'); 
                $invoiceproducts =$query->result_array();  



        $data['invoiceproducts']=$invoiceproducts;
        
               
        $data['business']=$this->business_model->getbusinessdetails();
        //$data['taxes']=$this->invoice_model->getinvocietaxes($invoiceid);
        
        $this->db->select('invoice_tax_name, sum(invoice_tax) as invoice_tax');
        $this->db->where('invoice_id', $invoiceid);
        $this->db->group_by('invoice_tax_name');
        $query =$this->db->get('invoice_taxes');
        
        $data['taxes'] = $query->result_array();
        
        $data['menu'] = 'hidden';
        $data['logout']='No';
        
        // $this->load->view('includes/header', $data);
        $this->load->view('restaurant/exist_order_invoice_view_for_pos',$data);
        //$this->load->view('includes/footer');
        
    } 


    function createretailinvoice_for_pos(){
        $orderid=$this->input->post('orderid', TRUE);
        $customer_phone = $this->input->post('customercell');
       
        if(null == $orderid || $orderid==0){
           echo 'error|This order was not found. Session may have expired. Try Again!';
           exit();
        }
        
       $this->load->model('scheduled_tasks_model');
       $loyalty_text = $this->scheduled_tasks_model->get_loyalty_text();
       
        //Get the order
        $data['order'] = $this->order_model->getopenorderbyid($orderid);
        if(!$data['order']){
            echo 'error|This order has already been invoice. Refresh Page!';
           exit();
            
        }
        $verification = $this->customer_model->get_customer_loyalty($this->input->post('customerid'));
        
        if((float)$verification[0]['retained'] <  ((float)$this->input->post('retained_amount_used') + (float)$this->input->post('remaining_retained'))){
           echo 'error|Another Invoice used the customer advance. Refresh Page!';
           exit();
       }
       
       if((float)$verification[0]['loyalty_points'] <  (float)$this->input->post('loyaltyused')){
           echo 'error|Loyalty points already used in some other invoice. Refresh Page!';
           exit();
       }   
        
       
        $result1 = $this->invoice_model->create_order_invoice_for_pos();
        
        $invoiceid= explode("|", $result1);
        if($invoiceid[0]=='error'){
            echo $invoiceid[0].'|'.$invoiceid[1];
            exit();
        }
        
        
        ////sms////
        
        $business=$this->business_model->getbusinessdetails();
       
        if($business[0]['loyalty_sms']=='Yes' && sizeof($verification)>0 && strlen($customer_phone)==11){
            
            $newloyaltypoints = $verification[0]['loyalty_points'];
            $customername= $verification[0]['customer_name'];
            
            
            if($business[0]['business_name']=='mks'){
                $msg='Thank u for your business of '.CURRENCY_CODE.'. '. $invoiceid[3].' at '.$business[0]['business_name'].'\n';
                
            }else{            
                $msg='Hi '.$customername.',\nThank you for visiting '.$business[0]['business_name'].'.\n';
            }
            
            if($business[0]['loyalty_enable']=='Y'){
                if((Int)$invoiceid[0]>0 && (Int)$invoiceid[1]>0  && $business[0]['show_points']=='Yes'){
                   //$newloyaltypoints =  (float)$newloyaltypoints+(float)$invoiceid[1];
                   $msg=$msg.'You have earned '. $invoiceid[1] .' points today. Your total points are '. $newloyaltypoints.'\n';
                } 
                if((Int)$invoiceid[0]>0 && (Int)$invoiceid[2]>0  && $business[0]['show_amount']=='Yes'){
                   //$newloyaltypoints =  (float)$newloyaltypoints+(float)$invoiceid[1];
                   $msg=$msg.'Your total bill amount is '. $invoiceid[2]."\n";
                   $msg=$msg.'You paid '. $invoiceid[3]."\n";
                   if((int)$invoiceid[4]>0){
                        $msg=$msg.'Your balance is '. $invoiceid[4]."\n";
                   }
                   
                }              
            }
           if($loyalty_text!==null && $loyalty_text!==''){
                $msg=$msg.$loyalty_text->msg;
            }
            //echo utf8_encode(trim($msg)), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business'];
            //exit();
            $msg = iconv('ISO-8859-1', 'UTF-8', $msg);
            $sendsms = $this->sms_model->send_sms(trim($msg), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business']); 
            //$updatelog = $this->invoice_model->invoice_sms_update($invoiceid[0], $sendsms);
        }
        
        if($business[0]['admin_notifications']==='Yes' && (Int)$invoiceid[0] > 0){
            $admins = $this->business_model->get_business_admins();
            
            $thisInvoice = $this->invoice_model->getinvoicebyid($invoiceid[0]);
            $msg=$business[0]['business_name'];
            $msg=$msg.'\nInvoice#: '.$thisInvoice[0]['id_invoice'].'\n Time: '.$thisInvoice[0]['invoice_date'].'\n Customer: '.$thisInvoice[0]['customer_name'];
            $msg=$msg.'\n Payable: '.number_format($thisInvoice[0]['net_amount']);
            if($thisInvoice[0]['payment_mode']=='Cash'){$msg=$msg.'\n Cash: '.number_format($thisInvoice[0]['paid_cash']);}
            if($thisInvoice[0]['payment_mode']=='Card'){$msg=$msg.'\n Card: '.number_format($thisInvoice[0]['paid_card']);}
            if($thisInvoice[0]['payment_mode']=='Check'){$msg=$msg.'\n Check: '.number_format($thisInvoice[0]['paid_check']);}
            if($thisInvoice[0]['payment_mode']=='Vocher'){$msg=$msg.'\n Voucher: '.number_format($thisInvoice[0]['paid_voucher']);}
            if((int)$thisInvoice[0]['balance']>0){$msg=$msg.'\n Balance: '.number_format($thisInvoice[0]['balance']);}
            
            foreach ($admins as $admin){
                if(null != $admin['user_mobile']){                
                    if(strlen($admin['user_mobile'])===11){    
                        $msg = iconv('ISO-8859-1', 'UTF-8', $msg);                
                        $sendsms = $this->sms_model->send_sms(trim($msg), $admin['user_mobile'], false, 'AdminSMS', false,  $business[0]['id_business']); 
                    }         
                }       
            }
        }
        
        echo "success|".$invoiceid[0]."|".$this->input->post('customerid');
    }

    
    // ========================> jun-14-2024 End <========================

    function updateslipcode(){
        if($this->input->post('invoiceid') != null){
            $this->db->where('id_invoice', $this->input->post('invoiceid'));
            $this->db->set('receipt_code', $this->input->post('receipt_code'));
            $this->db->set('receipt_url', $this->input->post('receipt_url'));
            $this->db->update('invoice');
            echo 'success|receipt code updated';

        } else {
            echo 'error|invoice id not found';
        }

    }
    

}
