<?php

class Invoice_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
         
    }
    
    function getPackageInvoices(){
        $customer = $this->input->post('customer');
        $type = $this->input->post('type');
        $start = $this->input->post('start');
        $end = $this->input->post('end');
        
        $this->db->select('*, DATE_FORMAT(invoice_date, "%d-%c-%Y") as invoice_date');
        $this->db->join('invoice_details invd', 'invd.invoice_id = inv.id_invoice');
        
        $this->db->where('inv.business_id', $this->session->userdata('businessid'));
        $this->db->where('inv.visit_time >', $start);
        $this->db->where('inv.visit_time <=', $end);
        if(!$type==""){
            $this->db->where('invd.service_type', $type);
        }
        if(!$customer==''){
            if(ctype_digit($customer)){
                $this->db->like('inv.customer_cell', $customer);
            } else{
                $this->db->like('inv.customer_name', $customer);
            }
        }
        $this->db->where('inv.invoice_status', 'valid');
        $this->db->where('inv.reference_invoice_number !=', 'bad debts');
        $this->db->order_by('inv.customer_name');
        $this->db->group_by('invd.invoice_id');
        $query = $this->db->get('invoice inv');
        return $query->result_array();
    }
     
    function getPackageTypes(){
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('service_type_active', 'Yes');
        $query = $this->db->get('package_type');
        return $query->result();
    }
    
    function markBadDebts(){
        
        $data = array(
            'remarks' => $this->input->post('remarks', TRUE),
            'is_recovery' => 'No'
            //'reference_invoice_number' => 'bad debts'
        );
        
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('id_invoice', $this->input->post('invoice_id', TRUE));
        
        $query = $this->db->update('invoice', $data);
        return $query;
     
        
    }
    
    function get_today_expenses(){
        
        $today = $this->input->post('calendar_date', TRUE);
        
        if(!isset($today) || empty($today)){
            $today = date('Y-m-d');
        }

        $event_mappings = $this->accounting_model->get_mapped_accounts(1);
        foreach($event_mappings as $event_mapping){
            if($event_mapping['entity_name']=='paid_cash'){
                $sql="SELECT ifnull(sum(credit),0) as today_expenses 
                FROM `account_vouchers` 
                JOIN `account_voucher_detail` ON `account_vouchers`.`id_account_vouchers` = `account_voucher_detail`.`account_voucher_id` 
                JOIN account_voucher_type on account_voucher_type.id_account_voucher_type = account_vouchers.voucher_type 
                WHERE `account_vouchers`.`business_id` = '".$this->session->userdata('businessid')."' 
                AND date(`account_vouchers`.`voucher_date`) = '".$today."'  
                AND `account_vouchers`.`voucher_status` = 'Active' 
                AND account_vouchers.voucher_type = 1
                AND account_head_id = ".$event_mapping['account_head_id'].";";
            }
        }
        
        
//        $sql="SELECT sum(debit) as today_expenses 
//                FROM `account_vouchers` 
//                JOIN `account_voucher_detail` ON `account_vouchers`.`id_account_vouchers` = `account_voucher_detail`.`account_voucher_id` 
//                JOIN `account_heads` on account_heads.id_account_heads = account_voucher_detail.account_head_id
//                JOIN `account_sub_control` on account_sub_control.id_account_sub_control = account_heads.account_sub_control_id
//                JOIN `account_control` on account_control.id_account_control = account_sub_control.account_control_id
//                JOIN `account_main` on account_main.id_account_main = account_control.account_main_id                
//                WHERE `account_vouchers`.`business_id` = '".$this->session->userdata('businessid')."' 
//                AND `account_vouchers`.`voucher_date` = '".$today."'  
//                AND `account_vouchers`.`voucher_status` = 'Active' 
//                AND account_main.account_main = 'Expenses'";
                

        $query = $this->db->query($sql);
        
        return $query->row();
        
    }
    
    function get_cash_register($t=null){
        
        $today = $this->input->post('calendar_date', TRUE);
        
        if(!isset($today) || empty($today)){
            if($t !== null ){
                $today = $t;
            } else {
                $today = date('Y-m-d');
            }
        }
       
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        //if(!empty($id_cash_register)){
        //    $this->db->where('id_cash_register', $id_cash_register);
        //} else{
            $this->db->where('cash_register_date', $today);
        //}
        $query = $this->db->get('cash_register');
        return $query->row();
        
    }
    
    function update_previous_register(){
        
        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'x5000' => $this->input->post('x5000', TRUE),
            'x1000' => $this->input->post('x1000', TRUE),
            'x500' => $this->input->post('x500', TRUE),
            'x100' => $this->input->post('x100', TRUE),
            'x75' => $this->input->post('x75', TRUE),
            'x50' => $this->input->post('x50', TRUE),
            'x20' => $this->input->post('x20', TRUE),
            'x10' => $this->input->post('x10', TRUE),
            'x5' => $this->input->post('x5', TRUE),
            'x1' => $this->input->post('x1', TRUE),
            
            'difference' => $this->input->post('totalDifference', TRUE),
            'daily_expense' => $this->input->post('daily_expense', TRUE),
            'remarks' => $this->input->post('remarks', TRUE),
            'till_amounts' => $this->input->post('till', TRUE),
            'cash_addition' => $this->input->post('cash_addition', TRUE)
        );
        
        $this->db->where('cash_register_date', $this->input->post('calendar_date', TRUE));
        $this->db->where('business_id', $this->session->userdata('businessid'));
        
        $query = $this->db->update('cash_register', $data);
        return $query;
        
        
    }
    
    function update_cash_register(){
        //echo ($this->input->post('x75', TRUE)); exit();
       $date = $this->input->post('calendar_date');
       
        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'x5000' => $this->input->post('x5000', TRUE),
            'x1000' => $this->input->post('x1000', TRUE),
            'x500' => $this->input->post('x500', TRUE),
            'x100' => $this->input->post('x100', TRUE),
            'x75' => $this->input->post('x75', TRUE),
            'x50' => $this->input->post('x50', TRUE),
            'x20' => $this->input->post('x20', TRUE),
            'x10' => $this->input->post('x10', TRUE),
            'x5' => $this->input->post('x5', TRUE),
            'x1' => $this->input->post('x1', TRUE),
            
            'difference' => $this->input->post('totalDifference', TRUE),
            'daily_expense' => $this->input->post('daily_expense', TRUE),
            'remarks' => $this->input->post('remarks', TRUE),
            'till_amounts' => $this->input->post('till', TRUE),
            'cash_addition' => $this->input->post('cash_addition', TRUE)
        );
        
        $this->db->where('cash_register_date', $date);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        
        $query = $this->db->update('cash_register', $data);
        return $query;
        
    }
    
    function insert_cash_register(){
        $date = $this->input->post('calendar_date');
        
        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'x5000' => $this->input->post('x5000', TRUE),
            'x1000' => $this->input->post('x1000', TRUE),
            'x500' => $this->input->post('x500', TRUE),
            'x100' => $this->input->post('x100', TRUE),
            'x75' => $this->input->post('x75', TRUE),
            'x50' => $this->input->post('x50', TRUE),
            'x20' => $this->input->post('x20', TRUE),
            'x10' => $this->input->post('x10', TRUE),
            'x5' => $this->input->post('x5', TRUE),
            'x1' => $this->input->post('x1', TRUE),
            'remarks' => $this->input->post('remarks', TRUE),
            'cash_register_date' => $date,
            'till_amounts' => $this->input->post('till', TRUE),
            'cash_addition' => $this->input->post('cash_addition', TRUE)
        );
        
        $this->db->insert('cash_register', $data);
        return $this->db->insert_id();
        
    }
    
    function get_cash_voucher($t = null){
        
        $today = $this->input->post('calendar_date', TRUE);
        
        if(!isset($today) || empty($today)){
            if($t !== null ){
                $today = $t;
            } else {
                $today = date('Y-m-d');
            }
        }
        
        $business_id = $this->session->userdata('businessid');
        
        $sub_query1 = ""
                . "SELECT ifnull(SUM(amount),0) FROM order_vouchers "
                . "WHERE payment_mode = 'Cash'  AND "
                . "date_format(voucher_date, '%Y-%m-%d') = '$today' AND "
                . "business_id = $business_id";
        
        $sub_query2 = ""
                . "SELECT ifnull(SUM(amount),0) FROM order_vouchers "
                . "WHERE payment_mode = 'Card' AND "
                . "date_format(voucher_date, '%Y-%m-%d') = '$today' AND "
                . "business_id = $business_id";
        
        $sub_query3 = ""
                . "SELECT ifnull(SUM(amount),0) FROM order_vouchers "
                . "WHERE payment_mode = 'Check' AND "
                . "date_format(voucher_date, '%Y-%m-%d') = '$today' AND "
                . "business_id = $business_id";
        
        
        $this->db->select("ifnull(SUM(amount),0) AS totalVoucherAmount, "
                . "($sub_query1) AS Cash, "
                . "($sub_query2) AS Card, "
                . "($sub_query3) AS Checks "
                . "", False);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('date_format(voucher_date,"%Y-%m-%d") =', $today);
        $query = $this->db->get('order_vouchers');
        //echo $query; exit();
        return $query->row();
        
    }
    
    function get_today_cash_info($t=null){
        
        $today = $this->input->post('calendar_date', TRUE);
       
        if(!isset($today) || empty($today)){
            if($t !== null ){
                $today = $t;
            } else {
                $today = date('Y-m-d');
            }
        }
        
        $datetime = new DateTime($today);
        $datetime->modify('+1 day');

        $tomorrow = $datetime->format('Y-m-d H:i:s');

        $business_id = $this->session->userdata('businessid');
        
        if($this->session->userdata('auto_voucher')=='Yes'){
            $cc_tip = $this->accounting_model->get_event_account(1, 'cc_tip');
            $cc_tip_account = $cc_tip->account_head_id;
            
            $cash = $this->accounting_model->get_event_account(1, 'paid_cash');
            $cash_account = $cash->account_head_id;
            
        }
        //invoice total
        $sub_query1 = ""
                . "SELECT SUM(balance) FROM invoice "
                . "WHERE "
                . "date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid' AND ifnull(reference_invoice_number,'') = ''";
        //balance
        $sub_query2 = ""
                . "SELECT SUM(paid_amount) FROM invoice "
                . "WHERE reference_invoice_number != '' AND "
                . "date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        //services
        $sub_query3 = ""
                . "SELECT SUM(total_payable) FROM invoice "
                . "WHERE invoice_type = 'service'   AND reference_invoice_number = '' And "
                . "date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        //sale
        $sub_query4 = ""
                . "SELECT SUM(total_payable) FROM invoice "
                . "WHERE invoice_type = 'sale' AND reference_invoice_number = '' AND "
                . "date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
       

        //Cash changing paid_amount to paid_cash
        $sub_query5 = "";
           // if($this->session->userdata('auto_voucher')=='Yes'){
           //     $sub_query5 .= "select sum(ifnull(debit,0))-sum(ifnull(credit,0)) as 'Cash' from account_vouchers
            //        join account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
            //        where account_voucher_detail.account_head_id = ". $cash_account. " and account_vouchers.voucher_status = 'Active'
            //        and date_format(voucher_date, '%Y-%m-%d')='". $today ."' and business_id=".$business_id."";
            //} else {
                $sub_query5 .="select sum(ifnull(casha,0) + ifnull(cashb,0) + ifnull(cashc,0)  + ifnull(cashd,0)) as 'Cash' from (
                    SELECT ifnull(SUM(paid_cash),0) as 'casha' 
                    FROM invoice WHERE payment_mode in ('Cash','Mixed') AND date(invoice_date) = '".$today."' 
                    AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ) a, (
                    select sum(ifnull(visit_advance.advance_amount,0)) as 'cashb' From visit_advance
                    join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id 
                    WHERE visit_status <> 'canceled' AND date(visit_advance.advance_date)= '".$today."'
                    And visit_advance.advance_mode='cash'                    
                    AND business_id = ".$business_id.") b, (
                    SELECT SUM(ifnull(retained_amount,0)) as 'cashc' 
                    FROM invoice WHERE payment_mode in ('Cash','Mixed') and paid_cash>0 
                    AND date(invoice_date)= '".$today."'
                    AND business_id = ".$business_id." AND invoice_status = 'valid'
                    ) c, (
                    SELECT sum(returnamount) as 'cashd' FROM invoice 
                    where payment_mode != 'Mixed' and paid_cash > 0 and date(invoice_date) = '".$today."' and business_id=".$business_id." 
                    and invoice_status='valid') d
                    ";
         //   }
        //Card changing paid_amount to paid_card
        $sub_query6 = ""
                ."select sum(carda + cardb + cardc) as 'Card' from (
                    SELECT ifnull(SUM(paid_card),0)  as 'carda' 
                    FROM invoice WHERE payment_mode in ('Card','Mixed') AND date(invoice_date)= '".$today."'
                    AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ) a, (
                    select ifnull(sum(visit_advance.advance_amount),0) + ifnull(sum(visit_advance.advance_cc_charge),0) as 'cardb' From visit_advance
                    join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    WHERE visit_status <> 'canceled' AND date(visit_advance.advance_date)= '".$today."'
                    And visit_advance.advance_mode='card'                    
                    AND business_id = ".$business_id.") b, (
                    SELECT ifnull(SUM(retained_amount),0) as 'cardc' 
                    FROM invoice WHERE payment_mode = 'Card' AND date(invoice_date) = '".$today."'
                    AND business_id = ".$business_id." AND invoice_status = 'valid'     
                    ) c
                    ";
       
        //Check changing paid_amount to paid_check
        $sub_query7 = ""
                ."select sum(checka + checkb + checkc) as 'Check' from (
                    SELECT ifnull(SUM(paid_check),0) as 'checka' 
                    FROM invoice WHERE payment_mode = 'Check' AND date(invoice_date) = '".$today."'
                    AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ) a, (
                    select ifnull(sum(visit_advance.advance_amount),0) as 'checkb' From visit_advance
                    join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
                    WHERE visit_status <> 'canceled' AND date(visit_advance.advance_date) = '".$today."'
                    And visit_advance.advance_mode='check'                    
                    AND business_id = ".$business_id.") b, (
                    SELECT ifnull(SUM(retained_amount),0) as 'checkc' 
                    FROM invoice WHERE payment_mode = 'Check' AND date(invoice_date)= '".$today."'
                    AND business_id = ".$business_id." AND invoice_status = 'valid'     
                    ) c
                    ";
        //advance adjusted
        $sub_query8 = ""
                . "SELECT SUM(advance_amount) FROM invoice "
                . "WHERE "
                . "date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //Todays Sale
        $sub_query9 = ""
                . "SELECT SUM(gross_amount) FROM invoice "
                . "WHERE reference_invoice_number = ''  AND "
                . "date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //totalVouchers changing paid_amount to paid_voucher
        $sub_query10 = ""
                . "SELECT SUM(paid_voucher) FROM invoice "
                . "WHERE payment_mode = 'Voucher' AND "
                . "date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        
        //totalAdvance from visit_advance
        $sub_query11 = ""
                . "SELECT SUM(visit_advance.advance_amount) FROM visit_advance join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id "
                
                . "WHERE visit_status != 'canceled' AND visit_status != 'cancelled' AND "
                . "date(visit_advance.advance_date) = '$today' AND "
                . "customer_visits.business_id = $business_id and ifnull(customer_id,0) > 0";
        
//        $accountheadid=214;
//        $sub_query11 = ""                
//                . "SELECT SUM(account_voucher_detail.credit) FROM account_vouchers join account_voucher_detail on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id "                
//                . "WHERE account_vouchers.voucher_status = 'Active' AND "
//                . "account_vouchers.voucher_date >= '$today' AND account_vouchers.voucher_date < '$tomorrow' AND "
//                . "account_vouchers.business_id = $business_id  and account_voucher_detail.account_head_id = $accountheadid ";
//      
//        
        
        //retained amount
        $sub_query12 = "" 
                . "SELECT SUM(retained_amount) FROM invoice "
                . "WHERE date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //cctip amount
        $sub_query13 = "" ;
                if($this->session->userdata('auto_voucher')=='Yes'){        
                    $sub_query13 .= "select sum(ifnull(credit,0)) as 'SUM(cc_tip)' from account_vouchers
                    join account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                    where account_voucher_detail.account_head_id = ". $cc_tip_account. " and account_vouchers.voucher_status = 'Active'
                    and date(voucher_date)='". $today ."' and business_id=".$business_id."";
                   
                   // echo $sub_query13; exit();
                } else {
                   $sub_query13 .= "SELECT SUM(cctip) FROM invoice 
                    WHERE date(invoice_date)=  '".$today."' AND 
                    business_id = ".$business_id." AND invoice_status = 'valid' ";
                }
        //cccharge amount
        $sub_query14 = "" 
//                . "SELECT SUM(cc_charge) FROM invoice "
//                . "WHERE date(invoice_date) = '$today' AND "
//                . "business_id = $business_id AND invoice_status = 'valid'";
        
                    ."SELECT a.cccharge_a + b.cccharge_b + c.cccharge_c as cc_charge "
                    ."from(SELECT ifnull(SUM(cc_charge),0) as cccharge_a FROM invoice " 
                    ."WHERE date(invoice_date) =  '".$today."' AND  "
                    ."business_id = ".$business_id." AND invoice_status = 'valid') as a, "
                    ."(SELECT ifnull(SUM(advance_cc_charge),0) as cccharge_b  "
                    ."FROM visit_advance "
                    ."join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id  "
                    ."WHERE date(visit_advance.advance_date) =  '".$today."' AND  "
                    ."business_id = ".$business_id." AND customer_visits.visit_status in('open','invoiced')) as b, "
                    ."(SELECT ifnull(SUM(voucher_cccharge),0) as cccharge_c "
                    ."FROM order_vouchers "
                    ."WHERE date(voucher_date) =  '".$today."' AND business_id = ".$business_id." AND voucher_status!='cancelled') as c ";
        
        //extra amount
        $sub_query15 = "" 
                . "SELECT SUM(other_charges) FROM invoice "
                . "WHERE date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        //extra taxes
        $sub_query16 = "" 
                . "SELECT SUM(tax_total) FROM invoice "
                . "WHERE date(invoice_date) = '$today' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //Training amount
        $sub_query17 = "" 
                . "SELECT SUM(paid_cash) FROM program_invoices "
                . "WHERE date(payment_date) >= '$today' AND "
                . "business_id = $business_id AND program_invoice_status = 'Active'";
        $sub_query18 = "" 
                . "SELECT SUM(paid_amount) FROM program_invoices "
                . "WHERE date(payment_date) = '$today' AND "
                . "business_id = $business_id AND program_invoice_status = 'Active'";
        $sub_query19 = "" 
                . "SELECT SUM(paid_card) FROM program_invoices "
                . "WHERE date(payment_date) = '$today' AND "
                . "business_id = $business_id AND program_invoice_status = 'Active'";
        $sub_query20 = "" 
                . "SELECT SUM(paid_check) FROM program_invoices "
                . "WHERE date(payment_date) = '$today' AND "
                . "business_id = $business_id AND program_invoice_status = 'Active'";
        $sub_query21="SELECT sum(returnamount) as 'returncash' FROM invoice 
                    where date(invoice_date) = '".$today."' and business_id=".$business_id." 
                    and invoice_status='valid'";
        $this->db->select("SUM(paid_amount) AS totalCash, "
                . "($sub_query1) AS totalBalance, "
                . "($sub_query2) AS totalRecovery, "
                . "($sub_query3) AS totalService, "
                . "($sub_query4) AS totalRetail, "
               
                . "($sub_query5) AS Cash, "
                . "($sub_query6) AS Card, "
                . "($sub_query7) AS Checks, "
                . "($sub_query8) AS AdvAdj, "
                . "($sub_query9) AS totalSale, "
                . "($sub_query10) AS totalVoucher, "  
                
                . "($sub_query11) AS totalAdvance, "
                . "($sub_query12) AS totalRetained, "
                . "($sub_query13) AS totalCCTip, "
                . "($sub_query14) AS totalCCCharge, "
                . "($sub_query15) AS totalExtra, " 
                . "($sub_query16) AS totalTax,"
                . "($sub_query17) AS totalTrainingCash, "
                . "($sub_query18) AS totalTraining, "
                . "($sub_query19) AS totalTrainingCard, "
                . "($sub_query20) AS totalTrainingCheck, "
                . "($sub_query21) AS totalReturnCash "
                . "");
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('date(invoice_date) =', $today);        
        $this->db->where('invoice_status', 'valid');
        $this->db->where('payment_mode', 'Cash');
        
        $query = $this->db->get('invoice');
        //echo $query; exit();
        return $query->row();
        
    }
    
    function get_advance_breakup($t=null){
        $today = $this->input->post('calendar_date', TRUE);
       
        if(!isset($today) || empty($today)){
            if($t !== null ){
                $today = $t;
            } else {
                $today = date('Y-m-d');
            }
        }
        $sql="select CONCAT(id_customer_visits,id_visit_advance) id_customer_visits, 
            customer_name, adv_mode advance_mode, adv_amount advance_amount, advance_cc_charge, 
            service_category.service_category, business_services.service_name, business_services.service_rate, advance_user
                from customer_visits
                join (
                        select id_visit_advance, customer_visit_id, sum(advance_amount) adv_amount, 
                        advance_mode adv_mode, advance_inst adv_inst, advance_date adv_date, advance_user, 
                        sum(advance_cc_charge) as advance_cc_charge
                        from visit_advance                        
                        where date_format(advance_date,'%Y-%m-%d') ='".$today."'
                        group by advance_mode, advance_inst, advance_date, id_visit_advance
                    ) va on customer_visits.id_customer_visits = va.customer_visit_id
            join visit_services on customer_visits.id_customer_visits = visit_services.customer_visit_id
            and visit_services.visit_service_status='Active' 
            join customers on customers.id_customers = customer_visits.customer_id
            join business_services on business_services.id_business_services = visit_services.service_id
            join service_category on business_services.service_category_id = service_category.id_service_category
            where customer_visits.business_id = ".$this->session->userdata('businessid')."
            and customer_visits.visit_status != 'canceled'  group by CONCAT(id_customer_visits,id_visit_advance), service_category, business_services.service_name, service_rate";
            //echo $sql; exit();
            $query = $this->db->query($sql);
            
            return $query->result_array();
        
    }
    
    
    function get_voucher_breakup($t=null){
        $today = $this->input->post('calendar_date', TRUE);
       
        if(!isset($today) || empty($today)){
            if($t !== null ){
                $today = $t;
            } else {
                $today = date('Y-m-d');
            }
        }
        $sql="SELECT * , order_vouchers.created_by as created_by
        FROM order_vouchers
        join customers on customers.id_customers = order_vouchers.customer_id
        where order_vouchers.business_id = ".$this->session->userdata('businessid')."
        and date_format(voucher_date, '%Y-%m-%d') ='".$today."'";
            
            $query = $this->db->query($sql);
            
            return $query->result_array();
        
    }
    
    function get_yesterday_till_amount($t = null){
        
        
        $today = $this->input->post('calendar_date', TRUE);
        
        if(!isset($today) || empty($today)){
            if($t !== null ){
                $today = $t;
            } else {
                $today = date('Y-m-d');
            }
        }
        
        $datetime = new DateTime($today);
        $datetime->modify('-1 day');
        
        $yesterday = $datetime->format('Y-m-d');
        
        $this->db->select("id_business, ifnull(till_amounts,0) as till_amounts", False);
        $this->db->join("cash_register", "business.id_business = cash_register.business_id AND cash_register_date ='".$yesterday."'", "left");
        $this->db->where('id_business', $this->session->userdata('businessid'));
        $query = $this->db->get('business');
        
        
        return $query->row();
        
    }

    function getnextinvoicenumber(){
        $this->db->select_max('id_invoice');
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        }
        $query = $this->db->get('invoice');
        
        return $query->result_array();
        
    }
    
    function disount_invoice_user_insert($invoiceid) {
        $data = array(
            'userid' => $this->db->escape_str($this->input->post('uid')),
            'name' => $this->db->escape_str($this->input->post('uname')),
            'username' => $this->db->escape_str($this->input->post('uusername')),
            'email' => $this->db->escape_str($this->input->post('uemail')),
            'invoiceid' => $invoiceid
        );
        
        $result = $this->db->insert('discount_invoice_users', $data);
        return TRUE;
    }
    
    function get_discount_user_pw(){
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('discount_password');
        
        return $query->result_array();
    }
    
    function update_invoice(){
       
       
        $business= $this->business_model->get_business_details();
        $taxperc= $this->business_model->get_tax_perc('service');
        
        $newloyaltypoints=0;
        
        $visitid=$this->input->post('visitid', TRUE);
        $service_ids=$this->input->post('serviceids', TRUE);
        $visit_service_ids=$this->input->post('visitserviceids', TRUE);
        $invoicenumber=$this->input->post('invoicenumber', TRUE);

        $invoicedate=date('Y-m-d H:i:s');
        if(defined('BACKDATEDINVOICE')){
            if(BACKDATEDINVOICE==TRUE){        
                $invoicedate=$this->input->post('invoicedate', TRUE);
            }
        }else{            
            $invoicedate=date('Y-m-d H:i:s');
        }
        
        
        $customerid=$this->input->post('customerid', TRUE);
        $customername=$this->input->post('customername',TRUE);
        $subtotal=$this->input->post('subtotal', TRUE);
        $org_subtotal=$this->input->post('org_subtotal', TRUE);
        
        $discount=$this->input->post('discount', TRUE);
        $discount_perc=$this->input->post('discount_perc', TRUE);
        
        $grosstotal=$this->input->post('grosstotal', TRUE);
        $paid=$this->input->post('paid', TRUE);
        
        $roundedadjustment= $this->input->post('roundedadjustment');
        $grandtotal=$this->input->post('grandtotal', TRUE);
        $totalpayable=$this->input->post('totalpayable', TRUE);
        
        $taxes=$this->input->post('taxes', TRUE);
        $taxtotal=$this->input->post('taxtotal', TRUE);
        $paymentmode=$this->input->post('mode', TRUE);
        $cashpaid=0;$cardpaid=0;$voucherpaid=0;$checkpaid=0;
        
        $cc_charge=$this->input->post('cc_charge', TRUE);
        $instrumentnumber = $paymentmode=="Online" ? 'Online '.$this->input->post('instrument_number', TRUE) : $this->input->post('instrument_number', TRUE);
        $balance=$this->input->post('balance', TRUE);
        $service_discount=$this->input->post('service_discount', TRUE);
        
        $discount_type=$this->input->post('discount_type', TRUE);
        $discounted_price=$this->input->post('discounted_price', TRUE);
        $service_addition=$this->input->post('service_addition', TRUE);
        $service_products=$this->input->post('service_products', TRUE);
        
        $returnamount=$this->input->post('returnamount', TRUE);
        $customer_advance=$this->input->post('customer_advance', TRUE);
        $retained_used=$this->input->post('retained_used', TRUE);
        $retained_amount_used=$this->input->post('retained_amount_used', TRUE);
        $remaining_retained=$this->input->post('remaining_retained', TRUE);
        $cctip = $this->input->post('cctip', TRUE);
        $advance_amount=$this->input->post('advance_amount',TRUE);
        $other_charges=$this->input->post('other_charges',TRUE);
        $serivce_flag=$this->input->post('service_flag',TRUE);
        $requested=$this->input->post('requested',TRUE);
       
        $coupon = $this->input->post('coupon');
        $invoice_extra = $this->input->post('invoice_extra');
        
        $return_cash = $customer_advance==='false' ? $returnamount: 0;
        
        $totalpaid= ($advance_amount+$paid)-($cctip+$cc_charge+$taxtotal);
        $paidnow=$advance_amount+$paid;
        
        //if(($paid+$advance_amount+$roundedadjustment) > $totalpayable && $customer_advance==='false'){$paid = $paid - $returnamount;}
        
        
        if($paymentmode=="Cash"){$cashpaid=$paid;}
        else if($paymentmode=="Card"){$cardpaid=$paid;}
        else if($paymentmode=="Check"){$checkpaid=$paid;}
        else if($paymentmode=="Online"){$checkpaid=$paid; $paymentmode='Check';}
        else if($paymentmode=="Voucher"){$voucherpaid=$paid;}
        else if($paymentmode=="Mixed"){
            $cashpaid=$this->input->post('cashpaid', TRUE);
            $cardpaid=$this->input->post('cardpaid', TRUE);
            $paidnow = $cashpaid+ $cardpaid;
        }
        
//        var_dump($discounted_price);
//        echo 'invoicediscount'.$discount_perc.'</br>';
//        echo 'gross'.$grosstotal.'</br>';
//        echo '$subtotal'.$subtotal.'</br>';
//        echo '$paidnow'.$paidnow.'</br>';
//        echo '$paid'.$paid.'</br>';
//        echo '$totalpayable'.$totalpayable.'</br>';
//        echo '$totalpaid'.$totalpaid.'</br>';
//        exit();
        
        //Loyalty
        $loyaltyused=$this->input->post('loyaltyused',TRUE);
        $loyaltyvalue=$this->input->post('loyaltyvalue',TRUE);
        $loyaltyenabled=$this->input->post('loyaltyenabled',TRUE);
        $sloyaltyenabled=$this->input->post('sloyaltyenabled',TRUE);
        
        if (in_array("packagetype", $serivce_flag)==false){
            if($loyaltyenabled=='Y' && $sloyaltyenabled=='Y') {
                $ra= $customer_advance==='true' ? $returnamount : 0;
                if($ra>0){
                    $ntotalpaid=(Float)$totalpaid-$ra;
                    if($ntotalpaid<0)($ntotalpaid = $ntotalpaid * -1);
                    $loyaltyearned=(Float)$ntotalpaid/ (Float)$loyaltyvalue;
                    
                }else{
                    $loyaltyearned=(Float)$totalpaid/ (Float)$loyaltyvalue;
                }
            } else {
                $loyaltyearned=0;                
            }
        } else {$loyaltyearned=0;}
        
        if($loyaltyearned < 0){$loyaltyearned=0;}
        
        
        //Get customer & visit
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->where('customer_visits.id_customer_visits', $visitid);
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $customervisits = $this->db->get('customer_visits');
        $customervisit = $customervisits->row();
        
        if($customervisit->visit_status == 'invoiced'){return 'error|Already Invoiced'; exit();}
                
        //Get visit details        
        $this->db->select('*');
        $this->db->join('business_services', 'business_services.id_business_services = visit_services.service_id');
        $this->db->join('service_category', 'service_category.id_service_category = business_services.service_category_id');
        //$this->db->join('visit_service_products', 'visit_services.id_visit_services = visit_service_products.visit_service_id', 'left');
        //$this->db->join('visit_service_staffs', 'visit_services.id_visit_services = visit_service_staffs.visit_service_id');
        $this->db->where('visit_services.customer_visit_id', $visitid);
        $this->db->where('visit_services.visit_service_status', 'Active');
        $this->db->where('visit_services.business_id', $this->session->userdata('businessid'));
        $visitdetails = $this->db->get('visit_services');
        $visittime=''; 
        foreach ($visitdetails->result() as $vd){            
            if($visittime==''){
                $visittime=$vd->visit_service_start;                
            }
        }
        
        $additional_charges=0;
        
        foreach ($service_addition as $sa){
            $additional_charges = $additional_charges + $sa;
        }

        
        //Create invoice    
        $invoice_date=$invoicedate;
        $customername=$customervisit->customer_name;
        
        $insertloyalty = true;
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){
                $insertloyalty=false;
            }
        }
        $tdiscount=0;
        foreach($service_discount as $sd){
            $tdiscount = (float)$sd;
        }
        $tdiscount = $tdiscount + (float)$discount;
        $loyaltyearned = $tdiscount==0 ? (intval($loyaltyused) == 0 ? $loyaltyearned :0) : 0;
        //echo  date_format(date_create($visittime),'Y-m-d').' '.date('H:i:s');
        $data = array(
            'customer_id'=>$customerid,
            'invoice_number'=>$invoicenumber,
            'business_id'=>$this->session->userdata('businessid'),
            'customer_name'=> $customervisit->customer_name,
            'customer_cell'=> $customervisit->customer_cell,
            'customer_email'=> $customervisit->customer_email,
            'customer_address'=> $customervisit->customer_address,
            'tax_total'=>$taxtotal,
            'paid_amount' => $paid,
            'paid_cash' => $cashpaid,
            'paid_card' => $cardpaid,
            'paid_voucher' => $voucherpaid,
            'paid_check' => $checkpaid,
            'discount' => $discount,
            'gross_amount' => $grosstotal + $taxtotal,
            'gross_wo_tax' => $grosstotal,
            'net_amount' => $grandtotal,
            'visit_id' => $visitid,
            'sub_total' => $subtotal,
            'payment_mode'=>$paymentmode,
            'instrument_number'=>$instrumentnumber,
            'cc_charge'=>$cc_charge,
            'balance'=>$balance,
            'is_recovery' => $balance > 0 ? 'Yes' : 'No',
            'discount_remarks' => $this->input->post('discount_remarks'),
            'discount_reason' => $this->input->post('invoice_discount_type'),            
            'returnamount' => $customer_advance==='true' ? 0 : $returnamount,
            'loyalty_used'=> $insertloyalty==true ? $loyaltyused : 0,
            'loyalty_earned'=> $insertloyalty==true ? $loyaltyearned : 0,
            'visit_time'=> $visittime,
            
            'invoice_date'=>$invoice_date,

            'advance_amount'=>$advance_amount,
            'advance_inst'=>$customervisit->advance_inst,
            'other_charges'=>$other_charges,
            
            'retained_used'=>$retained_used,
            'retained_amount_used'=>$retained_amount_used,
            'retained_amount'=>$customer_advance==='true' ? $returnamount : 0,
            'cctip'=>$cctip,            
            'total_payable'=>$totalpayable-($cctip+$cc_charge),
            'created_by' => $this->session->userdata('username'),
            'remarks' => $this->input->post('remarks', TRUE),
            'service_addition' => $additional_charges,
            'invoice_extra' => $invoice_extra
        );

        $this->db->insert('invoice', $data);
        $invoiceid =  $this->db->insert_id();
        
        //make sure invoice number is correct
        $today=date('Y-m-d');
        
        $seq=1;        
        $sql = "select max(invoice_seq)+1 as 'seq'
            from invoice where day(invoice_date)= day('".$today."') and invoice_status='valid' 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}
        
        if($paymentmode!=='Card' && $paymentmode!=='Mixed' && $business[0]['sh_hide']=='Yes'){
            if(isset($business[0]['s_min_sh'])){
               if($totalpayable > $business[0]['s_min_sh'] || $totalpayable == 0){
                   $seq=0;
               }
           } else {
               $seq=0;
           }
        }
        
        $update_invoice = array(
            'invoice_number' => date('Y-m').'-'.$invoiceid,
            'invoice_seq' => $seq
        );            
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        
        
        
        if(null!==$coupon && $coupon!==''){
            $this->db->where('coupon_number',$coupon);
            $this->db->set('coupon_status','used');
            $this->db->set('invoice_id', $invoiceid);
            $this->db->update('coupons');
        }
        
        //////////////////
        
        ///update customer advance
        if ($customer_advance==='true'){
            $newval=$returnamount + $remaining_retained;
        } else {
            $newval=$remaining_retained;
        }
        $this->db->set('customer_advance', $newval);
        $this->db->where('id_customers',$customerid);
        $this->db->update('customers');
        //////////
        
        $this->disount_invoice_user_insert($invoiceid);
       
        
        
        //Update Loyalty
        if($loyaltyenabled=='Y' && $sloyaltyenabled=='Y'){
            $this->db->select('loyalty_points');
            $this->db->where('id_customers =',$customerid);
            $existingpoint = $this->db->get('customers');
            $existingpoints = $existingpoint->result_array();
            
            $newloyaltypoints=(Float)$existingpoints[0]['loyalty_points'];
            if($loyaltyused>0){
                $newloyaltypoints= (Float)$existingpoints[0]['loyalty_points'] - $loyaltyused;
            }
            $calloyaltypoints=0;
            if($totalpaid>0){
                $calloyaltypoints = $totalpaid / $loyaltyvalue;
            }
            $newloyaltypoints=$newloyaltypoints+$calloyaltypoints;
            
            $this->db->where('id_customers = ', $customerid);
            $this->db->update('customers', array('loyalty_points'=>$newloyaltypoints));        
            
        }
        
        
        //Insert Invoice Products used
        foreach ($visitdetails->result() as $vd){
            //Insert Invoice Products selected at time of invoicing only
            foreach($service_products as $service_product){
                if(null != $service_product){
                    foreach($service_product as $product){
                       // echo $product;
                        if(null != $product && $product != ''){
                            $this->db->select('*');
                            $this->db->join('visit_services', 'id_visit_services = visit_service_id');
                            $this->db->where('product_id',$product);
                            $this->db->where('visit_service_products.customer_visit_id',$visitid);
                            $this->db->where('visit_service_id',$vd->id_visit_services);
                            $this->db->where('visit_services.visit_service_status','Active');
                            $q = $this->db->get('visit_service_products');
                            //echo $q;
                            $visit_product=$q->row();
                           // print_r($visit_product);
                            if($visit_product!=null && isset($visit_product->product_id)){
                                $data = array(
                                    'business_id' => $this->session->userdata('businessid'),
                                    'invoice_id' => $invoiceid,
                                    'customer_visit_id' => $visitid,
                                    'service_id' => $vd->service_id,
                                    'service_name' => $vd->service_name,
                                    'product_id' => $visit_product->product_id,
                                    'product_name' => $visit_product->product_name,
                                    'product_qty' => $visit_product->product_qty,
                                    'product_unit' => $visit_product->product_unit
                                );
                                $this->db->insert('invoice_visit_products', $data);
                            }
                        }
                    }
                }
            }
            

            
        }
        
        //insert invoice taxes
        if(isset($taxes)){
            foreach($taxes as $tax){
                $data=array(
                    'invoice_id'=>$invoiceid,
                    'business_id'=>$this->session->userdata('businessid'),
                    'invoice_tax_name'=>$tax['taxname'],
                    'invoice_tax'=>$tax['tax']
                );
                $this->db->insert('invoice_taxes', $data);
            }
        }
        
        $k=0;
        $totalservicediscount=0;
        
        $remainingsub=$subtotal - $discount; $remainingpaid=$paid+$advance_amount; 
        foreach($visit_service_ids as $service_id){
            //Get visit services
            $this->db->select('*');
            $this->db->join('business_services bs', 'bs.id_business_services = vs.service_id');
            $this->db->where('vs.customer_visit_id', $visitid);
            $this->db->where('vs.id_visit_services', $service_id); //added
            $this->db->where('vs.visit_service_status', 'Active');
            $this->db->where('vs.business_id', $this->session->userdata('businessid'));
            $visit_services1 = $this->db->get('visit_services vs');

            //$total_services=$visit_services1->num_rows();

            $visit_services = $visit_services1->row();
        
        
       // foreach($visit_services as $service){
            
            //Get package type
            if($visit_services->service_flag === 'servicetype'){
                $this->db->select('*, , visit_services.service_name as thisservice');
                $this->db->join('business_services', 'business_services.id_business_services = visit_services.service_id');
                $this->db->join('service_category', 'service_category.id_service_category = business_services.service_category_id');
                $this->db->join('service_type', 'service_type.id_service_types = service_category.service_type_id');
                $this->db->where('visit_services.customer_visit_id', $visitid);
                $this->db->where('visit_services.id_visit_services', $visit_services->id_visit_services);
                $this->db->where('visit_services.business_id', $this->session->userdata('businessid'));
                $this->db->where('visit_services.visit_service_status','Active');
                $servicetype1 = $this->db->get('visit_services');
                $servicetype2 = $servicetype1->row();
            } else{
                $this->db->select('*, , visit_services.service_name as thisservice');
                $this->db->join('business_services', 'business_services.id_business_services = visit_services.service_id');
                $this->db->join('package_services', 'package_services.service_id = business_services.id_business_services');
                $this->db->join('package_category', 'package_category.id_package_category = package_services.package_category_id');
                $this->db->join('package_type', 'package_category.package_type_id = package_type.id_package_type');
                $this->db->where('visit_services.customer_visit_id', $visitid);
                $this->db->where('visit_services.id_visit_services', $visit_services->id_visit_services);
                $this->db->where('visit_services.business_id', $this->session->userdata('businessid'));
                $this->db->where('package_services.package_category_id', $visit_services->id_service_category); //added 1/9/2017 owais
                $this->db->where('visit_services.visit_service_status','Active');
                $servicetype1 = $this->db->get('visit_services');
                $servicetype2 = $servicetype1->row();
            }
            
            //Get visit service products        
            $this->db->select('*');
            $this->db->join('visit_services','id_visit_services = visit_service_id');
            $this->db->where('visit_service_products.customer_visit_id', $visitid);
            $this->db->where('visit_service_id', $visit_services->id_visit_services);
            $this->db->where('visit_services.visit_service_status','Active');
            $vs_products = $this->db->get('visit_service_products');
            $products = "";
            foreach ($vs_products->result() as $vsp){
                $products .= $vsp->product_name."|";
            }
            
            //Get visit service staffs   
            $this->db->select('*');            
            $this->db->where('customer_visit_id', $visitid);
            $this->db->where('visit_service_id', $visit_services->id_visit_services);
            $this->db->where('visit_service_staff_status', 'Active');
            $vs_staff = $this->db->get('visit_service_staffs');
            $staff_count = $vs_staff->num_rows();
            $staffs = "";
            
            
            ///Calculate commission and paid ratios
            //Service Weights
            if($subtotal > 0){ 
                $service_weight=($discounted_price[$k]*100)/$subtotal;
            } else{
                $service_weight = 0;
            }
            
            //Calculate Wieghted Price            
            $service_price = ($totalpayable-$cctip-$cc_charge)*$service_weight/100;
            if($service_price<0){$service_price*-1;}//keep it positive
            //Calculate Paid
            $service_paid = ($totalpaid)*$service_weight/100;
            if($service_paid<0){$service_paid*-1;}//keep it positive
            
            //Calculate Commission
//            $commission = ($service_paid * $servicetype2->commission_perc) / 100;    
//            $commission_ratio =$commission/$staff_count;
            
            
            ///Calculate final discounted price for this service
            if(strpos($servicetype2->thisservice, '(nc)')!==false){
                $serviceprice=0;
            } else {
                $serviceprice=$servicetype2->service_rate;                
            }
            
            $priceafterdiscount=round(floatval($serviceprice) + floatval($service_addition[$k]) - floatval($service_discount[$k]),2);
            $invoicediscount=($priceafterdiscount*$discount_perc)/100;
            $finalprice=  $priceafterdiscount - $invoicediscount;
            $taxonoriginalprice= round(((floatval($servicetype2->service_rate) + floatval($service_addition[$k])) * $taxperc->tax_percentage)/100,2);
            
            ///Calculate paid amount for this service
            if($advance_amount>$grosstotal && $paid==0){
                $sPaidAmount= $finalprice;
            }else{
                $sPaidAmount = round(($paid + $advance_amount) - ($taxtotal+$cc_charge+$cctip+$other_charges),4);
            }
            if($grosstotal>0){$sPercOfGross = round(($finalprice*100)/$grosstotal,4);}else{$sPercOfGross=0;}
            $sPercPaidForService = round($sPaidAmount*$sPercOfGross/100,4);
            if($sPercPaidForService<0){$sPercPaidForService=0;}
             //Calculate Commission
           
            $commission = round($sPercPaidForService * ($servicetype2->commission_perc / 100),2);
            
            $totalservicediscount = $totalservicediscount + $service_discount[$k];
            
            
            
            ///Just put the paid amount in service (Trying out)
            $priceafterdiscount=round(floatval($serviceprice) + floatval($service_addition[$k]) - floatval($service_discount[$k]),2);
            $invoicediscount=($priceafterdiscount*$discount_perc)/100;
            $finalprice=  $priceafterdiscount - $invoicediscount;
            $taxonoriginalprice= round(((floatval($serviceprice) + floatval($service_addition[$k])) * $taxperc->tax_percentage)/100,2);
            $taxonfinalprice= round((floatval($finalprice) * $taxperc->tax_percentage)/100,2);
            
            $service_paid=0;
            $thisinvoicediscount = ($priceafterdiscount*$discount_perc)/100;
            $thisservice = ($serviceprice + $service_addition[$k]) - $service_discount[$k] - $thisinvoicediscount;
            
            
            if($thisservice < $remainingpaid){
                $service_paid=$thisservice;
            }else{
                if($remainingpaid>0){
                    $service_paid=$remainingpaid;
                } else {
                    $service_paid=0;
                }
            }
            
            $remainingsub = $remainingsub - $thisservice;
            $remainingpaid = $remainingpaid-$service_paid;
            
            $commission = ($service_paid * $servicetype2->commission_perc) / 100;
            $commission = round($commission, 2);
            
            $finaltax=0;
            if(isset($business[0]['tax_mode']) && $business[0]['tax_mode']=='after'){
                $finaltax = $taxonfinalprice;
            }else{
                $finaltax = $taxonoriginalprice;
            }
            
            //insert invoice details
            $services= array(
                'invoice_id' => $invoiceid,
                'business_id' => $this->session->userdata('businessid'),
                'service_id' => $servicetype2->id_business_services,
                'service_type' => $servicetype2->service_type,
                'service_category' => $servicetype2->service_category,
                'service_name' => $servicetype2->service_name,
                'staff' => '',
                'products' => $products,
                'price' => $serviceprice,
                'discount' => $service_discount[$k],
                'discount_type' => ($visit_services->membership == 'Yes') ? 'Membership' : $discount_type[$k],
                //'discounted_price' => $discounted_price[$k],
                //'discounted_price' => $service_price,
                'discounted_price' => $priceafterdiscount,
                'invoice_discount' => $invoicediscount,
                'service_addition' => $service_addition[$k],
                'final_price' => $finalprice,
                
                'taxes' => $finaltax,
                'paid'=>$service_paid,
                //'paid'=>$sPercPaidForService,
                
                'detail_visit_date'=>$servicetype2->visit_service_start,
                'service_flag'=>$servicetype2->service_flag,
                'requested'=>$requested[$k],
                'membership'=>$visit_services->membership,
                'visit_service_id'=>$visit_service_ids[$k]
            );
            $this->db->insert('invoice_details', $services);
            $invoice_detail_id=$this->db->insert_id();
            
            //insert invoice staff
            foreach($vs_staff->result() as $vss){
                $staffs .= $vss->staff_name."|";
                
                $services = array(
                    'invoice_id' => $invoiceid,
                    'invoice_detail_id' => $invoice_detail_id,
                    'business_id' => $this->session->userdata('businessid'),
                    'service_type' => $servicetype2->service_type,
                    'service_category' => $servicetype2->service_category,
                    'service_name' => $servicetype2->service_name,
                    'staff_name' => $vss->staff_name,
                    'staff_id' => $vss->staff_id,
                    'price' => $serviceprice / $staff_count,
                    'discount' => $service_discount[$k] / $staff_count,
                    'discounted_price' => $priceafterdiscount/$staff_count,
                    'invoice_discount' => $invoicediscount/$staff_count,
                    'service_addition' => $service_addition[$k]/$staff_count,
                    'final_price' => $finalprice/$staff_count,
                    //'paid' => $sPercPaidForService/$staff_count,
                    'paid'=>$service_paid/$staff_count,
                    //'commission' => $commission/$staff_count,
                    'commission' => $vss->additional_staff == 'No' ?  round(($service_paid/$staff_count) * $servicetype2->commission_perc/100, 2) : round(($service_paid/$staff_count) * $servicetype2->helper_perc/100, 2),
                    'requested'=>$requested[$k],                    
                    'additional_staff'=>$vss->additional_staff,
                    'visit_staff_id'=>$vss->id_visit_service_staffs
                );
                $this->db->insert('invoice_staff', $services);
                
                //update commissions
                $staffservice = array(
                    'invoice_id' => $invoiceid,
                    'invoice_detail_id' => $invoice_detail_id,
                    'business_id' => $this->session->userdata('businessid'),
                    'visit_id' => $visitid,
                    'staff_id' => $vss->staff_id,
                    'service_id' => $servicetype2->id_business_services,
                    'staff_name' => $vss->staff_name,
                    'service_type' => $servicetype2->service_type,
                    'service_category' => $servicetype2->service_category,
                    'service_name' => $servicetype2->service_name,
                    'price' => $serviceprice / $staff_count,
                    'discount' => $service_discount[$k] / $staff_count,
                    //'discounted_price' => $discounted_price[$k]/$staff_count,
                    
                    'discounted_price' => $serviceprice/$staff_count,
                    'staff_commission' => $commission/$staff_count,
                    'paid' => $service_paid/ $staff_count,
                    
                    'service_flag'=>$servicetype2->service_flag,
                    'requested'=>$requested[$k]
                );
                $this->db->insert('staff_services', $staffservice);
            }

            $k++;
        }
        

        ///create sale account voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(1);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Service Sale Voucher against invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $totalpayable,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername,
                'voucher_type'=>2,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'service'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount= $customer_advance==='true' ?  $cashpaid+ $returnamount : $cashpaid ;}
                
                if($debit[2]=="paid_card" && $cardpaid > 0){$debitamount= $customer_advance==='true' ?  $cardpaid+ $returnamount : $cardpaid ;}
                
                if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount= $customer_advance==='true' ?  $checkpaid+ $returnamount : $checkpaid ;}
                if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $voucherpaid;}
                
                if($debit[2]=="balance"){$debitamount= $balance;}
                if($debit[2]=="sale_discount_service"){
                    //if($loyaltyused==0){ //only if discount is not because of loyalty
                        $debitamount= $totalservicediscount + $discount;
                    //}
                }
                if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}
                if($debit[2]=="advance_adjusted"){
                    if($retained_amount_used==0 && $advance_amount > 0){
                        $debitamount= $advance_amount;
                    } elseif($retained_amount_used>0 && $advance_amount > 0) {
                        $debitamount= $advance_amount-$retained_amount_used;                        
                    } 
                }    
                if($debit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment < 0){
                        $debitamount=$roundedadjustment*-1; 
                    }
                    
                }
                
                if(defined('LOYALTY_VOUCHER')){                    
                    if(LOYALTY_VOUCHER==TRUE){
                        if($debit[2]=="loyalty_amount"){
                            if($loyaltyused>0){ //if discount is actually loyalty points
                                $debitamount= 0;
                            
                                //see if we need to bring the loyalty points in from HO
                                $my_business = $this->check_if_ho();
                                //bring the points from ho
                                if($my_business != $this->session->userdata('businessid')){
                                    $this->bring_in_ho_points($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                                }   

                                $this->create_loyalty_used_voucher($this->session->userdata('businessid'),$loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                                $debitamount= 0; // make sure
                            }                 
                        }
                    }
                }

                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                
                if($credit[2]=="grosstotal_service"){$creditamount= $org_subtotal + $other_charges;}
                
                if($credit[2]=="sales_tax"){$creditamount= $taxtotal;}
                if($credit[2]=="cc_fee"){$creditamount= $cc_charge;}
                if($credit[2]=="retained_amount"){$creditamount= $customer_advance==='true' ? $returnamount: 0;}
                if($credit[2]=="cc_tip"){$creditamount= $cctip;}
                
                if($paidnow > $totalpayable+$roundedadjustment){                    
                    if($credit[2]=="return_cash"){$creditamount= $customer_advance==='false' ? $returnamount: 0;}
                }

                if($credit[2]=="rounded_adjustment"){
                    if($roundedadjustment > 0){
                        $creditamount=$roundedadjustment; 
                    }
                }
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        

            ///create loyalty voucher
            if(defined('LOYALTY_VOUCHER')){                    
                if(LOYALTY_VOUCHER==TRUE){
                    if($loyaltyearned > 0){
                        $my_business= $this->check_if_ho();            
                        $this->add_loyalty_points_ho($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                    }
                }
            }
        }
        //update customer visit (mark as invoiced)
        
        $this->db->set('visit_status', 'invoiced');
        $this->db->set('invoice_seq', $seq);
        $this->db->where('id_customer_visits', $visitid);
        $this->db->update('customer_visits');

        //update last update date        
        $update_service = array(
            'update_date' => date('Y-m-d H:i:s')
        );
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'customer_visit_id' => $visitid
        ));
        $this->db->update('visit_services', $update_service);

        $mypaid = $customer_advance==='true' ? $advance_amount + $returnamount + $paid : $advance_amount + $paid;
        return $invoiceid.'|'.$loyaltyearned.'|'.$totalpayable.'|'.$mypaid.'|'.$balance;
    }
    
    function check_if_ho(){
        $my_business= $this->session->userdata('businessid');
        if($this->session->userdata('common_products')=='Yes'){
            $sqlb="select id_business from business where business.ho='Yes'";
            $b=$this->db->query($sqlb);
            $ho=$b->row();
            if($ho){
                $my_business= $ho->id_business;
            }
        }
       
        return $my_business;
    }

    function bring_in_ho_points($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid){
        ///create voucher in ho
        $data = array( 
            'business_id' => $my_business,
            'description' => 'Loyalty Points Moved to Branch '.$this->session->userdata('businessid').' against invoice ' . $invoiceid . ' on '. date('d-m-Y').', For '.$customername.' customer ID : '. $customerid,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $loyaltyused,
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> '1',
            'cost_center_name'=> 'Front Desk',
            'business_partner'=> 1,
            'business_partner_id'=>$customerid,
            'business_partner_name'=>$customername,
            'voucher_type'=>3,
            'payment_mode'=>'Cash',
            'bank_name'=>'',
            'invoice_id'=>$invoiceid,
            'auto_voucher'=>'Yes'                            
        );            
        $this->db->insert('account_vouchers', $data);
        $account_voucherid =  $this->db->insert_id();        

        $account_heads = $this->accounting_model->get_mapped_accounts(4,$my_business);     
        $debit_accounts  =[];
        $credit_accounts  =[];
        foreach($account_heads as $ah){
            if($ah['transaction_type']=='debit'){
               array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
            } else {
               array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
            }
        }
        $bank_name='';
        //enter detail entries
        foreach($debit_accounts as $debit_account){
            $debitamount=0;
            $debit = explode("|", $debit_account);
            //check entity
            if($debit[2]=="loyalty_expense"){$debitamount= $loyaltyused;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $debit[0],                
                'credit' => round($debitamount,2), //reverse entry
                'debit' => 0
            );
            //insert debit detail
            if($debitamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
        foreach($credit_accounts as $credit_account){
            $creditamount=0;
            $credit = explode("|", $credit_account);
            //check entity                
            if($credit[2]=="loyalty_amount"){$creditamount= $loyaltyused;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $credit[0],                
                'credit' => 0,
                'debit' => round($creditamount,2) //reverse entry
            );
            //insert credit detail
            if($creditamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }


        ///////create voucher in your own branch
        $data = array( 
            'business_id' => $this->session->userdata('businessid'),
            'description' => 'Loyalty Points Moved From HO to Branch '.$this->session->userdata('businessid').' against invoice ' . $invoiceid . ' on '. date('d-m-Y').', For '.$customername.' customer ID : '. $customerid,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $loyaltyused,
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> '1',
            'cost_center_name'=> 'Front Desk',
            'business_partner'=> 1,
            'business_partner_id'=>$customerid,
            'business_partner_name'=>$customername,
            'voucher_type'=>3,
            'payment_mode'=>'Cash',
            'bank_name'=>'',
            'invoice_id'=>$invoiceid,
            'auto_voucher'=>'Yes'                            
        );            
        $this->db->insert('account_vouchers', $data);
        $account_voucherid =  $this->db->insert_id();        

        $account_heads = $this->accounting_model->get_mapped_accounts(4,$this->session->userdata('businessid'));     
        $debit_accounts  =[];
        $credit_accounts  =[];
        foreach($account_heads as $ah){
            if($ah['transaction_type']=='debit'){
               array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
            } else {
               array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
            }
        }
        $bank_name='';
        //enter detail entries
        foreach($debit_accounts as $debit_account){
            $debitamount=0;
            $debit = explode("|", $debit_account);
            //check entity
            if($debit[2]=="loyalty_expense"){$debitamount= $loyaltyused;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $debit[0],                
                'debit' => round($debitamount,2), 
                'credit' => 0
            );
            //insert debit detail
            if($debitamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
        foreach($credit_accounts as $credit_account){
            $creditamount=0;
            $credit = explode("|", $credit_account);
            //check entity                
            if($credit[2]=="loyalty_amount"){$creditamount= $loyaltyused;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $credit[0],                
                'debit' => 0,
                'credit' => round($creditamount,2)
            );
            //insert credit detail
            if($creditamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
    }
    
    function create_loyalty_used_voucher($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid){

        $sql1="SELECT account_head_id, entity_name FROM account_event_mapping
        where account_event_id = 1 and entity_name = 'loyalty_amount' 
        and business_id=".$this->session->userdata('businessid')." ;";
        $query=$this->db->query($sql1);
        $result1 = $query->row();
        $loyalty_ah = $result1->account_head_id;

        $sql2="SELECT account_head_id, entity_name FROM account_event_mapping
        where account_event_id = 4 and entity_name = 'loyalty_expense' 
        and business_id=".$this->session->userdata('businessid')." ;";
        $query=$this->db->query($sql2);
        $result2= $query->row();
        $expense_ah = $result2->account_head_id;

        ////create loyalty used voucher
        if($loyaltyused>0){
            $data = array( 
                'business_id' => $my_business,
                'description' => 'Loyalty Points Used for discount on invoice ' . $invoiceid . ' on '. date('Y-m-d') .', For '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $loyaltyused,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername, 
                'voucher_type'=>3,
                'payment_mode'=>'Cash',
                'bank_name'=>'',
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes'                        
            );            
            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();        
    
            $data_debit=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $expense_ah,
                'credit' => round($loyaltyused,2), //reverse
                'debit' => 0
            );
            $this->db->insert('account_voucher_detail', $data_debit);

            
            $data_credit=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $loyalty_ah,
                'credit' => 0,
                'debit' => round($loyaltyused,2) //reverse
            );
            $this->db->insert('account_voucher_detail', $data_credit);


        }
    }

    function add_loyalty_points_ho($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid){
        ///create voucher in ho
        $account_heads = $this->accounting_model->get_mapped_accounts(4, $my_business);    
        $debit_accounts  =[];
        $credit_accounts  =[];        
        foreach($account_heads as $ah){
            if($ah['transaction_type']=='debit'){
               array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
            } else {
                array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
            }
        }
        $bank_name='';

        $data = array( 
            'business_id' => $my_business,
            'description' => 'Loyalty Points Earned against invoice ' . $invoiceid . ' on '. date('d-m-Y').', By '.$customername.' customer ID : '. $customerid,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $loyaltyearned,
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> '1',
            'cost_center_name'=> 'Front Desk',
            'business_partner'=> 1,
            'business_partner_id'=>$customerid,
            'business_partner_name'=>$customername,
            'voucher_type'=>3,
            'payment_mode'=>'Cash',
            'bank_name'=>$bank_name,
            'invoice_id'=>$invoiceid,
            'auto_voucher'=>'Yes',
            'sale_type'=>'loyalty'
        );

        $this->db->insert('account_vouchers', $data);
        $account_voucherid =  $this->db->insert_id();
        
        //enter detail entries
        foreach($debit_accounts as $debit_account){
            $debitamount=0;
            $debit = explode("|", $debit_account);
            //check entity
            if($debit[2]=="loyalty_expense"){$debitamount= $loyaltyearned;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $debit[0],                
                'debit' => round($debitamount,2),
                'credit' => 0
            );
            //insert debit detail
            if($debitamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
        foreach($credit_accounts as $credit_account){
            $creditamount=0;
            $credit = explode("|", $credit_account);
            //check entity                
            if($credit[2]=="loyalty_amount"){$creditamount= $loyaltyearned;}     
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $credit[0],            
                'debit' => 0,
                'credit' => round($creditamount,2)
            );
            //insert credit detail
            if($creditamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
    }


    function update_recovery_invoice(){
       
        
        $business= $this->business_model->get_business_details();
        
        $visitid = $this->input->post('visitid', TRUE);
        $visittime= $this->input->post('visit_time', TRUE);
        $invoicenumber = $this->input->post('invoicenumber', TRUE);
        $invoicedate = $this->input->post('invoicedate', TRUE);        
        
        $referenceinvoicenumber = $this->input->post('referenceinvoicenumber', TRUE);
        $recovery = $this->input->post('recovery', TRUE);
        $customerid = $this->input->post('customerid', TRUE);
        $customername='';
        
        $subtotal = $this->input->post('subtotal', TRUE);
        $paid = $this->input->post('paid', TRUE);
        $already_paid=$this->input->post('already_paid', TRUE);
        $discount = $this->input->post('discount', TRUE);
        $discount_perc=$this->input->post('discountperc',TRUE);
        $grosstotal = $this->input->post('grosstotal', TRUE);
        $grandtotal = $this->input->post('grandtotal', TRUE);
        $taxtotal = $this->input->post('taxtotal', TRUE);
        $paymentmode = $this->input->post('mode', TRUE);
        
        $totalpayable = $this->input->post('total_payable', TRUE);
        $cashpaid=0;$cardpaid=0;$voucherpaid=0;$checkpaid=0;
        $advance = $this->input->post('advance'); //this is the already paid amount
        
        $instrumentnumber = $paymentmode=="Online" ? 'Online '.$this->input->post('instrument_number', TRUE) : $this->input->post('instrument_number', TRUE);

        if($paymentmode=="Cash"){$cashpaid=$paid;}
        else if($paymentmode=="Card"){$cardpaid=$paid;}
        else if($paymentmode=="Check"){$checkpaid=$paid;}
        else if($paymentmode=="Online"){$checkpaid=$paid; $paymentmode='Check';}
        else if($paymentmode=="Voucher"){$voucherpaid=$paid;}
        else if($paymentmode=="Mixed"){
            $cashpaid=$this->input->post('cashpaid', TRUE);
            $cardpaid=$this->input->post('cardpaid', TRUE);
        } 
        
        
        $balance = $this->input->post('balance', TRUE);
        $returnamount = $this->input->post('returnamount', TRUE);
        $old_invoice_id = $this->input->post('old_invoice_id', TRUE);
        $other_charges=$this->input->post('other_charges', TRUE);
        $cc_charge=$this->input->post('cc_charge', TRUE);
        $original_cc_charge = $this->input->post('original_cc_charge', TRUE);
        $discountremarks=$this->input->post('discount_remarks', TRUE);
        $discounted_price=$this->input->post('discounted_price', TRUE);
        $service_discount=$this->input->post('service_discount', TRUE);
        
        
        //get total paid earlier
            $this->db->select('sum(paid_amount) as paidearlier');
            $this->db->where('invoice.visit_id', $visitid);
            $this->db->where('invoice.invoice_status','valid');
            $this->db->where('invoice.invoice_type','service');
            $this->db->group_by('invoice.visit_id');
            $pe = $this->db->get('invoice');
            $paidearliersum = $pe->row();
        
            if(null !== $paidearliersum){
                $paidearlier=$paidearliersum->paidearlier;
            } else {$paidearlier=0;}
        $totalpaid = $this->input->post('paid', TRUE); //no advance in recovery
           //echo $totalpaid; exit();     
        //Loyalty
        $loyaltyused=$this->input->post('loyaltyused',TRUE);
        $loyaltyvalue=$this->input->post('loyaltyvalue',TRUE);
        $loyaltyenabled=$this->input->post('loyaltyenabled',TRUE);
        $sloyaltyenabled=$this->input->post('sloyaltyenabled',TRUE);
        if($loyaltyenabled=='Y' && $sloyaltyenabled=='Y') {
            $loyaltyearned=(Float)$totalpaid/ (Float)$loyaltyvalue;
            
        } else {$loyaltyearned=0;}
        
        if($loyaltyearned < 0){$loyaltyearned=0;}
       
        
        //Get customer & visit
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = invoice.customer_id');
        $this->db->where('invoice.visit_id', $visitid);
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        }
        $this->db->where('invoice.invoice_status','valid');
        $this->db->order_by('id_invoice asc');
        $customervisits = $this->db->get('invoice');
       
         $customervisit = $customervisits->result_array();
         
       // echo $customervisits; exit();
      
        
       
       
        if(sizeof($customervisit)<=0){
            return 0;
            exit();
        }
        
        $insertloyalty = true;
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){
                $insertloyalty=false;
            }
        }

        $customername= $customervisit[0]['customer_name'];
        //Create invoice        
        $data = array(
            'customer_id' => $customerid,
            'invoice_number' => $invoicenumber,
            'invoice_date' => $invoicedate,
            'reference_invoice_number' => $referenceinvoicenumber,
            'is_recovery' => $recovery,
            'business_id' => $this->session->userdata('businessid'),
            'customer_name' => $customername,
            'customer_cell' => $customervisit[0]['customer_cell'],
            'customer_email' => $customervisit[0]['customer_email'],
            'customer_address' => $customervisit[0]['customer_address'],
            'tax_total' => $taxtotal,
            'discount' => $discount,
            'gross_amount' => $grosstotal,
            'paid_amount' => $paid,
            'paid_cash' => $cashpaid,
            'paid_card' => $cardpaid,
            'paid_voucher' => $voucherpaid,
            'paid_check' => $checkpaid,
            'net_amount' => $grandtotal,
            'visit_id' => $visitid,
            'sub_total' => $subtotal,
            'payment_mode' => $paymentmode,
            'instrument_number' => $instrumentnumber,
            'cc_charge' => $cc_charge,
            'balance' => $balance,
            'returnamount' => $returnamount,
            'discount_remarks'=>$discountremarks,
            'loyalty_used'=> $insertloyalty == true ? $loyaltyused : 0,
            'visit_time'=> $visittime,
            'other_charges'=> $other_charges,
            'cc_charge'=>$cc_charge,
            'loyalty_earned' => $insertloyalty ==true ? $loyaltyearned : 0,
            'total_payable'=>$totalpayable,
            'created_by' => $this->session->userdata('username'),
            'paid_earlier' => $paidearlier,
            'org_invoice_id'=> $customervisit[0]['id_invoice'],
            'invoice_extra' => $customervisit[0]['invoice_extra']
        );

        $this->db->insert('invoice', $data);
        $invoiceid =  $this->db->insert_id();
        
        //make sure invoice number is correct
        $today=date('Y-m-d');
        $seq=1;        
        $sql = "select max(invoice_seq)+1 as 'seq'
            from invoice where day(invoice_date)= day('".$today."') and invoice_status='valid' 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}
        if($paymentmode!=='Card' && $paymentmode!=='Mixed' && $business[0]['sh_hide']=='Yes' && $customervisit[0]['invoice_seq'] == 0){
            $seq=0;
        }        
       
        $update_invoice = array(
            'invoice_number' => date('Y-m').'-'.$invoiceid,
            'invoice_seq' => $seq
        ); 
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        //////////////////
        
        
        
        //update previous invoice
        $this->db->set('is_recovery', 'No');
        //$this->db->set('reference_invoice_number',date('Y-m').'-'.$invoiceid);
        $this->db->where('invoice_number', $referenceinvoicenumber);
        $this->db->update('invoice');
        
        
         //Update Loyalty
        if($loyaltyenabled=='Y' && $sloyaltyenabled=='Y'){
            $this->db->select('loyalty_points');
            $this->db->where('id_customers =',$customerid);
            $existingpoint = $this->db->get('customers');
            $existingpoints = $existingpoint->result_array();
            
            $newloyaltypoints=0;
            $calloyaltypoints=0;
            if((Float)$paid>0){
                $calloyaltypoints = (Float)$paid / (Float)$loyaltyvalue;
            }
            $newloyaltypoints=(Float)$existingpoints[0]['loyalty_points']+$calloyaltypoints;
            
            $this->db->where('id_customers = ', $customerid);
            $this->db->update('customers', array('loyalty_points'=>$newloyaltypoints));        
            
        }
        
        
        // get invoice details
        $this->db->select('business_services.id_business_services as service_id, business_services.commission_perc, invoice_details.service_type, invoice_details.service_category, invoice_details.service_name, invoice_details.price, invoice_details.discount, invoice_details.discounted_price, invoice_details.final_price, invoice_details.detail_visit_date, invoice_details.service_flag, invoice_details.invoice_discount, invoice_details.invoice_id, id_invoice_details');
        $this->db->join('invoice','invoice.id_invoice = invoice_details.invoice_id');
        $this->db->join('customer_visits','customer_visits.id_customer_visits = invoice.visit_id');
        $this->db->join('visit_services','customer_visits.id_customer_visits = visit_services.customer_visit_id and visit_services.service_id = invoice_details.service_id');
        $this->db->join('business_services','business_services.id_business_services = visit_services.service_id');
        $this->db->where('invoice_id', $customervisit[0]['id_invoice']);
        $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('invoice_details');
        $visit_services = $query->result();
        
        $k=0;
        
        $total_services= sizeof($visit_services);  
        
        
        $remainingsub=$subtotal - $discount; $remainingpaid=$paid;  //will use to calculate the paid service amount
        foreach($visit_services as $service){
            
            
            ///Calculate final discounted price for this service
            $priceafterdiscount=$service->discounted_price;
            $invoicediscount=$service->invoice_discount;
            $finalprice=  $service->final_price;
                       
                        
            ///Just put the paid amount in service (Trying out)
            $service_paid=0;
            
            
            //get already paid for this service
            $this->db->select('sum(paid) as alreadypaid');
            $this->db->join('invoice','invoice.id_invoice = invoice_details.invoice_id');
            $this->db->where('invoice.visit_id', $visitid);
            $this->db->where('invoice.invoice_status','valid');
            $this->db->where('invoice_details.service_id', $service->service_id);
            $this->db->group_by('invoice_details.service_id');
            $al_paid = $this->db->get('invoice_details');
            $already_paid = $al_paid->row();
            
            
            $thisservice =  $finalprice - $already_paid->alreadypaid;
            
            if($thisservice < $remainingpaid){
                if($thisservice > 0){
                    $service_paid=$thisservice;
                }else{
                    $service_paid=0;
                }
            }else{
                if($remainingpaid>0){
                    $service_paid = $remainingpaid;
                } else {
                    $service_paid=0;
                }
            }
            
            $remainingsub = $remainingsub - $thisservice;
            $remainingpaid = $remainingpaid-$service_paid;
            
            $services= array(
                'invoice_id' => $invoiceid,
                'business_id' => $this->session->userdata('businessid'),
                'service_id' => $service->service_id,
                'service_type' => $service->service_type,
                'service_category' => $service->service_category,
                'service_name' => $service->service_name,
                'staff' => '',                
                'price' => $service->price,
                'discount' => $service->discount,
                'discounted_price' => $service->discounted_price,
                'invoice_discount' => $service->invoice_discount,
                'final_price' => $service->final_price,
                
                'paid'=>$service_paid,
                //'paid' => $sPercPaidForService,
                
                'detail_visit_date'=>$service->detail_visit_date,
                'service_flag'=>$service->service_flag
            );
            $this->db->insert('invoice_details', $services);
            $invoice_detail_id=$this->db->insert_id();
            
            
            
            //Get visit service staffs   
            $this->db->select('*');
            $this->db->where('invoice_id', $service->invoice_id);
            $this->db->where('invoice_detail_id', $service->id_invoice_details);
            $vs_staff = $this->db->get('invoice_staff');
            $staff_count = $vs_staff->num_rows();
            $staffs = "";
            
            
            
            
            foreach($vs_staff->result() as $vss){
                
                $commission = ($service_paid * $service->commission_perc) / 100;
                $commission_ratio = round($commission, 2);
                //$commission_ratio =$commission/$staff_count;
                
                $staffs .= $vss->staff_name."|";
                
                $services = array(
                        
                    'invoice_id' => $invoiceid,
                    'invoice_detail_id' => $invoice_detail_id,
                    'business_id' => $this->session->userdata('businessid'),
                    'service_type' => $service->service_type,
                    'service_category' => $service->service_category,
                    'service_name' => $service->service_name,
                    'staff_name' => $vss->staff_name,
                    'staff_id' => $vss->staff_id,
                    'price' => $service->price,
                    'discount' => $service->discount,
                    'discounted_price' => $service->discounted_price,
                    'invoice_discount' => $service->invoice_discount,
                    'final_price' => $service->final_price,
                    //'paid' => $sPercPaidForService/$staff_count,
                    'paid' => $service_paid/$staff_count,
                    
                    'commission' => $commission_ratio,
                   // 'requested'=>$requested[$k],
                    'additional_staff'=>$vss->additional_staff    
                    
                );
                $this->db->insert('invoice_staff', $services);
                
                //update commissions
                $staffservice = array(
                    'invoice_id' => $invoiceid,
                    'invoice_detail_id' => $invoice_detail_id,
                    'business_id' => $this->session->userdata('businessid'),
                    'visit_id' => $visitid,
                    'staff_id' => $vss->staff_id,
                    'service_id' => $service->service_id,
                    'staff_name' => $vss->staff_name,
                    'service_type' => $service->service_type,
                    'service_category' => $service->service_category,
                    'service_name' => $service->service_name,
                    'price' => $vss->price / $staff_count,
                    'discount' => $vss->discount,
                    //'discounted_price' => $discounted_price[$k]/$staff_count,
                    'discounted_price' => $vss->discounted_price,
                    'staff_commission' => $commission_ratio,
                    'paid' => $service_paid/ $staff_count,
                    
                    'service_flag'=>$service->service_flag
                );
                $this->db->insert('staff_services', $staffservice);
            }
           
            $k++;
        }
        
        
        ///create recovery sale account voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(30);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Recovery Service Sale Voucher against invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $totalpayable,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername,
                'voucher_type'=>2,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'service'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount= $cashpaid;}
                if($debit[2]=="paid_card" && $cardpaid > 0){$debitamount=$cardpaid;}
                if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount= $checkpaid;}
                //if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $voucherpaid : $voucherpaid;}
                if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $voucherpaid;}
                
                //if($debit[2]=="sale_discount"){$debitamount= $totalservicediscount + $discount;}
                //if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}
                //if($debit[2]=="advance_adjusted"){$debitamount= $advance_amount;}
                
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                //if($credit[2]=="grosstotal"){$creditamount= $org_subtotal + $other_charges ;}
                
               if($credit[2]=="balance"){$creditamount= $totalpaid-$cc_charge;}
                //if($credit[2]=="sales_tax"){$creditamount= $taxtotal;}
                if($credit[2]=="cc_fee"){$creditamount= $cc_charge;}
                //if($credit[2]=="retained_amount"){$creditamount= $customer_advance==='true' ? $returnamount: 0;}
                //if($credit[2]=="cc_tip"){$creditamount= $cctip;}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,                    
                    'account_head_id' => $credit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        }
        
        
        return $invoiceid;
    }
    
    function update_recovery_order_invoice(){
        
       // exit();
        $business= $this->business_model->get_business_details();
        
        $orderid=$this->input->post('orderid', TRUE);
        $visittime=$this->input->post('visittime', TRUE);
        $invoicenumber=$this->input->post('invoicenumber', TRUE);
        $invoicedate=$this->input->post('invoicedate', TRUE);
        $referenceinvoicenumber = $this->input->post('referenceinvoicenumber', TRUE);
        
        $recovery = $this->input->post('recovery', TRUE);
        $customerid=$this->input->post('customerid', TRUE);
        
        $paid=$this->input->post('paid', TRUE);
        
        $subtotal=$this->input->post('subtotal', TRUE);
        $discount=$this->input->post('discount', TRUE);
        $grosstotal=$this->input->post('grosstotal', TRUE);
        $grandtotal=$this->input->post('grandtotal', TRUE);
        $taxes=$this->input->post('taxes', TRUE);
        $cc_charge=$this->input->post('cc_charge', TRUE);
        $taxtotal=$this->input->post('taxtotal', TRUE);

        

        $paymentmode=$this->input->post('mode', TRUE);
        $cashpaid=0;$cardpaid=0;$voucherpaid=0;$checkpaid=0;

        $instrumentnumber = $paymentmode=="Online" ? 'Online '.$this->input->post('instrument_number', TRUE) : $this->input->post('instrument_number', TRUE);

        if($paymentmode=="Cash"){$cashpaid=$paid;}
        else if($paymentmode=="Card"){$cardpaid=$paid;}
        else if($paymentmode=="Check"){$checkpaid=$paid;}
        else if($paymentmode=="Online"){$checkpaid=$paid; $paymentmode='Check';}
        else if($paymentmode=="Voucher"){$voucherpaid=$paid;}
        else if($paymentmode=="Mixed"){
            $cashpaid=$this->input->post('cashpaid', TRUE);
            $cardpaid=$this->input->post('cardpaid', TRUE);
        } 
        
        
        $balance=$this->input->post('balance');
        $totalpayable=$this->input->post('totalpayable');
        $returnamount=$this->input->post('returnamount');
        $old_invoice_id = $this->input->post('old_invoice_id', TRUE);
        
        $discounted_price=$this->input->post('discounted_price', TRUE);
        $customer_advance=$this->input->post('customer_advance', TRUE);
        
        $advance_amount=$this->input->post('advance_amount',TRUE);
        
        $other_charges=$this->input->post('other_charges',TRUE);
        
        $totalpaid= $this->input->post('paid', TRUE);
        
         //get total paid earlier
            $this->db->select('sum(paid_amount) as paidearlier');
            $this->db->where('invoice.visit_id', $orderid);
            $this->db->where('invoice.invoice_status','valid');
            $this->db->where('invoice.invoice_type','sale');
            $this->db->group_by('invoice.visit_id');
            $pe = $this->db->get('invoice');
            $paidearliersum = $pe->row();
        
            if(null !== $paidearliersum){
                $paidearlier=$paidearliersum->paidearlier;
            } else {$paidearlier=0;}
        
        
        //Loyalty
        $loyaltyused=$this->input->post('loyaltyused',TRUE);
        $loyaltyvalue=$this->input->post('loyaltyvalue',TRUE);
        $loyaltyenabled=$this->input->post('loyaltyenabled',TRUE);
        $rloyaltyenabled=$this->input->post('rloyaltyenabled',TRUE);
        if($loyaltyenabled=='Y' && $rloyaltyenabled=="Y") {
            $loyaltyearned=(Float)$totalpaid/ (Float)$loyaltyvalue;
            
        } else {$loyaltyearned=0;}
         if($loyaltyearned < 0){$loyaltyearned=0;}       
        
        //Get original invoice & customer
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = invoice.customer_id');
        $this->db->where('invoice.id_invoice', $old_invoice_id);
        //$this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $customerinvoices = $this->db->get('invoice');
       
        $customerinvoice = $customerinvoices->row();
        
        $customername=$customerinvoice->customer_name;
        $org_invoice_id = 0;
        if(null !== $customerinvoice->org_invoice_id && $customerinvoice->org_invoice_id > 0){
            $org_invoice_id = $customerinvoice->org_invoice_id;
        }else{
            $org_invoice_id = $customerinvoice->id_invoice;
        }
        
        $insertloyalty = true;
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){
                $insertloyalty=false;
            }
        }

        //Create invoice        
        $data = array(
            'customer_id'=> $customerinvoice->customer_id,
            'invoice_number'=>$invoicenumber,
            'invoice_date' => $invoicedate,
            'reference_invoice_number' => $referenceinvoicenumber,
            'is_recovery' => $recovery,
            'paid_amount' => $paid,
            'paid_cash' => $cashpaid,
            'paid_card' => $cardpaid,
            'paid_voucher' => $voucherpaid,
            'paid_check' => $checkpaid,
            'cc_charge' => $cc_charge,
            'instrument_number'=>$instrumentnumber,
            'balance'=>$balance,
            'payment_mode'=>$paymentmode,
            'invoice_type'=>'sale',
            'is_recovery' => $balance > 0 ? 'Yes' : 'No',
            'returnamount' => $returnamount,
            'org_invoice_id' => $org_invoice_id,            
            'business_id'=>$this->session->userdata('businessid'),
            'customer_name'=> $customerinvoice->customer_name,
            'customer_cell'=> $customerinvoice->customer_cell,
            'customer_email'=> $customerinvoice->customer_email,
            'customer_address'=> $customerinvoice->customer_address,
            'tax_total'=> $customerinvoice->tax_total,
            'discount' => $customerinvoice->discount,'gross_amount' => $customerinvoice->gross_amount,
            'total_payable'=>$customerinvoice->total_payable,
            'paid_earlier' => $paidearlier,
            'net_amount' => $grandtotal,
            'visit_id' => $customerinvoice->visit_id,
            'sub_total' => $customerinvoice->sub_total,
            'visit_time' =>$customerinvoice->visit_time,
            'created_by' => $this->session->userdata('username')
            
        );

        $this->db->insert('invoice', $data);
        $invoiceid =  $this->db->insert_id();
        
        //make sure invoice number is correct
         $today=date('Y-m-d');
        $seq=1;        
        $sql = "select max(invoice_seq)+1 as 'seq'
            from invoice where day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}

        if(isset($business[0]['r_auto_sh'])){
            if($business[0]['r_auto_sh']=='No'){
                $seq=0;
            }
        }
            
        $update_invoice = array(
            'invoice_number' => date('Y-m').'-'.$invoiceid,
            'invoice_seq' => $seq
        ); 
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        //////////////////
        
        
        //update previous invoice
        $this->db->set('is_recovery', 'No');
        $this->db->where('id_invoice', $old_invoice_id);
        $this->db->update('invoice');
        
        
         //Get original invoice products
        $this->db->select('invoice_products.*');
        $this->db->join('invoice','invoice.id_invoice = invoice_products.invoice_id');
        $this->db->where('invoice_products.invoice_id', $old_invoice_id);
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        }        
        $ip = $this->db->get('invoice_products');
        
        $invoiceproducts = $ip->result();
        
        
        foreach($invoiceproducts as $invoiceproduct){
                     
            //calculate weight of product price
            //Product Weights
            if($customerinvoice->sub_total > 0){ 
                $product_final_price = ($invoiceproduct->discounted_price)*$invoiceproduct->invoice_qty;
                $product_weight=($product_final_price  * 100)/$customerinvoice->sub_total;
            } else{
                $product_weight = 0;
            }
//            
//            //Calculate Wieghted Price            
//            $product_price = ($customerinvoice->total_payable * $product_weight) / 100;
           
            //Calculate Paid
            $product_paid = $totalpaid * $product_weight/100;
           
            //Calculate Commission
            
            //update invoice products
            $products = array(
                'invoice_id' => $invoiceid,
                'business_id' => $this->session->userdata('businessid'),
                'staff_name' => $invoiceproduct->staff_name,
                'staff_id' => $invoiceproduct->staff_id,
                'product_id' => $invoiceproduct->product_id,
                'category' => $invoiceproduct->category,
                'batch_id' => $invoiceproduct->batch_id,
                'batch' => $invoiceproduct->batch,
                'brand_name' => $invoiceproduct->brand_name,
                'product_name' => $invoiceproduct->product_name,
                'price' => $invoiceproduct->price,
                'invoice_qty' => $invoiceproduct->invoice_qty,
                'service_addition' => $invoiceproduct->service_addition,
                'invoice_discount' => $invoiceproduct->invoice_discount,
                'final_price' => $invoiceproduct->final_price,
                'discount' => $invoiceproduct->discount,
                'discounted_price' => $invoiceproduct->discounted_price,
                'paid' => $product_paid
            );
            $this->db->insert('invoice_products', $products);
            $invoice_detail_id=$this->db->insert_id();
        }
        // get staff_service details
        $this->db->select('*');
        $this->db->where('invoice_id', $old_invoice_id);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('staff_services');
        $staffproducts = $query->result();
        
        $count = $query->num_rows();
        
        foreach($staffproducts as $staffproduct) {
            
            //calculate weight of product price
            //Product Weights
            if($customerinvoice->sub_total > 0){ 
                $product_final_price = ($staffproduct->price - $staffproduct->discount)*$staffproduct->qty;
                $product_weight=($product_final_price *100)/$customerinvoice->sub_total;
            } else{
                $product_weight = 0;
            }
//            
//            //Calculate Wieghted Price            
//            $product_price = $customerinvoice->total_payable * $product_weight/100;
            
            //Calculate Paid
            $product_paid = $totalpaid * $product_weight/100;
            
            
            //update commissions
            $staffproducts = array(
                'invoice_id' => $invoiceid,
                'invoice_detail_id' => $invoice_detail_id,
                'business_id' => $this->session->userdata('businessid'),
                'order_id' => $staffproduct->order_id,
                'staff_id' => $staffproduct->staff_id,
                'staff_name' => $staffproduct->staff_name,
                'brand_name' => $staffproduct->brand_name,
                'product_name' => $staffproduct->product_name,
                'price' => $staffproduct->price,
                'sale_type' => 'sale',
                'qty' => $staffproduct->qty,
                'discount' => $staffproduct->discount,
                'discounted_price' => $staffproduct->discounted_price,
                'paid' => $product_paid
            );
            $this->db->insert('staff_services', $staffproducts);
        }
        
       
        ///create recovery retail sale account voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(30);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Recovery Retail Sale Voucher against invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $totalpayable,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername,
                'voucher_type'=>2,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'sale'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount= $cashpaid;}
                if($debit[2]=="paid_card" && $cardpaid > 0){$debitamount=$cardpaid;}
                if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount= $checkpaid;}
                //if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $voucherpaid : $voucherpaid;}
                
                
                //if($debit[2]=="sale_discount"){$debitamount= $totalservicediscount + $discount;}
                //if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}
                //if($debit[2]=="advance_adjusted"){$debitamount= $advance_amount;}
                
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                //if($credit[2]=="grosstotal"){$creditamount= $org_subtotal + $other_charges ;}
                
               if($credit[2]=="balance"){$creditamount= $totalpaid-$cc_charge;}
                //if($credit[2]=="sales_tax"){$creditamount= $taxtotal;}
                if($credit[2]=="cc_fee"){$creditamount= $cc_charge;}
                //if($credit[2]=="retained_amount"){$creditamount= $customer_advance==='true' ? $returnamount: 0;}
                //if($credit[2]=="cc_tip"){$creditamount= $cctip;}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        }
        
        
        return $invoiceid;
    }
    
    function update_order_invoice(){
        exit();
        $product_ids=$this->input->post('product_ids', TRUE);
        $orderid=$this->input->post('orderid', TRUE);
        
        //Get order products
        $this->db->select('business_brands.id_business_brands,
                            business_brands.business_brand_name,
                            business_products.product,
                            order_products.staff_name,
                            order_products.staff_id,
                            order_products.qty,
                            business_products.price,
                            business_products.id_business_products as product_id,
                            business_products.category as category,
                            order_products.batch,
                            order_products.batch_id,
                            adjustment_order_id, order_status, business_products.commission, product_batch.batch_amount, order_extra');
        $this->db->join('business_products', 'business_products.id_business_products = order_products.product_id');
        $this->db->join('business_brands', 'business_brands.id_business_brands = business_products.brand_id');
        $this->db->join('product_batch', 'product_batch.id_batch= order_products.batch_id');
        $this->db->join('customer_orders', 'customer_orders.id_customer_order = order_products.customer_order_id');
        $this->db->join('adjustment_notes', 'adjustment_notes.adjustment_order_id = order_products.customer_order_id and adjustment_notes.product_id = order_products.product_id', 'left');
        $this->db->where('order_products.customer_order_id', $orderid);
        $this->db->where('order_products.business_id', $this->session->userdata('businessid'));
        $this->db->group_by('product_batch.id_batch');
        $orderproducts = $this->db->get('order_products');
      //  echo $orderproducts; exit();
        $stopproduct='';
        
        //$op=$orderproducts->result_array() ;
        
        foreach($orderproducts->result_array() as $row){
            if($row['adjustment_order_id'] == null){
                if($row['order_status']=='invoiced'){return 'error|Already Invoiced'; exit();}
                $qty=0;
                $batches = $this->product_model->get_all_batches($row['product_id'], $this->session->userdata('businessid'));
                print_r($batches);
                foreach($batches as $batch){
                    if($batch['id_batch']==$row['batch_id']){
                        $qty=$batch['total_stock'];
                        if($qty < $row['qty']){
                            $stopproduct=$row['product_name'];
                            return('error|Stock Qty is lower in batch '.$batch['batch_number'] .' then the Ordered Qty for '.$stopproduct);
                            exit();
                        }
                    }
                }
            }
        }
        
        $business= $this->business_model->get_business_details();
        $taxperc= $this->business_model->get_tax_perc('sale');
       
        $newloyaltypoints=0;
        
        $batch_ids=$this->input->post('batch_ids', TRUE);
        $batches=$this->input->post('batches', TRUE);
        
        $product_ids=$this->input->post('product_ids', TRUE);
        
        $invoicenumber=$this->input->post('invoicenumber', TRUE);
        $invoicedate=$this->input->post('invoicedate', TRUE);
        $customerid=$this->input->post('customerid', TRUE);
        
        $subtotal=$this->input->post('subtotal', TRUE);
        $org_subtotal=$this->input->post('orgsubtotal', TRUE);
        
        $paid=$this->input->post('paid', TRUE);
        $discount=$this->input->post('discount', TRUE);
        $discount_perc=$this->input->post('discount_perc', TRUE);
        $service_addition=$this->input->post('service_addition', TRUE);
        
        $grosstotal=$this->input->post('grosstotal', TRUE);
        $net_amount=$this->input->post('net_amount', TRUE);
        $grandtotal=$this->input->post('grandtotal', TRUE);
        $totalpayable=$this->input->post('totalpayable', TRUE);
        $roundedadjustment=$this->input->post('roundedadjustment');
        
        
        $taxes=$this->input->post('taxes', TRUE);
        $taxtotal=$this->input->post('taxtotal', TRUE);
        $cc_charge=$this->input->post('cc_charge', TRUE);
        $paymentmode=$this->input->post('mode', TRUE);
        $cashpaid=0;$cardpaid=0;$voucherpaid=0;$checkpaid=0;
                
        $instrumentnumber = $paymentmode=='Online' ?  'Online '.$this->input->post('instrument_number', TRUE) : $this->input->post('instrument_number', TRUE);
        $balance=$this->input->post('balance');
        $returnamount=$this->input->post('returnamount');
        $product_discount=$this->input->post('product_discount', TRUE);
        $discounted_price=$this->input->post('discounted_price', TRUE);
        
        $customer_advance=$this->input->post('customer_advance', TRUE);
        $retained_used=$this->input->post('retained_used', TRUE);
        $retained_amount_used=$this->input->post('retained_amount_used', TRUE);
        $remaining_retained=$this->input->post('remaining_retained', TRUE);
        
        $cctip = $this->input->post('cctip', TRUE);
        
        $advance_amount=$this->input->post('advance_amount',TRUE);
        
        $other_charges=$this->input->post('other_charges',TRUE);
        $serivce_flag=$this->input->post('service_flag',TRUE);
        
        $totalpaid= $advance_amount+$paid;
        $totalpaidnow= $totalpaid;
        
        if($paymentmode=="Cash"){$cashpaid=$paid;}
        else if($paymentmode=="Card"){$cardpaid=$paid;}
        else if($paymentmode=="Check"){$checkpaid=$paid;}
        else if($paymentmode=="Online"){$checkpaid=$paid; $paymentmode='Check';}
        else if($paymentmode=="Voucher"){$voucherpaid=$paid;}
        else if($paymentmode=="Mixed"){
            $cashpaid=$this->input->post('cashpaid', TRUE);
            $cardpaid=$this->input->post('cardpaid', TRUE);
            $totalpaidnow = $cashpaid + $cardpaid;
        } 
         
        //Loyalty
        $loyaltyused=$this->input->post('loyaltyused',TRUE);
        $loyaltyvalue=$this->input->post('loyaltyvalue',TRUE);
        $loyaltyenabled=$this->input->post('loyaltyenabled',TRUE);
        $sloyaltyenabled=$this->input->post('sloyaltyenabled',TRUE);
        $rloyaltyenabled=$this->input->post('rloyaltyenabled',TRUE);
        
        if($loyaltyenabled=='Y' && $rloyaltyenabled=="Y") {$loyaltyearned=(Float)$totalpaid/ (Float)$loyaltyvalue;}
        else {$loyaltyearned=0;}
        if($loyaltyearned < 0){$loyaltyearned=0;}        
        //Get customer & order
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
        $this->db->where('customer_orders.id_customer_order', $orderid);
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        $customerorders = $this->db->get('customer_orders');
       
        $customerorder = $customerorders->row();

        $insertloyalty = true;
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){
                $insertloyalty=false;
            }
        }
        
        //print_r($other_charges); exit();
        //Create invoice    
        $invoice_date=$invoicedate;
        $visittime=$invoicedate;
        $customername=$customerorder->customer_name;
        $data = array(
            'customer_id'=>$customerid,
            'invoice_number'=>'999',
            'business_id'=>$this->session->userdata('businessid'),
            'customer_name'=> $customerorder->customer_name,
            'customer_cell'=> $customerorder->customer_cell,
            'customer_email'=> $customerorder->customer_email,
            'customer_address'=> $customerorder->customer_address,
            'tax_total'=>$taxtotal,
            'paid_amount' => $paid,
            'paid_cash' => $cashpaid,
            'paid_card' => $cardpaid,
            'paid_voucher' => $voucherpaid,
            'paid_check' => $checkpaid,
            'discount' => $discount,
            'gross_amount' => $grosstotal,
            'net_amount' => $net_amount,
            'visit_id' => $orderid,
            'visit_time' => $visittime,
            'sub_total' => $subtotal,
            'invoice_type'=>'sale',
            'payment_mode'=>$paymentmode,
            'instrument_number'=>$instrumentnumber,
            'cc_charge'=>$cc_charge,
            'balance'=>$balance,
            'is_recovery' => $balance > 0 ? 'Yes' : 'No',
            'returnamount' => $returnamount,
            'discount_remarks' => $this->input->post('discount_remarks'),
            'returnamount' => $returnamount,
            'loyalty_used'=> $insertloyalty==true ? $loyaltyused : 0,
            'advance_amount'=>$advance_amount,
            'other_charges'=>$other_charges,
            'invoice_date'=>$invoice_date,
            'retained_used'=>$retained_used,
            'retained_amount_used'=>$retained_amount_used,
            'retained_amount'=>$customer_advance==='true' ? $returnamount : 0,
            'cctip'=>$cctip,
            'loyalty_earned'=> $insertloyalty==true ? $loyaltyearned : 0,
            'total_payable'=>$totalpayable,
            'created_by' => $this->session->userdata('username')
        );

        $this->db->insert('invoice', $data);
        $invoiceid =  $this->db->insert_id();
        
        //make sure invoice number is correct
         $today=date('Y-m-d');
        $seq=1;        
        $sql = "select max(invoice_seq)+1 as 'seq'
            from invoice where day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}
           
        if(isset($business[0]['r_auto_sh'])){
            if($business[0]['r_auto_sh']=='No'){
                $seq=0;
            }
        }
        
        
        $update_invoice = array(
            'invoice_number' => date('Y-m').'-'.$invoiceid,
            'invoice_seq' => $seq
        ); 
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        //////////////////
        
         ///update customer advance
        if ($customer_advance==='true'){
            $newval=$returnamount + $remaining_retained;
        } else {
            $newval=$remaining_retained;
        }
        $this->db->set('customer_advance', $newval);
        $this->db->where('id_customers',$customerid);
        $this->db->update('customers');
        //////////
        
        //Update Loyalty
        if($loyaltyenabled=='Y' && $rloyaltyenabled=='Y'){
            $this->db->select('loyalty_points');
            $this->db->where('id_customers =',$customerid);
            $existingpoint = $this->db->get('customers');
            $existingpoints = $existingpoint->result_array();
            
            $newloyaltypoints=(Float)$existingpoints[0]['loyalty_points'];
            if($loyaltyused>0){
                $newloyaltypoints= (Float)$existingpoints[0]['loyalty_points'] - $loyaltyused;
            }
            $calloyaltypoints=0;
            if($totalpaid>0){
                $calloyaltypoints = $totalpaid / $loyaltyvalue;
            }
            $newloyaltypoints=$newloyaltypoints+$calloyaltypoints;
            
            $this->db->where('id_customers = ', $customerid);
            $this->db->update('customers', array('loyalty_points'=>$newloyaltypoints));        
            
        }
        /////
        $this->disount_invoice_user_insert($invoiceid);
        
        
        //insert invoice taxes
        if(isset($taxes)){
            foreach($taxes as $tax){
                $data=array(
                    'invoice_id'=>$invoiceid,
                    'business_id'=>$this->session->userdata('businessid'),
                    'invoice_tax_name'=>$tax['taxname'],
                    'invoice_tax'=>$tax['tax']
                );
                $this->db->insert('invoice_taxes', $data);
            }
        }
        
        //insert invoice products
        $k=0;
        //foreach ($orderproducts1 as $orderproduct)
        $b=0;
        
        $totalproductdiscount=0;
        $batch_amount=0;
        $remainingsub=$subtotal; $remainingpaid=$paid+$advance_amount; 
        
        $total_service_additions=0;
        //print_r($op);
        //foreach($product_ids as $product_id)
        foreach($orderproducts->result() as $orderproduct)
        {
            //print_r($orderproduct);
            //$priceafterdiscount= round(floatval($orderproduct->price) - floatval($product_discount[$k]),2);
            $taxonoriginalprice= round((floatval($orderproduct->price) * $taxperc->tax_percentage)/100,2);
            
            
            $totalproductdiscount = $totalproductdiscount + $product_discount[$k];
            
            $total_service_additions = $total_service_additions + $service_addition[$k];
            
            //Just put the paid amount in product details (Trying out)
            $priceafterdiscount=round(floatval($orderproduct->price) + floatval($service_addition[$k]) - floatval($product_discount[$k]),2);
            $invoicediscount=$discount/sizeof($product_discount);
            $finalprice=  ($priceafterdiscount*$orderproduct->qty) - $invoicediscount;
            if($business[0]['tax_mode']=='before'){
                $taxonoriginalprice= round((((floatval($orderproduct->price) * $orderproduct->qty) + floatval($service_addition[$k])) * $taxperc->tax_percentage)/100,2);
            }else{
                $taxonoriginalprice= round(((floatval($finalprice) + floatval($service_addition[$k])) * $taxperc->tax_percentage)/100,2);
            }
            
            
            $product_paid=0;
            //$thisinvoicediscount = $discount/sizeof($orderproduct);
            //$thisproduct = ($orderproduct->price + $service_addition[$k]) - ($product_discount[$k] + $invoicediscount);
            //$thisproduct = $thisproduct * $orderproduct->qty;
            
            if($finalprice < $remainingpaid){
                $product_paid=$finalprice;
            }else{
                if($remainingpaid>0){
                    $product_paid=$remainingpaid;
                } else {
                    $product_paid=0;
                }
            }
            
            $remainingsub = $remainingsub - $finalprice;
            $remainingpaid = $remainingpaid-$product_paid;
            
            $commission = ($product_paid * $orderproduct->commission) / 100;
            $commission = round($commission, 2);
            
            $batch_amount += ((float)$orderproduct->batch_amount*$orderproduct->qty);
            
            
            $products= array(
                'invoice_id'=>$invoiceid,
                'business_id'=>$this->session->userdata('businessid'),
                'brand_name'=>$orderproduct->business_brand_name,
                'product_name'=>$orderproduct->product,
                'staff_name'=>$orderproduct->staff_name,
                'staff_id'=>$orderproduct->staff_id,
                'invoice_qty'=>$orderproduct->qty,
                'price'=>$orderproduct->price,
                'service_addition'=>$service_addition[$k],
                'discount'=>$product_discount[$k],
                //'discounted_price'=>$discounted_price[$k],
                'discounted_price'=>$priceafterdiscount,
                'invoice_discount'=>$invoicediscount,
                'final_price'=>$finalprice,
                'taxes'=>$taxonoriginalprice,
                'paid'=>$product_paid,
                'product_id'=>$orderproduct->product_id,
                'category'=>$orderproduct->category,
                'batch'=>$orderproduct->batch,
                'batch_id'=>$orderproduct->batch_id,
                'commission'=>$commission
            );
            
            
            $this->db->insert('invoice_products', $products);
            $invoice_detail_id=$this->db->insert_id();

            
            //insert staff sale
            $amount=$orderproduct->price*$orderproduct->qty;
            
            $staffsale=array(
                'invoice_id'=>$invoiceid,
                'invoice_detail_id' =>  $invoice_detail_id,
                'business_id'=>$this->session->userdata('businessid'),
                'order_id'=>$orderid,
                'staff_id'=>$orderproduct->staff_id,
                'staff_name'=>$orderproduct->staff_name,
                'brand_name'=>$orderproduct->business_brand_name,
                'product_name'=>$orderproduct->product,
                'price'=>$amount,
                'sale_type'=>'sale',
                'qty'=>$orderproduct->qty,
                'discount'=>$product_discount[$k],
                'discounted_price'=>$priceafterdiscount,
                'paid'=>$product_paid
            );
            $this->db->insert('staff_services', $staffsale);                
            $k++;
        }
        
        $this->db->where('adjustment_order_id', $orderid);
        $this->db->delete('adjustment_notes');
        
        
         ///create retail sale voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(1);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Retail Sale Voucher against invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $totalpayable,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername,
                'voucher_type'=>2,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'sale'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount+$cashpaid : $cashpaid;}
                if($debit[2]=="paid_card" && $cardpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount+$cardpaid : $cardpaid;}
                if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $checkpaid : $checkpaid;}
                if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $voucherpaid : $voucherpaid;}
                
                if($debit[2]=="balance"){$debitamount= $balance;}
                if($debit[2]=="sale_discount_retail"){$debitamount= $totalproductdiscount + $discount;}
                if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}
                                
                if($debit[2]=="advance_adjusted"){
                    if($retained_amount_used==0 && $advance_amount > 0){
                        $debitamount= $advance_amount;
                    } elseif($retained_amount_used>0 && $advance_amount > 0) {
                        $debitamount= $advance_amount-$retained_amount_used;                        
                    } 
                }    
                
                if($debit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment < 0){                       
                        $debitamount=$roundedadjustment*-1;
                    }
                    
                }
                if(defined('LOYALTY_VOUCHER')){                    
                    if(LOYALTY_VOUCHER==TRUE){
                        if($debit[2]=="loyalty_amount"){
                            if($loyaltyused>0){ //if discount is actually loyalty points
                                $debitamount= 0;
                            
                                //see if we need to bring the loyalty points in from HO
                                $my_business = $this->check_if_ho();
                                //bring the points from ho
                                if($my_business != $this->session->userdata('businessid')){
                                    $this->bring_in_ho_points($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                                }   

                                $this->create_loyalty_used_voucher($this->session->userdata('businessid'),$loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                                $debitamount= 0; // make sure
                            }                 
                        }
                    }
                }
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                if($credit[2]=="grosstotal_retail"){$creditamount= $org_subtotal + $other_charges;}
                
                if($credit[2]=="sales_tax"){$creditamount= $taxtotal;}
                if($credit[2]=="cc_fee"){$creditamount= $cc_charge;}
                if($credit[2]=="retained_amount"){$creditamount= $customer_advance==='true' ? $returnamount: 0;}
                if($credit[2]=="cc_tip"){$creditamount= $cctip;}
                
                if($totalpaidnow > $totalpayable+$roundedadjustment){
                    if($credit[2]=="return_cash"){$creditamount= $customer_advance==='false' ? $returnamount: 0;}
                }
                if($credit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment > 0){
                        
                        $creditamount=$roundedadjustment; 
                    }
                    
                }
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }

            ///create loyalty voucher
            if(defined('LOYALTY_VOUCHER')){                    
                if(LOYALTY_VOUCHER==TRUE){
                    if($loyaltyearned > 0){
                        $my_business= $this->check_if_ho();            
                        $this->add_loyalty_points_ho($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                    }
                }
            }
            //create inventory and cost of goods voucher/////////////////////////////////
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(23);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Cost of Goods Solds Voucher against reference voucher ID '. $account_voucherid . ' invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $batch_amount,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername,
                'voucher_type'=>3,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                //'sale_type'=>'sale'
            );

            $this->db->insert('account_vouchers', $data);
            $cogs_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                
                if($debit[2]=="cogs"){$debitamount= $batch_amount;}
                
                $data_detail=array(
                    'account_voucher_id' => $cogs_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                
                if($credit[2]=="inventory"){$creditamount= $batch_amount;}
                
                $data_detail=array(
                    'account_voucher_id' => $cogs_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        }
        
        
        //update customer order (mark as invoiced)
        $this->db->set('order_status', 'invoiced');
        $this->db->where('id_customer_order', $orderid);
        $this->db->update('customer_orders');
        //return "success|".$invoiceid;
        
        
        $mypaid = $customer_advance==='true' ? $advance_amount + $returnamount + $paid : $advance_amount + $paid;
        return $invoiceid.'|'.$loyaltyearned.'|'.$totalpayable.'|'.$mypaid.'|'.$balance;
    }
    
    function getrecoveryinvoices($sh=false){
        $today = date('Y-m-d');
        
        $this->db->select('*,DATE_FORMAT(invoice_date, "%d-%m-%Y") as invoice_date, DATE_FORMAT(visit_time, "%d-%m-%Y %h:%i") as visit_time, DATE_FORMAT(visit_time, "%Y-%m-%d") as sked_date');
        //$this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->join('business', 'business.id_business=invoice.business_id');
        $this->db->where('invoice.balance >', 0);
        $this->db->where('invoice.is_recovery', 'Yes');
        $this->db->where('invoice.invoice_status=', 'valid');
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice.invoice_seq > ', 0);
        }
        $query = $this->db->get('invoice');
        
        return $query->result_array();
    }
    
    function gettodayinvoices($feedback=null, $order='asc', $status='valid', $sh=false, $mdate=null, $customer_id=null){
        
        
        if($mdate==null){
            $today = date('Y-m-d');
            $tomorrow = date('Y-m-d H:i:s', strtotime('tomorrow'));
        }else{
            $today = $mdate;
        }
        
        $this->db->select('*, DATE_FORMAT(invoice_date, "%h:%i") as invoice_time, DATE_FORMAT(invoice_date, "%d-%c-%Y") as invoice_date, DATE_FORMAT(visit_time, "%d-%c-%Y %H:%i") as visit_time');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        
        if(null == $customer_id){
            $this->db->where('date(invoice_date) =', $today);
        }
        //$this->db->where('invoice_date <', $tomorrow);
        if(null!==$feedback){
            $this->db->where('feedback_status', $feedback);
            
        }
        if($status=='valid'){
            $this->db->where('invoice_status', 'valid');
        }
        
        if(null != $customer_id){
            $this->db->where('invoice.customer_id', $customer_id);
        }
        
        
        if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice_seq >', 0);
        }
        
        $this->db->order_by('id_invoice '.$order.'');
        //$this->db->where('reference_invoice_number !=', 'bad debts');
        $query = $this->db->get('invoice');
        //echo $query; exit();
       
        return $query->result_array();
    }
    
   
    
    function getinvoicedetailstaff($invoicedetailid){
                      
        $this->db->select('*');
        $this->db->where('invoice_detail_id', $invoicedetailid);
        $query = $this->db->get('invoice_staff');
        
        return $query->result_array();
        
        
    }
    
    function getdayinvoices($today=null, $order='asc', $feedback=null, $invoice_id=null, $type=null, $sh=false, $status='valid'){
        
        //$today = date('Y-m-d');
        //$tomorrow = date('Y-m-d H:i:s', strtotime('tomorrow'));
        
        $sql = " SELECT
        invoice.invoice_seq,
        id_invoice,
        visit_id,
        invoice_type,
        invoice.customer_name,
        invoice.customer_cell,
        invoice.customer_id,
        invoice_d.staff_id,
        invoice_d.staff_name AS staff,
        reference_invoice_number,
        returnamount,
        CONCAT(
            invoice_d.service_type,
            ' ',
            invoice_d.service_category,
            ' ',
            invoice_d.service_name
        ) AS service,
        invoice_d.service_name,
        invoice_d.service_id,
        invoice_d.service_type,
        invoice_d.service_category,
        invoice.discount AS 'invoice_discount',
        invoice.service_addition as invoice_addition,
        invoice.payment_mode,
        paid_amount,
        sub_total,
        other_charges,
        gross_amount AS gross,
        total_payable AS gross_amount,
        retained_amount,
        invoice.balance,
        invoice.advance_amount,
        cctip,
        tax_total,
        cc_charge,
        invoice_d.id_invoice_details,
        invoice_d.price + invoice_d.service_addition price,
        invoice_d.paid AS paid_details,
        invoice_d.service_addition,
        invoice_d.discount,
        paid_amount,
        paid_cash,
        paid_card,
        paid_voucher,
        paid_check,
        CONCAT(
            invoice_products.brand_name,
            ' ',
            invoice_products.product_name,
            ' x ',
            invoice_products.invoice_qty
        ) product_name,
        invoice_qty,
        invoice_products.price product_price,
        invoice_products.discount discounted_price,
        invoice_products.service_addition product_addition,
        invoice_products.staff_name product_staff,
        invoice_products.discount product_discount,
        
        feedback_status,
        invoice_status,
        DATE_FORMAT(invoice_date, '%d-%c-%Y') AS invoice_date,
        DATE_FORMAT(invoice_date, '%H:%i') AS invoice_time,
        case when ifnull(customer_visits.inservice_time,'')!='' then DATE_FORMAT(customer_visits.inservice_time, '%H:%i') else 'N/A' end AS inservice_time,
        case when invoice.invoice_type='service' then DATE_FORMAT(detail_visit_date, '%H:%i') else  'N/A' end  AS visit_time,        
        case when invoice.invoice_type='service' then DATE_FORMAT(detail_visit_date, '%d-%c-%Y') else  'N/A' end  AS visit_date,
        case when invoice.invoice_type='service' then DATE_FORMAT(detail_visit_date, '%d-%c-%Y') else  'N/A' end  AS visit_date,
        retained_amount_used,
        invoice.created_by
        FROM invoice
        LEFT join customer_visits on invoice.visit_id = customer_visits.id_customer_visits
        LEFT JOIN (select invoice_details.*, invoice_staff.staff_id, invoice_staff.staff_name 
           FROM invoice_details
           JOIN invoice_staff ON invoice_staff.invoice_detail_id = invoice_details.id_invoice_details
           JOIN invoice on invoice.id_invoice = invoice_details.invoice_id
           WHERE 1=1 ";
    
        if(null!==$today){    
            $sql .=" AND DATE(invoice.invoice_date) = '".$today."' ";
        }    
        $sql .=" ) as invoice_d 
           ON invoice_d.invoice_id = invoice.id_invoice
        
        LEFT JOIN invoice_products on invoice_products.invoice_id = invoice.id_invoice ";
        if(null!==$today){
            $sql .=" AND date(invoice_products.invoice_product_date) = '".$today."' ";
        }
        $sql .=" Where invoice.business_id = '". $this->session->userdata('businessid')."' ";
        //$sql .=" Where 1=1 ";
        if($status!=='all'){
            $sql .=" AND invoice.invoice_status ='".$status."' ";
        } 
         if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            
            $sql .=" AND invoice.invoice_seq > 0 ";
        }
        
        
        //$this->db->where('invoice_type', 'service');
        //$this->db->where('reference_invoice_number', '');
        
        if(null!==$today){
            $sql .=" AND date(invoice_date) ='".$today."' ";
        }
        if(null!==$feedback){
            $sql .=" AND feedback_status ='".$feedback."' ";
            $sql .=" AND ifnull(reference_invoice_number,'') ='' ";
            
        }
        if(null!==$type){
            $sql .=" AND invoice_type ='".$type."' ";
            
        }
        if(null!==$invoice_id){
            $sql .=" AND id_invoice = ".$invoice_id." ";
        }
        //$this->db->where('reference_invoice_number !=', 'bad debts');
        $sql .=" order by id_invoice ".$order." ";
        
       // echo $sql; exit();
        $query = $this->db->query($sql);
        
        return $query->result_array();
    }
    
    function getmaxinvoice(){
        $this->db->select('max(id_invoice) as maxid',false);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('invoice_status', 'valid');
        $query= $this->db->get('invoice');
        
        return $query->row();
    }

    
    
    function getappointmentsstaff($id_customer_visit, $id_visit_service){
        $this->db->select('staff_id, staff_name');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('customer_visit_id', $id_customer_visit);
        $this->db->where('visit_service_id', $id_visit_service);
        $this->db->where('visit_service_status','Active'); 
        $query = $this->db->get('visit_service_staffs');
        return $query->result();
    }
    
    function getappointments($appointment_date){
        //$today = date('Y-m-d');
        $today = date('Y-m-d',strtotime($appointment_date));
        
        $this->db->select('*, DATE_FORMAT(visit_service_start, "%d-%m-%Y") as Date');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->join('visit_services', 'visit_services.customer_visit_id = customer_visits.id_customer_visits and visit_service_status="Active"');
        $this->db->join('service_category', 'service_category.id_service_category = visit_services.id_service_category');
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        //$this->db->where('visit_services.visit_service_start >=', $today);
        $this->db->like('visit_services.visit_service_start', $today);
        $this->db->where('customer_visits.visit_status !=', 'canceled');
        $this->db->order_by('visit_services.visit_service_start', 'asc');
        $query = $this->db->get('customer_visits');
        
        return $query->result();
    }
    
    function getproductbyname($product_name){
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('product', $product_name);
        $query = $this->db->get('business_products');
        return $query->row();
    }
    
    
    function cancel_invoice_old(){
        $invoice_id = $this->input->post('invoiceid', TRUE);
        $visit_order_id = $this->input->post('visit_order_id', TRUE);
        $flag = $this->input->post('flag', TRUE);
        
        //Find original invoice using reference
        $this->db->select("ifnull(reference_invoice_number,'') reference_invoice_number, is_recovery, balance, paid_amount, visit_id, invoice_number, loyalty_used, customer_id");
        $this->db->where("id_invoice =", $invoice_id);
        $query = $this->db->get("invoice");
        $results=$query->result();
        
        $customer_id=0;
        $loyaltyused=0;
        $visitid='';
        $isrecovery='';
        $balance='';
        $paid_amount='';
        $invoice_number='';
        if(isset($results)){
            foreach($results as $result){
                $visitid=$result->visit_id;
                $reference_invoice_number =$result->reference_invoice_number;
                $is_recovery=$result->is_recovery;
                $balance=$result->balance;
                $paid_amount =$result->paid_amount;
                $invoice_number=$result->invoice_number;
                $customer_id=$result->customer_id;
                $loyaltyused=$result->loyalty_used;
            }
        }
        
        if($balance !== "" && (float)$balance > 0 && $is_recovery=="No"){
            return "Balance from this invoice has been recovered in a later invoice. Please Cancel the latest invoice first!"  ; 
            exit();
        }
    }
    
    
    function cancel_invoice(){
        
        $invoice_id = $this->input->post('invoiceid', TRUE);
        $visit_order_id = $this->input->post('visit_order_id', TRUE);
        $flag = $this->input->post('flag', TRUE);
        $reason = $this->input->post('reason', TRUE);
        //Find original invoice using reference
        $this->db->select("ifnull(reference_invoice_number,'') reference_invoice_number, balance, paid_amount, visit_id, invoice_number, loyalty_used, customer_id");
        $this->db->where("id_invoice =", $invoice_id);
        $query = $this->db->get("invoice");
        $results=$query->result();
        
        $customer_id=0;
        $loyaltyused=0;
        $visitid='';
        $isrecovery='';
        $balance='';
        $paid_amount='';
        $invoice_number='';
        if(isset($results)){
            foreach($results as $result){
                $visitid=$result->visit_id;
                $isrecovery=$result->reference_invoice_number;
                $balance=$result->balance;
                $paid_amount =$result->paid_amount;
                $invoice_number=$result->invoice_number;
                $customer_id=$result->customer_id;
                $loyaltyused=$result->loyalty_used;
            }
        }
      

        if($isrecovery && $isrecovery !== ''){
            // change selected invoice status
            $this->db->where('id_invoice', $invoice_id);
            $this->db->update('invoice', array('invoice_status' => 'cancelled', 'cancelreason' => $reason,  'cancelled_by' => $this->session->userdata('username')));

            //change account voucher status
                    $this->db->where('invoice_id', $invoice_id);
                    $this->db->update('account_vouchers', array('voucher_status' => 'cancelled', 'cancelled_by' => $this->session->userdata('username')));
                    
            
            //Find newer recovery invoice
            $this->db->select('id_invoice, invoice_number, reference_invoice_number, balance, is_recovery');
            $this->db->where('visit_id=', $visitid);
            $this->db->where('id_invoice <>', $invoice_id);
            $this->db->where('invoice_status=', 'valid');
            $this->db->order_by('id_invoice','DESC');
            $this->db->limit(1);
            $query=$this->db->get('invoice');
            $newer_invoices=$query->result();
            
            
            foreach($newer_invoices as $newer_invoice)
            {
                if ($newer_invoice->id_invoice > $invoice_id){
                    
                    $new_balance = (float)$newer_invoice->balance + (float)$paid_amount;
                     //add balance back to the latests invoice
                    $this->db->where('invoice_number=',$newer_invoice->invoice_number);
                    $this->db->update('invoice', array('balance' => $new_balance));
                    
                }else {
                    // change original invoice status
                    $this->db->where('invoice_number', $newer_invoice->invoice_number);
                    $this->db->update('invoice', array('is_recovery' => 'Yes'));
                }
            }
        } else {
      
        
            if($flag === 'service'){
                //check if there are any referencing invoices
                $this->db->select('id_invoice, invoice_number, balance');
                $this->db->where('ifnull(reference_invoice_number,"") <>', '');
                 $this->db->where('id_invoice <>', $invoice_id);
                $this->db->where('visit_id=', $visitid);
                $this->db->where('invoice_status=', 'valid');
                $this->db->order_by('id_invoice','DESC');
                $this->db->limit(1);
                $query=$this->db->get('invoice');

                $referencing_invoices =  $query->num_rows();
                $referencing_i = $query->result_array();
                if($referencing_invoices > 0){
                    $referencing_number=$referencing_i[0]['invoice_number'];
                    return "error|Balance from this invoice has been recovered in a later invoice ". $referencing_number.". Please Cancel the latest invoice first!";
                }   else {
                
                    
                    // change invoice status
                    $this->db->where('id_invoice', $invoice_id);
                    $this->db->update('invoice', array('invoice_status' => 'cancelled', 'cancelreason' => $reason, 'cancelled_by' => $this->session->userdata('username')));
                    
                    //change account voucher status
                    $this->db->where('invoice_id', $invoice_id);
                    $this->db->update('account_vouchers', array('voucher_status' => 'cancelled', 'cancelled_by' => $this->session->userdata('username')));
                    
                    
                    // change customer visits status
                    $this->db->where('id_customer_visits', $visit_order_id);
                    $this->db->update('customer_visits', array('visit_status' => 'open'));
                    
                                       
                }             
                
                
            } else{
                //check if there are any referencing invoices
                $this->db->select('id_invoice, invoice_number, balance');
                $this->db->where('ifnull(reference_invoice_number,"") <>', '');
                 $this->db->where('id_invoice <>', $invoice_id);
                $this->db->where('visit_id=', $visitid);
                $this->db->where('invoice_status=', 'valid');
                $this->db->order_by('id_invoice','DESC');
                $this->db->limit(1);
                $query=$this->db->get('invoice');

                $referencing_invoices =  $query->num_rows();
                $referencing_i = $query->result_array();
                
                if($referencing_invoices > 0){
                    $referencing_number=$referencing_i[0]['invoice_number'];
                    return "error|Balance from this invoice has been recovered in a later invoice ". $referencing_number.". Please Cancel the latest invoice first!";
                }   else {
                    $details = $this->getinvoiceproducts($invoice_id);

                    $qty = $details[0]['invoice_qty'];
                    $product_name = $details[0]['product_name'];

                    $product = $this->getproductbyname($product_name);


                    // change invoice status
                    $this->db->where('id_invoice', $invoice_id);
                    $this->db->update('invoice', array('invoice_status' => 'cancelled', 'cancelreason' => $reason, 'cancelled_by' => $this->session->userdata('username')));

                    //change account voucher status
                    $this->db->where('invoice_id', $invoice_id);
                    $this->db->update('account_vouchers', array('voucher_status' => 'cancelled', 'cancelled_by' => $this->session->userdata('username'), 'cancelled_on' => date('Y-m-d H:i:s')));
                    
                    // change customer visits status
                    $this->db->where('id_customer_order', $visit_order_id);
                    $this->db->update('customer_orders', array('order_status' => 'open'));

                }
            }
        }
        
        return "success|".$invoice_id;
    }
    
    function getpackageinvoicebyids($invoice_ids){
        $this->db->select('*, sum(net_amount) as netTotal, sum(gross_amount) as grossTotal, sum(paid_amount) as paidTotal, sum(returnamount) as returnTotal, sum(balance) as balanceTotal, invoice.created_by as created_by');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where_in('id_invoice', $invoice_ids);
        $query = $this->db->get('invoice');
        return $query->result_array();
    }
    
    function check_invoice_recoverable($invoiceid){
        $this->db->select('is_recovery, customer_id, id_invoice');
        //$this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->where('id_invoice', $invoiceid);
        $query = $this->db->get('invoice');
        return $query->row();
    }
    
    function getinvoicebyid($invoiceid){
        $this->db->select('*,date_format(invoice_date,"%d-%m-%Y") as invoice_date, date_format(invoice_date,"%H:%i") as invoice_time, invoice.created_by as created_by');
        $this->db->join('customers', 'customers.id_customers = invoice.customer_id');
       // $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->where('invoice.id_invoice=', $invoiceid);
        $query = $this->db->get('invoice');
        
        return $query->result_array();
    }
    
    function getinvoicebyno($invoiceno){
        $this->db->select('*,date_format(invoice_date,"%d-%m-%Y %H:%i") as invoice_date, date_format(invoice_date,"%H:%i") as invoice_time,  invoice.created_by as created_by');
       // $this->db->where('invoice.business_id', $this->session->userdata('businessid'));
        $this->db->where('invoice.invoice_number=', $invoiceno);
        $query = $this->db->get('invoice');
        
        return $query->result_array();
    }
    
    function getpackageinvoicedetails($invoice_ids){
        $this->db->select('invoice_details.*');
        $this->db->join('invoice', 'invoice.id_invoice = invoice_details.invoice_id');
        $this->db->where('invoice_details.business_id', $this->session->userdata('businessid'));
        $this->db->where_in('invoice_id', $invoice_ids);
        $this->db->order_by('invoice.visit_time, invoice_details.invoice_detail_date');
        $query = $this->db->get('invoice_details');
        
        return $query->result_array();
    }
    
    function getinvoicedetails($invoiceid){
        $this->db->select('*');
        $this->db->where('invoice_details.invoice_id=', $invoiceid);
        $query = $this->db->get('invoice_details');
        
        return $query->result_array();
    }
    
    function getalreadypaidservice($visitid, $serviceid){
        //get already paid for this service
            $this->db->select('sum(paid) as alreadypaid');
            $this->db->join('invoice','invoice.id_invoice = invoice_details.invoice_id');
            $this->db->where('invoice.visit_id', $visitid);
            $this->db->where('invoice.invoice_status','valid');
            $this->db->where('invoice_details.service_id', $serviceid);
            $this->db->group_by('invoice_details.service_id');
            $query = $this->db->get('invoice_details');
        
        return $query->row();
    }
    function alreadypaidinvoice($visitid){
        
        $this->db->select(' visit_id, total_payable, sum(paid_amount) as alreadypaid');
        $this->db->where('visit_id',$visitid);
        $this->db->where('invoice_status', 'valid');
        $this->db->group_by('visit_id');
        $query = $this->db->get('invoice');
        return $query->row();
    }
    
    function getinvoicestaff($invoiceid){
        $this->db->select('*');
        $this->db->where('invoice_staff.invoice_id=', $invoiceid);
        $query = $this->db->get('invoice_staff');
        
        return $query->result_array();
        
        
    }
    
    function getinvoiceproducts($invoiceid){
        $this->db->select('*');
        $this->db->where('invoice_products.invoice_id=', $invoiceid);
        $query = $this->db->get('invoice_products');
        
        return $query->result_array();
    }
    
    
    function getinvocietaxes($invoiceid){
        $this->db->select('*');
        $this->db->where('invoice_taxes.invoice_id=', $invoiceid);
        $query = $this->db->get('invoice_taxes');
        
        return $query->result_array();
    }
    
    function nextvisitreturn($cur_staffid, $visitid){
        
        $cur_visit_id=0;
        
        $this->db->select('id_customer_visits');
        $this->db->join('customer_visits', 'customer_visits.id_customer_visits= visit_services.customer_visit_id');
        $this->db->join('visit_service_staffs', 'visit_services.id_visit_services = visit_service_staffs.visit_service_id');
        $this->db->where('customer_visits.visit_status','open');
        $this->db->where('visit_service_staffs.staff_id like',$cur_staffid);
        $this->db->where('customer_visits.id_customer_visits <>',$visitid);
        $this->db->where('visit_services.business_id', $this->session->userdata('businessid'));
        $this->db->where('visit_services.visit_service_status','Active');
        $this->db->order_by('id_customer_visits', 'DESC');
        $this->db->limit(1);
        $nextvisitnumber=$this->db->get('visit_services');

        foreach ($nextvisitnumber->result() as $row){
            
            $cur_visit_id = $row->id_customer_visits;
            
        }
       
        return $cur_visit_id;
        
    }
    
    function discount_login() {
        $username = $this->db->escape_str($this->input->post('discount_username', TRUE));
        $password = md5($this->db->escape_str($this->input->post('discount_password', TRUE)));
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('username', $username);
        $this->db->where('password', $password);
        $query = $this->db->get('discount_password');
        
        return $query->row();
    }
    
    function invoice_service_product($serviceid){
        $this->db->select('sp.business_product_id, sp.business_service_id, bp.product, bp.id_business_products');
        $this->db->join('business_products bp', 'bp.id_business_products = sp.business_product_id');
        $this->db->where('sp.business_service_id', $serviceid);
        $result = $this->db->get('services_products sp');
        
        return $result->result_array();
    }
    
    function invoice_service_product_update(){
        $product_id = $this->input->post('product_id', TRUE) ? $this->input->post('product_id', TRUE) : NULL;
        $product_name = $this->input->post('product_name', TRUE) ? $this->input->post('product_name', TRUE) : NULL;
        
        $this->db->where('visit_service_id', $this->input->post('visit_service_id', TRUE));
        $this->db->where('customer_visit_id', $this->input->post('customer_visit_id', TRUE));
        $delete_visit_product = $this->db->delete('visit_service_products');
        $data = array();
        if ($delete_visit_product) {
            if ($product_id && $product_id != NULL) {
                for ($i = 0; $i < sizeof($product_id); $i++) {
                    $data[] = array(
                        'customer_visit_id' => $this->input->post('customer_visit_id', TRUE),
                        'visit_service_id' => $this->input->post('visit_service_id', TRUE),
                        'product_id' => $product_id[$i],
                        'product_name' => $product_name[$i],
                        'business_id' => $this->session->userdata('businessid')
                    );
                }
                $this->db->insert_batch('visit_service_products', $data);
                return $this->input->post('visit_service_id');
            } else {
                return $this->input->post('visit_service_id');
            }
        }
    }
    
    public function get_advance_byid($visitid){
        $this->db->select('sum(paid_amount) as "advance"');
        $this->db->where('visit_id', $visitid);
        $this->db->where('advance', 'true');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $result = $this->db->get('invoice');
        
        return $result->result_array();
    }

    public function invoice_balance($invoiceid){
        
        $this->db->select('balance');
        $this->db->where('id_invoice', $invoiceid);
        $this->db->where('is_recovery', 'Yes');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $result = $this->db->get('invoice');
        
        return $result->result_array();
        
    }
    
    public function invoice_sms_update($invoiceid, $sendsms){
        
        if($sendsms !== 'SMS Service is not setup!'){
            $pos= strpos($sendsms, '<?xml version="1.0" encoding="utf-8"?>');
            $myXMLData= substr($sendsms, $pos);
            $xml = simplexml_load_string($myXMLData);
            $this->db->set('sms_log', 'error:'.$xml->error.' status:'.$xml->status.' msg:'.$xml->msgdata.' receiver:'.$xml->receiver);
        } else {
            $this->db->set('sms_log', 'error:'.$sendsms);        
        }
        
        $this->db->where('id_invoice',$invoiceid);
        $this->db->update('invoice');
        
        return $invoiceid;
        
    }
    public function get_day_retail_count($sh=false){
        
        $today=$today = date('Y-m-d');
        
        $this->db->select("count(id_invoice) invoices",false);
        $this->db->where("date_format(invoice_date, '%Y-%m-%d')=",$today);
        $this->db->where("invoice_type =","sale");
        if($sh==true || $this->session->userdata('role')=='Sh-Users'){
             $this->db->where("invoice_seq >",0);
        }
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $result = $this->db->get('invoice');
        
        return $result->row();
    }
    
    public function get_day_services_count($sh=false){
        
        $today=$today = date('Y-m-d');
        
        $this->db->select("count(id_invoice) invoices",false);
        $this->db->where("date_format(invoice_date, '%Y-%m-%d')=",$today);
        $this->db->where("invoice_type =","service");
         if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
            $this->db->where('invoice.invoice_seq > ', 0);
        }
        
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $result = $this->db->get('invoice');
        
        return $result->row();
        
    }

   
    public function get_discounttypes(){
        
        $this->db->select("id_discount_reasons, discount_reason, discount_perc",false);
      
      //  $this->db->where('business_id', $this->session->userdata('businessid'));
        $result = $this->db->get('discount_reasons');
        return $result->result_array();
    }
    
    public function update_feedback($invoiceid, $status){
        
        $this->db->set('feedback_status',$status);
        $this->db->where('id_invoice',$invoiceid);
        $this->db->update('invoice');
        
        return $invoiceid;
        
    }
    
    
    public function create_order_invoice(){
        //exit();
        $orderid=$this->input->post('orderid', TRUE);
        
        // Unescape the string values in the JSON array
        $tableData = $_POST['tabledata'];
        //exit();
        $total_qty = 0;
        $total_price = 0;
        $today = date('Y-m-d');
        $stopproduct='';
        
        foreach($tableData as $row){  
            if($row['batch_id']>0){
                //check qty in selected batch
                $this_batches = $this->product_model->get_a_batch($row['batch_id'], $today);
                if($this_batches->total_stock <  $row['product_qty']){
                    $stopproduct=$row['productname'];
                    return('error|Stock Qty is lower in batch '.$row['batch'] .' then the Ordered Qty for '.$stopproduct);
                    exit();
                }
            }
        }
       
       ///insert new invoice
       
       ///insert new invoice_products
       
       ///insert new invoice tax
       
       ///create account voucher
       
//        $product_ids=$this->input->post('product_ids', TRUE);
        $orderid=$this->input->post('orderid', TRUE);
        
        //Get order products
        $this->db->select('business_brands.id_business_brands,
                            business_brands.business_brand_name,
                            business_products.product,
                            order_products.staff_name,
                            order_products.staff_id,
                            order_products.qty,
                            business_products.price,
                            business_products.id_business_products as product_id,
                            business_products.category as category,
                            order_products.batch,
                            order_products.batch_id,
                            adjustment_order_id, order_status, business_products.commission, product_batch.batch_amount');
        $this->db->join('business_products', 'business_products.id_business_products = order_products.product_id');
        $this->db->join('business_brands', 'business_brands.id_business_brands = business_products.brand_id');
        $this->db->join('product_batch', 'product_batch.id_batch= order_products.batch_id');
        $this->db->join('customer_orders', 'customer_orders.id_customer_order = order_products.customer_order_id');
        $this->db->join('adjustment_notes', 'adjustment_notes.adjustment_order_id = order_products.customer_order_id and adjustment_notes.product_id = order_products.product_id', 'left');
        $this->db->where('order_products.customer_order_id', $orderid);
        $this->db->where('order_products.business_id', $this->session->userdata('businessid'));
        $this->db->group_by('product_batch.id_batch');
        $orderproducts = $this->db->get('order_products');
      //  echo $orderproducts; exit();
        
        $business= $this->business_model->get_business_details();
        //$taxperc= $this->business_model->get_tax_perc('sale');
       
        $newloyaltypoints=0;
        
        //$invoicenumber=$this->input->post('invoicenumber', TRUE);
        $invoicedate=$this->input->post('invoicedate', TRUE);
        $customerid=$this->input->post('customerid', TRUE);
        
        $subtotal=$this->input->post('subtotal', TRUE);
        $org_subtotal=$this->input->post('orgsubtotal', TRUE);
        $gross_amount=$this->input->post('grosstotal', TRUE);
        $net_amount=$this->input->post('net_amount', TRUE);
        
        $paid=$this->input->post('paid', TRUE);
        $discount=$this->input->post('discount', TRUE);
        
        $grandtotal=$this->input->post('grandtotal', TRUE);
        $totalpayable=$this->input->post('totalpayable', TRUE);
        $roundedadjustment=$this->input->post('roundedadjustment');
        
        
        $taxes=$this->input->post('taxes', TRUE);
        $taxtotal=$this->input->post('taxtotal', TRUE);
        
        $totaladdition =0;
        $totaldiscount =0;
        
        foreach($tableData as $row){            
            $taxtotal += $row['product_tax'];            
            $totaladdition += $row['product_addition'];
            $totaldiscount += $row['product_discount'];
        }
        
        $cc_charge=$this->input->post('cc_charge', TRUE);
        $paymentmode=$this->input->post('mode', TRUE);
        $cashpaid=0;$cardpaid=0;$voucherpaid=0;$checkpaid=0;
                
        $instrumentnumber= $paymentmode=='Online' ? 'Online '.$this->input->post('instrument_number', TRUE) :  $this->input->post('instrument_number', TRUE);
        $balance=$this->input->post('balance');
        $returnamount=$this->input->post('returnamount');
        //$product_discount=$this->input->post('product_discount', TRUE);
        //$discounted_price=$this->input->post('discounted_price', TRUE);
        
        $customer_advance=$this->input->post('customer_advance', TRUE);
        $retained_used=$this->input->post('retained_used', TRUE);
        $retained_amount_used=$this->input->post('retained_amount_used', TRUE);
        $remaining_retained=$this->input->post('remaining_retained', TRUE);
        
        $cctip = $this->input->post('cctip', TRUE);
        
        $advance_amount=$this->input->post('advance_amount',TRUE);
        
        $other_charges=$this->input->post('other_charges',TRUE);
        //$serivce_flag=$this->input->post('service_flag',TRUE);
        
        $totalpaid= $advance_amount+$paid;
        $totalpaidnow= $totalpaid;
        
        if($paymentmode=="Cash"){$cashpaid=$paid;}
        else if($paymentmode=="Card"){$cardpaid=$paid;}
        else if($paymentmode=="Check"){$checkpaid=$paid;}
        else if($paymentmode=="Online"){$checkpaid=$paid; $paymentmode='Check';}
        else if($paymentmode=="Voucher"){$voucherpaid=$paid;}
        else if($paymentmode=="Mixed"){
            $cashpaid=$this->input->post('cashpaid', TRUE);
            $cardpaid=$this->input->post('cardpaid', TRUE);
            $totalpaidnow = $cashpaid + $cardpaid;
        } 
         
        //Loyalty
        $loyaltyused=$this->input->post('loyaltyused',TRUE);
        $loyaltyvalue=$this->input->post('loyaltyvalue',TRUE);
        $loyaltyenabled=$this->input->post('loyaltyenabled',TRUE);
        //$sloyaltyenabled=$this->input->post('sloyaltyenabled',TRUE);
        $rloyaltyenabled=$this->input->post('rloyaltyenabled',TRUE);
        
        if($loyaltyenabled=='Y' && $rloyaltyenabled=="Y") {$loyaltyearned=(Float)$totalpaid/ (Float)$loyaltyvalue;}
        else {$loyaltyearned=0;}
        if($loyaltyearned < 0){$loyaltyearned=0;}        
        //Get customer & order
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
        $this->db->where('customer_orders.id_customer_order', $orderid);
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        $customerorders = $this->db->get('customer_orders');
       
        $customerorder = $customerorders->row();
        
        $insertloyalty = true;
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){
                $insertloyalty=false;
            }
        }
        $loyaltyearned= (float)$discount == 0 ? ((float)$loyaltyused == 0 ? $loyaltyearned : 0) : 0;
        //print_r($other_charges); exit();
        //Create invoice    
        $invoice_date=$invoicedate;
        $visittime=$invoicedate;
        $customername=$customerorder->customer_name;
        $data = array(
            'customer_id'=>$customerid,
            'invoice_number'=>'999',
            'business_id'=>$this->session->userdata('businessid'),
            'customer_name'=> $customerorder->customer_name,
            'customer_cell'=> $customerorder->customer_cell,
            'customer_email'=> $customerorder->customer_email,
            'customer_address'=> $customerorder->customer_address,
            'tax_total'=>$taxtotal,
            'paid_amount' => $paid,
            'paid_cash' => $cashpaid,
            'paid_card' => $cardpaid,
            'paid_voucher' => $voucherpaid,
            'paid_check' => $checkpaid,
            'discount' => $discount,
            'gross_amount' => $gross_amount + $taxtotal,
            'gross_wo_tax' => $gross_amount,
            'net_amount' => $net_amount,
            'visit_id' => $orderid,
            'visit_time' => $visittime,
            'sub_total' => $org_subtotal ,
            'invoice_type'=>'sale',
            'payment_mode'=>$paymentmode,
            'instrument_number'=>$instrumentnumber,
            'cc_charge'=>$cc_charge,
            'balance'=>$balance,
            'is_recovery' => $balance > 0 ? 'Yes' : 'No',
            'discount_remarks' => $this->input->post('discount_remarks'),
            'returnamount' => $customer_advance==='false' ? $returnamount: 0,
            'loyalty_used'=> $insertloyalty == true ? $loyaltyused : 0,
            'loyalty_earned'=> $insertloyalty==true ? $loyaltyearned : 0,
            'advance_amount'=>$advance_amount,
            'other_charges'=>$other_charges + $totaladdition,
            'invoice_date'=>$invoice_date,
            'retained_used'=>$retained_used,
            'retained_amount_used'=>$retained_amount_used,
            'retained_amount'=>$customer_advance==='true' ? $returnamount : 0,
            'cctip'=>$cctip,            
            'total_payable'=>$totalpayable,
            'created_by' => $this->session->userdata('username')
        );
        //print_r($data); exit();
        
        $this->db->insert('invoice', $data);
        $invoiceid =  $this->db->insert_id();
        
        //make sure invoice number is correct
         $today=date('Y-m-d');
        $seq=1;        
        $sql = "select max(invoice_seq)+1 as 'seq'
            from invoice where day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}
           
        if(isset($business[0]['r_auto_sh'])){
            if($business[0]['r_auto_sh']=='No'){
                $seq=0;
            }
        }
        
        
        $update_invoice = array(
            'invoice_number' => date('Y-m').'-'.$invoiceid,
            'invoice_seq' => $seq
        ); 
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        //////////////////
        
         ///update customer advance
        if ($customer_advance==='true'){
            $newval=$returnamount + $remaining_retained;
        } else {
            $newval=$remaining_retained;
        }
        $this->db->set('customer_advance', $newval);
        $this->db->where('id_customers',$customerid);
        $this->db->update('customers');
        //////////
        
        //Update Loyalty
        if($loyaltyenabled=='Y' && $rloyaltyenabled=='Y'){
            $this->db->select('loyalty_points');
            $this->db->where('id_customers =',$customerid);
            $existingpoint = $this->db->get('customers');
            $existingpoints = $existingpoint->result_array();
            
            $newloyaltypoints=(Float)$existingpoints[0]['loyalty_points'];
            if($loyaltyused>0){
                $newloyaltypoints= (Float)$existingpoints[0]['loyalty_points'] - $loyaltyused;
            }
            $calloyaltypoints=0;
            if($totalpaid>0){
                $calloyaltypoints = $totalpaid / $loyaltyvalue;
            }
            $newloyaltypoints=$newloyaltypoints+$calloyaltypoints;
            
            $this->db->where('id_customers = ', $customerid);
            $this->db->update('customers', array('loyalty_points'=>$newloyaltypoints));        
            
        }
        /////
        $this->disount_invoice_user_insert($invoiceid);
        
        
        //insert product sales tax
        foreach($tableData as $row){
            $data=array(
                'invoice_id'=>$invoiceid,
                'business_id'=>$this->session->userdata('businessid'),
                'invoice_tax_name'=> 'Sales Tax',
                'invoice_tax'=>$row['product_tax']
            );
            $this->db->insert('invoice_taxes', $data);
        }
        
        //insert invoice taxes
        if(isset($taxes)){
            foreach($taxes as $tax){
                $data=array(
                    'invoice_id'=>$invoiceid,
                    'business_id'=>$this->session->userdata('businessid'),
                    'invoice_tax_name'=>$tax['taxname'],
                    'invoice_tax'=>$tax['tax']
                );
                $this->db->insert('invoice_taxes', $data);
            }
        }
        
        //insert invoice products
        $k=0;
        //foreach ($orderproducts1 as $orderproduct)
        $b=0;
        
        
        
        $totalproductdiscount=0;
        $batch_amount=0;        
        $remainingsub=$subtotal; 
        $remainingpaid=$paid+$advance_amount; 
        
        $total_service_additions=0;
        $product_cog = [];
        //foreach($orderproducts->result() as $orderproduct)
        foreach($tableData as $row){ 
            
            $product_paid=0;
            
            if($row['product_total'] < $remainingpaid){
                $product_paid = $row['product_total'];
            }else{
                if($remainingpaid > 0){
                    $product_paid = $remainingpaid;
                } else {
                    $product_paid=0;
                }
            }
            
            //$remainingsub = $remainingsub - $row['product_total'];
            $remainingpaid = $remainingpaid - $product_paid;
            
            //get commission perc
            if($row['batch_id']>0){
                $this->db->select('product, category, ifnull(commission,0) as commission, ifnull(batch_amount,0) as batch_amount, track_inventory');
                $this->db->join('product_batch', 'product_id = id_business_products');
                $this->db->where('id_business_products', $row['productid']);
                $this->db->where('id_batch', $row['batch_id']); 
            }else{
                $this->db->select('product, category, ifnull(commission,0) as commission, ifnull(purchase_price,0) as batch_amount, track_inventory');
                $this->db->where('id_business_products', $row['productid']);                
            }
            $query = $this->db->get('business_products');
            
            $product = $query->row();
            
            //print_r($product); exit();
            
            $commission_perc = $product->commission;
            $product_batch_amount = $product->batch_amount;
            
            $product_cog[$row['batch_id']] = $product_batch_amount * $row['product_qty'];
            
            $category = $product->category;
            
            $totalproductdiscount += $row['product_discount'];
            $total_service_additions += $row['product_addition'];
            
            $commission = (($product_paid- $row['product_tax']) * $commission_perc) / 100;
            $commission = round($commission, 2);
            
            
            //get batch amount
            $tot_prod_batch_amount = (float)$product_batch_amount * $row['product_qty'];
            $batch_amount = round($batch_amount +  $tot_prod_batch_amount,2);
            
            //$product_batch_amount = round((float)$batch_amount,2); 
            
            
            $products= array(
                'invoice_id'=>$invoiceid,
                'business_id'=>$this->session->userdata('businessid'),
                'brand_name'=>$row['brandname'],
                'product_name'=>$row['productname'],
                'staff_name'=>$row['staff_name'],
                'staff_id'=>$row['staff_id'],
                'invoice_qty'=>$row['product_qty'],
                'price'=>$row['unitprice'],
                'service_addition'=>$row['product_addition'],
                'discount'=>$row['product_discount'],                
                'discounted_price'=>$row['product_subtotal'],
                'invoice_discount'=>0,
                'final_price'=>$row['product_total'],
                'taxes'=>$row['product_tax'],
                'paid'=>$product_paid,
                'product_id'=>$row['productid'],
                'category'=>$category,
                'batch' => $row['batch'],
                'batch_id'=>$row['batch_id'],
                'commission'=>$commission                
            );
            
            
            $this->db->insert('invoice_products', $products);
            $invoice_detail_id=$this->db->insert_id();
            if ($this->db->field_exists('cog_amount', 'invoice_products')){
                $this->db->set('cog_amount', $tot_prod_batch_amount);
                $this->db->where('id_invoice_products', $invoice_detail_id);
                $this->db->update('invoice_products');
            }
            
            //insert staff sale
            $amount=$row['unitprice']*$row['product_qty'];
            
            $staffsale=array(
                'invoice_id'=>$invoiceid,
                'invoice_detail_id' =>  $invoice_detail_id,
                'business_id'=>$this->session->userdata('businessid'),
                'order_id'=>$orderid,
                'staff_id'=>$row['staff_id'],
                'staff_name'=>$row['staff_name'],
                'brand_name'=>$row['brandname'],
                'product_name'=>$row['productname'],
                'price'=>$amount,
                'sale_type'=>'sale',
                'qty'=>$row['product_qty'],
                'discount'=>$row['product_discount'],
                'discounted_price'=>$row['product_subtotal'],
                'paid'=>$product_paid
            );
            $this->db->insert('staff_services', $staffsale);                
            $k++;
        }
        
        $this->db->where('adjustment_order_id', $orderid);
        $this->db->delete('adjustment_notes');
        
        
         ///create retail sale voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(1);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Retail Sale Voucher against invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $totalpayable,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername,
                'voucher_type'=>2,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'sale'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount+$cashpaid : $cashpaid;}
                if($debit[2]=="paid_card" && $cardpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount+$cardpaid : $cardpaid;}
                if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $checkpaid : $checkpaid;}
                if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $voucherpaid : $voucherpaid;}
                
                if($debit[2]=="balance"){$debitamount= $balance;}
                if($debit[2]=="sale_discount_retail"){$debitamount= $totalproductdiscount + $discount;}
                if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}
                                
                if($debit[2]=="advance_adjusted"){
                    if($retained_amount_used==0 && $advance_amount > 0){
                        $debitamount= $advance_amount;
                    } elseif($retained_amount_used>0 && $advance_amount > 0) {
                        $debitamount= $advance_amount-$retained_amount_used;                        
                    } 
                }    
                
                if($debit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment < 0){
                       
                        $debitamount=$roundedadjustment*-1;
                    }
                    
                }
                if(defined('LOYALTY_VOUCHER')){                    
                    if(LOYALTY_VOUCHER==TRUE){
                        if($debit[2]=="loyalty_amount"){
                            if($loyaltyused>0){ //if discount is actually loyalty points
                                $debitamount= 0;
                            
                                //see if we need to bring the loyalty points in from HO
                                $my_business = $this->check_if_ho();
                                //bring the points from ho
                                if($my_business != $this->session->userdata('businessid')){
                                    $this->bring_in_ho_points($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                                }   

                                $this->create_loyalty_used_voucher($this->session->userdata('businessid'),$loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                                $debitamount= 0; // make sure
                            }                 
                        }
                    }
                }
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                if($credit[2]=="grosstotal_retail"){$creditamount= $org_subtotal + $total_service_additions;}                
                if($credit[2]=="sales_tax"){$creditamount= $taxtotal;}
                if($credit[2]=="cc_fee"){$creditamount= $cc_charge;}
                if($credit[2]=="retained_amount"){$creditamount= $customer_advance==='true' ? $returnamount: 0;}
                if($credit[2]=="cc_tip"){$creditamount= $cctip;}
                //if($credit[2]=="additional_charges"){$creditamount= $totaladdition;}
                
                if($totalpaidnow > $totalpayable+$roundedadjustment){
                    if($credit[2]=="return_cash"){$creditamount= $customer_advance==='false' ? $returnamount: 0;}
                }
                if($credit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment > 0){
                        
                        $creditamount=$roundedadjustment; 
                    }                    
                }
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            ///create loyalty voucher
            if(defined('LOYALTY_VOUCHER')){                    
                if(LOYALTY_VOUCHER==TRUE){
                    if($loyaltyearned > 0){
                        $my_business= $this->check_if_ho();            
                        $this->add_loyalty_points_ho($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                    }
                }
            }

            if($product->track_inventory=='Yes'){
                //create inventory and cost of goods voucher/////////////////////////////////
                $debit_accounts=[];
                $credit_accounts=[];

                $account_heads = $this->accounting_model->get_mapped_accounts(23);
                //var_dump ($account_heads); exit();
                foreach($account_heads as $ah){
                    if($ah['transaction_type']=='debit'){
                       array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                    } else {
                        array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                    }
                }

                $bank_name='';
                $batch_amount = round($batch_amount,2);
                //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
                $data = array( 
                    'business_id' => $this->session->userdata('businessid'),
                    'description' => 'Cost of Goods Solds Voucher against reference voucher ID '. $account_voucherid . ' invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                    'voucher_date' => date('Y-m-d H:i:s'),
                    'voucher_amount' => $batch_amount,
                    'voucher_status' => 'Active',
                    'created_by' => $this->session->userdata('username'),
                    'cost_center'=> '1',
                    'cost_center_name'=> 'Front Desk',
                    'business_partner'=> 1,
                    'business_partner_id'=>$customerid,
                    'business_partner_name'=>$customername,
                    'voucher_type'=>3,
                    'payment_mode'=>$paymentmode,
                    'bank_name'=>$bank_name,
                    'invoice_id'=>$invoiceid,
                    'auto_voucher'=>'Yes',
                    //'sale_type'=>'sale'
                );

                $this->db->insert('account_vouchers', $data);
                $cogs_voucherid =  $this->db->insert_id();

                //enter debit entries
                $total_cog = 0;
                foreach($debit_accounts as $debit_account){
                    $debitamount=0;
                    $debit = explode("|", $debit_account);
                    //check entity

                    if($debit[2]=="cogs"){                    
                        foreach($tableData as $row){
                            $debitamount= $product_cog[$row['batch_id']];
                            $total_cog = $total_cog + $product_cog[$row['batch_id']];
                           // $debitamount= $debitamount * $product_cog[$row['batch_id']];
                            $data_detail=array(
                                'account_voucher_id' => $cogs_voucherid,
                                'account_head_id' => $debit[0],
                                'instrument_number' => $instrumentnumber,
                                'detail_remarks' => $row['productid'],
                                'debit' => round($debitamount,2),
                                'credit' => 0
                            );
                            //insert debit detail
                            if($debitamount>0){
                                $this->db->insert('account_voucher_detail', $data_detail);
                            }
                        }
                    }
                }
                //enter credit entries
                foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                
                //if($credit[2]=="inventory"){$creditamount= $batch_amount;}
                if($credit[2]=="inventory"){$creditamount= $total_cog;}
                
                $data_detail=array(
                    'account_voucher_id' => $cogs_voucherid,
                    'account_head_id' => $credit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            }
        }
        
        
        //update customer order (mark as invoiced)
        $this->db->set('order_status', 'invoiced');
        $this->db->where('id_customer_order', $orderid);
        $this->db->update('customer_orders');
        //return "success|".$invoiceid;
        
        
        $mypaid = $customer_advance==='true' ? $advance_amount + $returnamount + $paid : $advance_amount + $paid;
        return $invoiceid.'|'.$loyaltyearned.'|'.$totalpayable.'|'.$mypaid.'|'.$balance;
       
       
       
    }
    


    // ===============> jun-14-2024  start <================== 
      // for pos  
      public function create_order_invoice_for_pos(){ 
        $orderid=$this->input->post('orderid', TRUE);
        // Unescape the string values in the JSON array
        $tableData = $_POST['tabledata']; 
        $total_qty = 0;
        $total_price = 0;
        $today = date('Y-m-d');
        $stopproduct='';         
        // Validation For purpose Start From Here 
        $selected_batch_data=[];
        foreach($tableData as $row){  
            // Saif Code start From Here
            $sql="SELECT  `business_products`.`product_type` ,  `business_products`.`track_inventory` , ifnull(commission,0) as commission , `business_products`.`category` , `business_products`.`purchase_price`  FROM `business_products`  where id_business_products=?";
            $resp = $this->db->query($sql, array($row['productid']));
            $products_data_with_type_and_inventry = $resp->row(); 
            $product_type= $products_data_with_type_and_inventry->product_type;
            $track_inventory = $products_data_with_type_and_inventry->track_inventory; 
            $category = $products_data_with_type_and_inventry->category; 
            $purchase_price = $products_data_with_type_and_inventry->purchase_price;  
              if($product_type =="Physical"){     
                    // =================================> checking Track Inventry <=========================== 
                       if($track_inventory =="Yes"){
                                            $sql="SELECT *, 
                                            ifnull(e.addition, 0) as manualQty,
                                            ifnull(e.qty_purchased, 0) as purchasedQty,
                                            ifnull(e.transfer_in, 0) as transfer_in,
                                            ifnull(e.transfer_out, 0) as transfer_out,
                                            ifnull(e.sold,0) + ifnull(e.franchise_sale,0) as sold,
                                            ifnull(e.franchise_sale,0) as franchise_sale,
                                            ifnull(e.used,0) as used,
                                            ifnull(e.returned,0) as returned,
                                            (ifnull(e.addition, 0) + ifnull(e.qty_purchased, 0) + ifnull(e.transfer_in, 0)) - (ifnull(e.transfer_out, 0) + ifnull(e.sold, 0) + ifnull(e.used, 0) + ifnull(e.returned, 0) + ifnull(e.franchise_sale,0)) as total_stock,
                                            date_format(expiry_date, '%d-%m-%Y') as 'batch_expiry', 
                                            round(datediff(expiry_date, now())/30) as expiry,
                                            date_format(batch_date, '%d-%m-%Y') as 'bdate' , batch_amount
                                            FROM business_products
                                            LEFT JOIN
                                            (
                                            select id_batch, batch_number, batch_date, expiry_date, batch_qty, qty_purchased,
                                            product_batch.product_id, business_store, transfer_in, transfer_out,
                                            sold, used, returned, batch_amount, addition, franchise_sale, store_id, business_stores.business_id
                                            from 
                                        product_batch 
                                                    LEFT join business_stores on business_stores.id_business_stores = product_batch.store_id 
                                                    LEFT join(
                                                            SELECT batch_id, sum(adjustment_qty) as addition FROM adjustment_notes
                                                            group by batch_id
                                                    ) as adj
                                                    on adj.batch_id = product_batch.id_batch
                                            LEFT Join (
                                                SELECT batch_id, product_id, sum(invoice_qty) as sold FROM invoice_products
                                                join invoice on invoice.id_invoice = invoice_products.invoice_id
                                                and invoice_status = 'valid'
                                                            and ifnull(reference_invoice_number,'') = ''
                                                and batch_id is not null
                                                group by batch_id, product_id
                                            ) as a
                                            on a.product_id = product_batch.product_id 
                                            and a.batch_id=product_batch.id_batch
                                            left join(
                                                SELECT product_id, batch, batch_id, sum(ifnull(dispatch_qty,0)) as used 
                                                FROM dispatch_notes                        
                                                where status = 'Active'
                                                and batch_id is not null
                                                group by product_id, batch, batch_id
                                            ) as b
                                            on b.product_id = product_batch.product_id
                                            and b.batch_id = product_batch.id_batch
                                            left join(
                                                SELECT product_id, batch_id, sum(ifnull(return_qty,0)) as returned
                                                FROM return_notes
                                                where return_status = 'Active'
                                                and batch_id is not null
                                                group by product_id,  batch_id
                                            ) as c
                                            on c.product_id = product_batch.product_id
                                            and c.batch_id = product_batch.id_batch
                                                    left join(
                                                SELECT grn_product_id, grn_batch_id, sum(ifnull(grn_qty_received,0)) as qty_purchased
                                                FROM grn_details
                                                where grn_batch_id is not null
                                                group by grn_product_id,  grn_batch_id
                                            ) as d
                                            on d.grn_product_id = product_batch.product_id
                                            and d.grn_batch_id = product_batch.id_batch
                                                    left join(
                                                SELECT product_id, batch_id, sum(ifnull(tranfer_out_qty,0)) as transfer_out, sum(ifnull(tranfer_in_qty,0)) as transfer_in 
                                                FROM transfer_notes
                                                where batch_id is not null 
                                                            and transfer_notes.status='Active' 
                                                group by product_id, batch_id
                                            ) as f
                                                    on f.product_id = product_batch.product_id
                                            and f.batch_id = product_batch.id_batch
                                                    left join(
                                                SELECT product_id, batch_id, sum(ifnull(qty,0)) as franchise_sale
                                                FROM franchise_orders
                                                            join franchise_order_products on franchise_orders.id_franchise_orders = franchise_order_products.franchise_order_id
                                                where batch_id is not null
                                                            and (franchise_orders.order_status='Paid' OR franchise_orders.order_status='Invoiced')                         
                                                group by product_id, batch_id
                                                            ) as h
                                                            on h.batch_id = product_batch.id_batch 
                                                            and  h.product_id = product_batch.product_id
                                            ) as e ON e.product_id = business_products.id_business_products WHERE id_business_products = ? ";

                                            $resp = $this->db->query($sql, array($row['productid']));
                                            $batchData = $resp->result(); 
                                        $product_name =   $row['productname'];
                                            $batchDataCount = count($batchData);
                                            $each_product_qty =  $row['product_qty'];
                                            if(  $batchDataCount  < 1){
                                                    // $warning_msg_list[] ="$product_name =>  Available Stock: 0, Required Stock: $each_product_qty"; 
                                                           return('error|'.$product_name .' =>   Available Stock: 0,  Required Stock :'.$each_product_qty);
                                                            exit();
                                            }
                                            $unitprice =  $row['unitprice'];
                                            $total_batches_sum=0;
                                            foreach($batchData as $batch_data){
                                                if($batch_data->total_stock > 0){
                                                    $total_batches_sum+=$batch_data->total_stock;
                                                }
                                            }
                                            if($total_batches_sum < $each_product_qty){
                                                // $warning_msg_list[] = " $product_name =>  Available Stock: $total_batches_sum, Required Stock: $each_product_qty"; 
                                                return('error|'.$product_name .' =>   Available Stock: '.$total_batches_sum.',  Required Stock :'.$each_product_qty);
                                                exit();
                                            }
                                            foreach($batchData as $batch_data){
                                                if($each_product_qty==0){
                                                    break;
                                                }
                                                $total_stock = $batch_data->total_stock;
                                                $id_batch =  $batch_data->id_batch;
                                                $batch_number =  $batch_data->batch_number;
                                                $store_id =  $batch_data->store_id;
                                                        if($total_stock >= $each_product_qty){
                                                            $total_price = $unitprice * $each_product_qty;
                                                            $selected_batch_data[] =[
                                                                "product_name"=>$row['productname'],
                                                                "qty"=>$each_product_qty,
                                                                "productid"=>$row['productid'],
                                                                "batch_id"=>$id_batch,
                                                                "batch_number"=>$batch_number,
                                                                "store_id"=>$store_id,
                                                                "total_price"=>$total_price ,
                                                                "product_type"=>"Physical",
                                                                "track_inventory"=>$track_inventory
                                                            ]; 
                                                                $each_product_qty=0;
                                                                break;
                                                            }elseif( $total_stock < $each_product_qty &&  $total_stock > 0){
                                                            //   $qty_after_subtraction = $each_product_qty-$total_stock;
                                                                    $each_product_qty=$each_product_qty-$total_stock;
                                                                    $total_price = $unitprice * $total_stock;
                                                                        $selected_batch_data[]=[
                                                                            "product_name"=>$row['productname'],
                                                                            "qty"=>$total_stock,
                                                                            "productid"=>$row['productid'],
                                                                            "batch_id"=>$id_batch,
                                                                            "batch_number"=>$batch_number,
                                                                            "store_id"=>$store_id,
                                                                            "total_price"=>$total_price ,
                                                                            "product_type"=>"Physical",
                                                                            "track_inventory"=>$track_inventory
                                                                            ];  
                                                                    }
                                                        }
                                      }else{

                                         $selected_batch_data[]=[
                                            "product_name"=>$row['productname'],
                                            "qty"=>$row['product_qty'],
                                            "productid"=>$row['productid'],
                                            "batch_id"=>0,
                                            "batch_number"=>0,
                                            "store_id"=>0,
                                            "total_price"=>($row['product_qty']*$row['unitprice']),
                                            "product_type"=>"Physical",
                                            "track_inventory"=>$track_inventory
                                            ];   
                                    }                        
                       }else if($product_type =="Compiled Kit"){  

                        $sql="SELECT `kit_config`.`business_product_id` ,  `kit_config`.`kit_qty` ,  `kit_config`.`kit_measure_qty` , `kit_config`.`kit_id`,business_products.purchase_price,business_products.brand_id ,business_products.product ,business_products.unit_type  ,business_products.measure_unit , business_products.track_inventory   FROM `kit_config` 
                        inner join business_products on business_products.id_business_products = `kit_config`.`business_product_id`  where kit_id=?";
                        $resp = $this->db->query($sql, array($row['productid']));
                        $kit_inner_products  = $resp->result();
                        $kit_inner_products_count   = count($kit_inner_products);
                        // if( $kit_inner_products_count < 1){
                        //     $response = array(
                        //         'warning_msg' => "The current inventory for $product_name is insufficient to fulfill your required quantity. Total stock available: 0"
                        //     );
                        //     return  $response ;
                        // }
                                foreach( $kit_inner_products  as $kit_product_data ){
                                            $business_product_id =  $kit_product_data->business_product_id;
                                            $kit_qty =  $kit_product_data->kit_qty;
                                            $unit_price_inner_kit_product =  $kit_product_data->purchase_price;
                                            $product_name =  $kit_product_data->product;
                                            $unit_type =  $kit_product_data->unit_type;
                                            $measure_unit =  $kit_product_data->measure_unit;
                                            $track_inventory =  $kit_product_data->track_inventory; 
                             if($track_inventory =="Yes"){
                                            $sql="SELECT *, 
                                        ifnull(e.addition, 0) as manualQty,
                                        ifnull(e.qty_purchased, 0) as purchasedQty,
                                        ifnull(e.transfer_in, 0) as transfer_in,
                                        ifnull(e.transfer_out, 0) as transfer_out,
                                        ifnull(e.sold,0) + ifnull(e.franchise_sale,0) as sold,
                                        ifnull(e.franchise_sale,0) as franchise_sale,
                                        ifnull(e.used,0) as used,
                                        ifnull(e.returned,0) as returned,
                                        (ifnull(e.addition, 0) + ifnull(e.qty_purchased, 0) + ifnull(e.transfer_in, 0)) - (ifnull(e.transfer_out, 0) + ifnull(e.sold, 0) + ifnull(e.used, 0) + ifnull(e.returned, 0) + ifnull(e.franchise_sale,0)) as total_stock,
                                        date_format(expiry_date, '%d-%m-%Y') as 'batch_expiry', 
                                        round(datediff(expiry_date, now())/30) as expiry,
                                        date_format(batch_date, '%d-%m-%Y') as 'bdate' , batch_amount
                                        FROM business_products
                                        LEFT JOIN
                                        (
                                        select id_batch, batch_number, batch_date, expiry_date, batch_qty, qty_purchased,
                                        product_batch.product_id, business_store, transfer_in, transfer_out,
                                        sold, used, returned, batch_amount, addition, franchise_sale, store_id, business_stores.business_id
                                        from 
                                    product_batch 
                                                LEFT join business_stores on business_stores.id_business_stores = product_batch.store_id 
                                                LEFT join(
                                                        SELECT batch_id, sum(adjustment_qty) as addition FROM adjustment_notes
                                                        group by batch_id
                                                ) as adj
                                                on adj.batch_id = product_batch.id_batch
                                        LEFT Join (
                                            SELECT batch_id, product_id, sum(invoice_qty) as sold FROM invoice_products
                                            join invoice on invoice.id_invoice = invoice_products.invoice_id
                                            and invoice_status = 'valid'
                                                        and ifnull(reference_invoice_number,'') = ''
                                            and batch_id is not null
                                            group by batch_id, product_id
                                        ) as a
                                        on a.product_id = product_batch.product_id 
                                        and a.batch_id=product_batch.id_batch
                                        left join(
                                            SELECT product_id, batch, batch_id, sum(ifnull(dispatch_qty,0)) as used 
                                            FROM dispatch_notes                        
                                            where status = 'Active'
                                            and batch_id is not null
                                            group by product_id, batch, batch_id
                                        ) as b
                                        on b.product_id = product_batch.product_id
                                        and b.batch_id = product_batch.id_batch
                                        left join(
                                            SELECT product_id, batch_id, sum(ifnull(return_qty,0)) as returned
                                            FROM return_notes
                                            where return_status = 'Active'
                                            and batch_id is not null
                                            group by product_id,  batch_id
                                        ) as c
                                        on c.product_id = product_batch.product_id
                                        and c.batch_id = product_batch.id_batch
                                                left join(
                                            SELECT grn_product_id, grn_batch_id, sum(ifnull(grn_qty_received,0)) as qty_purchased
                                            FROM grn_details
                                            where grn_batch_id is not null
                                            group by grn_product_id,  grn_batch_id
                                        ) as d
                                        on d.grn_product_id = product_batch.product_id
                                        and d.grn_batch_id = product_batch.id_batch
                                                left join(
                                            SELECT product_id, batch_id, sum(ifnull(tranfer_out_qty,0)) as transfer_out, sum(ifnull(tranfer_in_qty,0)) as transfer_in 
                                            FROM transfer_notes
                                            where batch_id is not null 
                                                        and transfer_notes.status='Active' 
                                            group by product_id, batch_id
                                        ) as f
                                                on f.product_id = product_batch.product_id
                                        and f.batch_id = product_batch.id_batch
                                                left join(
                                            SELECT product_id, batch_id, sum(ifnull(qty,0)) as franchise_sale
                                            FROM franchise_orders
                                                        join franchise_order_products on franchise_orders.id_franchise_orders = franchise_order_products.franchise_order_id
                                            where batch_id is not null
                                                        and (franchise_orders.order_status='Paid' OR franchise_orders.order_status='Invoiced')                         
                                            group by product_id, batch_id
                                                        ) as h
                                                        on h.batch_id = product_batch.id_batch 
                                                        and  h.product_id = product_batch.product_id
                                        ) as e ON e.product_id = business_products.id_business_products WHERE id_business_products = ? ";
                        
                                            $resp = $this->db->query($sql, array($business_product_id));
                                            $batchData = $resp->result();
                        
                                            $each_product_qty =  $row['product_qty']*$kit_qty;
                                            $batchDataCount = count($batchData);
                                            if($batchDataCount  < 1){
                                                // $response = array(
                                                //     'warning_msg' => "The current inventory for $product_name is insufficient to fulfill your required quantity. Total stock available: 0"
                                                // );
                                                // return   $response; 
                                                return('error|'.$product_name .' =>   Available Stock: 0,  Required Stock :'.$each_product_qty);
                                                exit();
                                            } 

                                            $unitprice =   $unit_price_inner_kit_product;
                                            $total_batches_sum=0;
                                            foreach($batchData as $batch_data){
                                                if($batch_data->total_stock > 0){
                                                    $total_batches_sum+=$batch_data->total_stock;
                                                }
                                            }
                                            if($total_batches_sum < $each_product_qty){
                                                return('error|'.$product_name .' =>   Available Stock: '.$total_batches_sum.',  Required Stock :'.$each_product_qty);
                                                exit();
                                            }
                                            foreach($batchData as $batch_data){
                                                if($each_product_qty==0){
                                                    break;
                                                }
                                                $total_stock = $batch_data->total_stock;
                                                $id_batch =  $batch_data->id_batch;
                                                $batch_number =  $batch_data->batch_number;
                                                $store_id =  $batch_data->store_id;
                                                if($total_stock >= $each_product_qty){
                                                    $total_price =  $unit_price_inner_kit_product * $each_product_qty;
                                                    $selected_batch_data[]=[
                                                        "product_name"=>$product_name,
                                                        "qty"=>$each_product_qty,
                                                        "productid"=>$business_product_id,
                                                        "batch_id"=>$id_batch,
                                                        "batch_number"=>$batch_number,
                                                        "store_id"=>$store_id,
                                                        "total_price"=>$total_price ,
                                                        "product_type"=>"Compiled Kit",
                                                        "track_inventory"=>$track_inventory
                                                    ]; 
                                                    $each_product_qty=0;
                                                    break;
                                                }elseif( $total_stock < $each_product_qty &&  $total_stock >0){
                                                    $qty_after_subtraction = $each_product_qty-$total_stock;
                                                    $each_product_qty=$each_product_qty-$total_stock;
                                                    $total_price = $unit_price_inner_kit_product * $total_stock;
                                                    $selected_batch_data[]=[
                                                        "product_name"=>$product_name,
                                                        "qty"=>$total_stock,
                                                        "productid"=>$business_product_id,
                                                        "batch_id"=>$id_batch,
                                                        "batch_number"=>$batch_number,
                                                        "store_id"=>$store_id,
                                                        "total_price"=>$total_price ,
                                                        "product_type"=>"Compiled Kit",
                                                        "track_inventory"=>$track_inventory
                                                    ];
                                                }
                                            } 
                               }else{  

                                 $t_qty= $row['product_qty']*$kit_qty;
                                 $selected_batch_data[]=[
                                    "product_name"=>$product_name,
                                    "qty"=>$row['product_qty'],
                                    "productid"=>$business_product_id,
                                    "batch_id"=>0,
                                    "batch_number"=>0,
                                    "store_id"=>0,
                                    "total_price"=>($t_qty*$unit_price_inner_kit_product),
                                    "product_type"=>"Compiled Kit",
                                    "track_inventory"=>$track_inventory
                                    ];   

                               } 
                          }
                       }
           // Saif Code End From Here
        }  
        // Validation For purpose End Here  
        
       ///insert new invoice
       
       ///insert new invoice_products
       
       ///insert new invoice tax
       
       ///create account voucher
       
//        $product_ids=$this->input->post('product_ids', TRUE);
        $orderid=$this->input->post('orderid', TRUE);
        
        //Get order products
        $this->db->select('business_brands.id_business_brands,
                            business_brands.business_brand_name,
                            business_products.product,
                            order_products.staff_name,
                            order_products.staff_id,
                            order_products.qty,
                            business_products.price,
                            business_products.id_business_products as product_id,
                            business_products.category as category,
                            order_products.batch,
                            order_products.batch_id,
                            adjustment_order_id, order_status, business_products.commission, product_batch.batch_amount');
        $this->db->join('business_products', 'business_products.id_business_products = order_products.product_id');
        $this->db->join('business_brands', 'business_brands.id_business_brands = business_products.brand_id');
        $this->db->join('product_batch', 'product_batch.id_batch= order_products.batch_id');
        $this->db->join('customer_orders', 'customer_orders.id_customer_order = order_products.customer_order_id');
        $this->db->join('adjustment_notes', 'adjustment_notes.adjustment_order_id = order_products.customer_order_id and adjustment_notes.product_id = order_products.product_id', 'left');
        $this->db->where('order_products.customer_order_id', $orderid);
        $this->db->where('order_products.business_id', $this->session->userdata('businessid'));
        $this->db->group_by('product_batch.id_batch');
        $orderproducts = $this->db->get('order_products');
      //  echo $orderproducts; exit();
        
        $business= $this->business_model->get_business_details();
        //$taxperc= $this->business_model->get_tax_perc('sale');
       
        $newloyaltypoints=0;
        
        //$invoicenumber=$this->input->post('invoicenumber', TRUE);
        $invoicedate=$this->input->post('invoicedate', TRUE);
        $customerid=$this->input->post('customerid', TRUE);
        
        $subtotal=$this->input->post('subtotal', TRUE);
        $org_subtotal=$this->input->post('orgsubtotal', TRUE);
        $gross_amount=$this->input->post('grosstotal', TRUE);
        $net_amount=$this->input->post('net_amount', TRUE);
        
        $paid=$this->input->post('paid', TRUE);
        $discount=$this->input->post('discount', TRUE);
        
        $grandtotal=$this->input->post('grandtotal', TRUE);
        $totalpayable=$this->input->post('totalpayable', TRUE);
        $roundedadjustment=$this->input->post('roundedadjustment');
        
        
        $taxes=$this->input->post('taxes', TRUE);
        $taxtotal=$this->input->post('taxtotal', TRUE);
        
        $totaladdition =0;
        $totaldiscount =0;
        
        foreach($tableData as $row){            
            $taxtotal += $row['product_tax'];            
            $totaladdition += $row['product_addition'];
            $totaldiscount += $row['product_discount'];
        }
        
        $cc_charge=$this->input->post('cc_charge', TRUE);
        $paymentmode=$this->input->post('mode', TRUE);
        $cashpaid=0;$cardpaid=0;$voucherpaid=0;$checkpaid=0;
                
        $instrumentnumber= $paymentmode=='Online' ? 'Online '.$this->input->post('instrument_number', TRUE) :  $this->input->post('instrument_number', TRUE);
        $balance=$this->input->post('balance');
        $returnamount=$this->input->post('returnamount');
        //$product_discount=$this->input->post('product_discount', TRUE);
        //$discounted_price=$this->input->post('discounted_price', TRUE);
        
        $customer_advance=$this->input->post('customer_advance', TRUE);
        $retained_used=$this->input->post('retained_used', TRUE);
        $retained_amount_used=$this->input->post('retained_amount_used', TRUE);
        $remaining_retained=$this->input->post('remaining_retained', TRUE);
        
        $cctip = $this->input->post('cctip', TRUE);
        
        $advance_amount=$this->input->post('advance_amount',TRUE);
        
        $other_charges=$this->input->post('other_charges',TRUE);
        //$serivce_flag=$this->input->post('service_flag',TRUE);
        
        $totalpaid= $advance_amount+$paid;
        $totalpaidnow= $totalpaid;
        
        if($paymentmode=="Cash"){$cashpaid=$paid;}
        else if($paymentmode=="Card"){$cardpaid=$paid;}
        else if($paymentmode=="Check"){$checkpaid=$paid;}
        else if($paymentmode=="Online"){$checkpaid=$paid; $paymentmode='Check';}
        else if($paymentmode=="Voucher"){$voucherpaid=$paid;}
        else if($paymentmode=="Mixed"){
            $cashpaid=$this->input->post('cashpaid', TRUE);
            $cardpaid=$this->input->post('cardpaid', TRUE);
            $totalpaidnow = $cashpaid + $cardpaid;
        } 
         
        //Loyalty
        $loyaltyused=$this->input->post('loyaltyused',TRUE);
        $loyaltyvalue=$this->input->post('loyaltyvalue',TRUE);
        $loyaltyenabled=$this->input->post('loyaltyenabled',TRUE);
        //$sloyaltyenabled=$this->input->post('sloyaltyenabled',TRUE);
        $rloyaltyenabled=$this->input->post('rloyaltyenabled',TRUE);
        
        if($loyaltyenabled=='Y' && $rloyaltyenabled=="Y") {$loyaltyearned=(Float)$totalpaid/ (Float)$loyaltyvalue;}
        else {$loyaltyearned=0;}
        if($loyaltyearned < 0){$loyaltyearned=0;}        
        //Get customer & order
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
        $this->db->where('customer_orders.id_customer_order', $orderid);
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        $customerorders = $this->db->get('customer_orders');
       
        $customerorder = $customerorders->row();
        
        $insertloyalty = true;
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){
                $insertloyalty=false;
            }
        }

        //print_r($other_charges); exit();
        //Create invoice    
        $invoice_date=$invoicedate;
        $visittime=$invoicedate;
        $customername=$customerorder->customer_name;
        $data = array(
            'customer_id'=>$customerid,
            'invoice_number'=>'999',
            'business_id'=>$this->session->userdata('businessid'),
            'customer_name'=> $customerorder->customer_name,
            'customer_cell'=> $customerorder->customer_cell,
            'customer_email'=> $customerorder->customer_email,
            'customer_address'=> $customerorder->customer_address,
            'tax_total'=>$taxtotal,
            'paid_amount' => $paid,
            'paid_cash' => $cashpaid,
            'paid_card' => $cardpaid,
            'paid_voucher' => $voucherpaid,
            'paid_check' => $checkpaid,
            'discount' => $discount,
            'gross_amount' => $gross_amount + $taxtotal,
            'gross_wo_tax' => $gross_amount,
            'net_amount' => $net_amount,
            'visit_id' => $orderid,
            'visit_time' => $visittime,
            'sub_total' => $org_subtotal ,
            'invoice_type'=>'sale',
            'payment_mode'=>$paymentmode,
            'instrument_number'=>$instrumentnumber,
            'cc_charge'=>$cc_charge,
            'balance'=>$balance,
            'is_recovery' => $balance > 0 ? 'Yes' : 'No',
            'discount_remarks' => $this->input->post('discount_remarks'),
            'returnamount' => $customer_advance==='false' ? $returnamount: 0,
            'loyalty_used'=> $insertloyalty == true ? $loyaltyused : 0,
            'advance_amount'=>$advance_amount,
            'other_charges'=>$other_charges + $totaladdition,
            'invoice_date'=>$invoice_date,
            'retained_used'=>$retained_used,
            'retained_amount_used'=>$retained_amount_used,
            'retained_amount'=>$customer_advance==='true' ? $returnamount : 0,
            'cctip'=>$cctip,
            'loyalty_earned'=> $insertloyalty==true ? $loyaltyearned : 0,
            'total_payable'=>$totalpayable,
            'created_by' => $this->session->userdata('username'),
            'order_id' =>$orderid
        );
        //print_r($data); exit();
        $this->db->insert('invoice', $data);
        $invoiceid =  $this->db->insert_id();
        //make sure invoice number is correct
         $today=date('Y-m-d');
        $seq=1;        
        $sql = "select max(invoice_seq)+1 as 'seq'
            from invoice where day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}
        if(isset($business[0]['r_auto_sh'])){
            if($business[0]['r_auto_sh']=='No'){
                $seq=0;
            }
        }
        $update_invoice = array(
            'invoice_number' => date('Y-m').'-'.$invoiceid,
            'invoice_seq' => $seq
        ); 
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        //////////////////
        
         ///update customer advance
        if ($customer_advance==='true'){
            $newval=$returnamount + $remaining_retained;
        } else {
            $newval=$remaining_retained;
        }
        $this->db->set('customer_advance', $newval);
        $this->db->where('id_customers',$customerid);
        $this->db->update('customers');
        //////////
        
        //Update Loyalty
        if($loyaltyenabled=='Y' && $rloyaltyenabled=='Y'){
            $this->db->select('loyalty_points');
            $this->db->where('id_customers =',$customerid);
            $existingpoint = $this->db->get('customers');
            $existingpoints = $existingpoint->result_array();
            
            $newloyaltypoints=(Float)$existingpoints[0]['loyalty_points'];
            if($loyaltyused>0){
                $newloyaltypoints= (Float)$existingpoints[0]['loyalty_points'] - $loyaltyused;
            }
            $calloyaltypoints=0;
            if($totalpaid>0){
                $calloyaltypoints = $totalpaid / $loyaltyvalue;
            }
            $newloyaltypoints=$newloyaltypoints+$calloyaltypoints;
            
            $this->db->where('id_customers = ', $customerid);
            $this->db->update('customers', array('loyalty_points'=>$newloyaltypoints));        
            
        }
        /////
        $this->disount_invoice_user_insert($invoiceid);
        
        
        //insert product sales tax
        foreach($tableData as $row){
            $data=array(
                'invoice_id'=>$invoiceid,
                'business_id'=>$this->session->userdata('businessid'),
                'invoice_tax_name'=> 'Sales Tax',
                'invoice_tax'=>$row['product_tax']
            );
            $this->db->insert('invoice_taxes', $data);
        }
        //insert invoice taxes
        if(isset($taxes)){
            foreach($taxes as $tax){
                $data=array(
                    'invoice_id'=>$invoiceid,
                    'business_id'=>$this->session->userdata('businessid'),
                    'invoice_tax_name'=>$tax['taxname'],
                    'invoice_tax'=>$tax['tax']
                );
                $this->db->insert('invoice_taxes', $data);
            }
        }
        //insert invoice products
        $k=0;
        //foreach ($orderproducts1 as $orderproduct)
        $b=0;
        $totalproductdiscount=0;
        $batch_amount=0;        
        $remainingsub=$subtotal; 
        $remainingpaid=$paid+$advance_amount; 
        $total_service_additions=0;
        $product_cog = [];
        //foreach($orderproducts->result() as $orderproduct) 
        $staff_id_for_dispatch=0;
        foreach($tableData as $row){  
            // Saif Code start From Here
            $sql="SELECT  `business_products`.`product_type` ,  `business_products`.`track_inventory` , ifnull(commission,0) as commission , `business_products`.`category` , `business_products`.`purchase_price`  FROM `business_products`  where id_business_products=?";
            $resp = $this->db->query($sql, array($row['productid']));
            $products_data_with_type_and_inventry = $resp->row(); 
            $product_type= $products_data_with_type_and_inventry->product_type;
            $track_inventory = $products_data_with_type_and_inventry->product_type; 
            $category = $products_data_with_type_and_inventry->category; 
            $purchase_price = $products_data_with_type_and_inventry->purchase_price;  
            if($product_type =="Compiled Kit"){   

                $product_paid=0;
            
                if($row['product_total'] < $remainingpaid){
                    $product_paid = $row['product_total'];
                }else{
                    if($remainingpaid > 0){
                        $product_paid = $remainingpaid;
                    } else {
                        $product_paid=0;
                    }
                } 

                //$remainingsub = $remainingsub - $row['product_total'];
                       $remainingpaid = $remainingpaid - $product_paid; 

                 //get commission perc
                    if(-1 > 0){
                        $this->db->select('product, category, ifnull(commission,0) as commission, ifnull(batch_amount,0) as batch_amount, track_inventory');
                        $this->db->join('product_batch', 'product_id = id_business_products');
                        $this->db->where('id_business_products', $row['productid']);
                        $this->db->where('id_batch', $row['batch_id']); 
                    }else{
                        $this->db->select('product, category, ifnull(commission,0) as commission, ifnull(purchase_price,0) as batch_amount, track_inventory');
                        $this->db->where('id_business_products', $row['productid']);                
                    }
                    $query = $this->db->get('business_products');
                    $product = $query->row();
                    //print_r($product); exit();
                    
                    $commission_perc = $product->commission;
                    $product_batch_amount = $product->batch_amount;
                    $product_cog[$row['batch_id']] = $product_batch_amount * $row['product_qty'];
                    
                    $category = $product->category;
                    $totalproductdiscount += $row['product_discount'];
                    $total_service_additions += $row['product_addition'];
                    
                    $commission = (($product_paid- $row['product_tax']) * $commission_perc) / 100;
                    $commission = round($commission, 2);
                    
                    
                    //get batch amount
                    $tot_prod_batch_amount = (float)$product_batch_amount * $row['product_qty'];
                    $batch_amount = round($batch_amount +  $tot_prod_batch_amount,2);

                        $products= array(
                            'invoice_id'=>$invoiceid,
                            'business_id'=>$this->session->userdata('businessid'),
                            'brand_name'=>$row['brandname'],
                            'product_name'=>$row['productname'],
                            'staff_name'=>$row['staff_name'],
                            'staff_id'=>$row['staff_id'],
                            'invoice_qty'=>$row['product_qty'],
                            'price'=>$row['unitprice'],
                            'service_addition'=>$row['product_addition'],
                            'discount'=>$row['product_discount'],                
                            'discounted_price'=>$row['product_subtotal'],
                            'invoice_discount'=>0,
                            'final_price'=>$row['product_total'],
                            'taxes'=>$row['product_tax'],
                            'paid'=>$product_paid,
                            'product_id'=>$row['productid'],
                            'category'=>$category,
                            'batch' => 0,
                            'batch_id'=>0,
                            'commission'=>$commission               
                        ); 

                        $this->db->insert('invoice_products', $products);
                        $invoice_detail_id=$this->db->insert_id();   

                            //insert staff sale
                        $amount=$row['unitprice']*$row['product_qty'];
                        
                        $staffsale=array(
                            'invoice_id'=>$invoiceid,
                            'invoice_detail_id' =>  $invoice_detail_id,
                            'business_id'=>$this->session->userdata('businessid'),
                            'order_id'=>$orderid,
                            'staff_id'=>$row['staff_id'],
                            'staff_name'=>$row['staff_name'],
                            'brand_name'=>$row['brandname'],
                            'product_name'=>$row['productname'],
                            'price'=>$amount,
                            'sale_type'=>'sale',
                            'qty'=>$row['product_qty'],
                            'discount'=>$row['product_discount'],
                            'discounted_price'=>$row['product_subtotal'],
                            'paid'=>$product_paid
                        );
                        $this->db->insert('staff_services', $staffsale); 


            }  
             if($product_type =="Physical"){  
             
                    $staff_id_for_dispatch = $row['staff_id'];
                    $staff_name_for_dispatch = $row['staff_name'];
                    $discount_price_per_qty = $row['product_discount']/ $row['product_qty']; 
                    foreach($selected_batch_data as $item){
                          $product_type =  $item['product_type'];
                      if($item['product_type'] == "Physical"){ 
                            $product_name = $item['product_name'];
                            $productid = $item['productid'];
                            $batch_id = $item['batch_id'];
                            $batch_number =  $item['batch_number'];
                            $store_id =  $item['store_id'];
                            $total_price = $item['total_price'];
                            if($productid == $row['productid']){
                                $product_actual_price = $row['unitprice'];
                                $qty =  $item['qty'];
                                $total_discount_amount = $discount_price_per_qty * $qty;
                                $price_after_qty_and_discount = ($product_actual_price*$qty)-$total_discount_amount;
                                $tax_amount = ($price_after_qty_and_discount * $row['product_tax_perc']) / 100;
                                $totalPrice = $price_after_qty_and_discount + $tax_amount;
                                $cos_g_amount_for_invoice =  $purchase_price*$qty;        

                                $product_paid=0;
        
                                if($totalPrice < $remainingpaid){
                                    $product_paid = $totalPrice;
                                }else{
                                    if($remainingpaid > 0){
                                        $product_paid = $remainingpaid;
                                    } else {
                                        $product_paid=0;
                                    }
                                }
                                
                                //$remainingsub = $remainingsub - $row['product_total'];
                                $remainingpaid = $remainingpaid - $product_paid;
                                
                                //get commission perc
                                if($batch_id>0){
                                    $this->db->select('product, category, ifnull(commission,0) as commission, ifnull(batch_amount,0) as batch_amount, track_inventory');
                                    $this->db->join('product_batch', 'product_id = id_business_products');
                                    $this->db->where('id_business_products', $productid);
                                    $this->db->where('id_batch', $batch_id); 
                                }else{
                                    $this->db->select('product, category, ifnull(commission,0) as commission, ifnull(purchase_price,0) as batch_amount, track_inventory');
                                    $this->db->where('id_business_products', $productid);                
                                }
                                $query = $this->db->get('business_products');
                                $product = $query->row();
                                //print_r($product); exit();
                                
                                $commission_perc = $product->commission;
                                $product_batch_amount = $product->batch_amount;
                                $product_cog[$batch_id] = $product_batch_amount * $qty;
                                
                                $category = $product->category;
                                $totalproductdiscount += $total_discount_amount;
                                $total_service_additions += 0;
                                
                                $commission = (($product_paid- $tax_amount) * $commission_perc) / 100;
                                $commission = round($commission, 2);
                                
                                
                                //get batch amount
                                $tot_prod_batch_amount = (float)$product_batch_amount * $qty;
                                $batch_amount = round($batch_amount +  $tot_prod_batch_amount,2);




                                $products= array(
                                    'invoice_id'=>$invoiceid,
                                    'business_id'=>$this->session->userdata('businessid'),
                                    'brand_name'=>$row['brandname'],
                                    'product_name'=>$row['productname'],
                                    'staff_name'=>$row['staff_name'],
                                    'staff_id'=>$row['staff_id'],
                                    'invoice_qty'=>$qty,
                                    'price'=>$row['unitprice'],
                                    'service_addition'=>0,
                                    'discount'=> $total_discount_amount,
                                    'discounted_price'=>$price_after_qty_and_discount,
                                    'invoice_discount'=>0,
                                    'final_price'=>$totalPrice,
                                    'taxes'=>$tax_amount,
                                    'paid'=>$product_paid,
                                    'product_id'=>$row['productid'],
                                    'category'=>$category,
                                    'batch' =>$batch_number,
                                    'batch_id'=>$batch_id,
                                    'commission'=>0,
                                    'cog_amount'=>$cos_g_amount_for_invoice,
                                    'commission'=>$commission 
                                );
                                $this->db->insert('invoice_products', $products);
                                $invoice_detail_id=$this->db->insert_id();  


                                $amount=$row['unitprice']*$qty;
                                $staffsale=array(
                                    'invoice_id'=>$invoiceid,
                                    'invoice_detail_id' =>  $invoice_detail_id,
                                    'business_id'=>$this->session->userdata('businessid'),
                                    'order_id'=>$orderid,
                                    'staff_id'=>$row['staff_id'],
                                    'staff_name'=>$row['staff_name'],
                                    'brand_name'=>$row['brandname'],
                                    'product_name'=>$row['productname'],
                                    'price'=>$amount,
                                    'sale_type'=>'sale',
                                    'qty'=>$qty,
                                    'discount'=>$total_discount_amount,
                                    'discounted_price'=>$price_after_qty_and_discount,
                                    'paid'=>$product_paid
                                );
                                $this->db->insert('staff_services', $staffsale);                
                            }
                        } 
                    }
              }    
           // Saif Code End From Here    
            $k++;
        }
        $this->db->where('adjustment_order_id', $orderid);
        $this->db->delete('adjustment_notes');
        
        
         ///create retail sale voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(1);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Retail Sale Voucher against invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $totalpayable,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername,
                'voucher_type'=>2,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'sale'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount+$cashpaid : $cashpaid;}
                if($debit[2]=="paid_card" && $cardpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount+$cardpaid : $cardpaid;}
                if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $checkpaid : $checkpaid;}
                if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $voucherpaid : $voucherpaid;}
                
                if($debit[2]=="balance"){$debitamount= $balance;}
                if($debit[2]=="sale_discount_retail"){$debitamount= $totalproductdiscount + $discount;}
                if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}
                                
                if($debit[2]=="advance_adjusted"){
                    if($retained_amount_used==0 && $advance_amount > 0){
                        $debitamount= $advance_amount;
                    } elseif($retained_amount_used>0 && $advance_amount > 0) {
                        $debitamount= $advance_amount-$retained_amount_used;                        
                    } 
                }    
                
                if($debit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment < 0){
                       
                        $debitamount=$roundedadjustment*-1;
                    }
                    
                }
                if(defined('LOYALTY_VOUCHER')){                    
                    if(LOYALTY_VOUCHER==TRUE){
                        if($debit[2]=="loyalty_amount"){
                            if($loyaltyused>0){ //if discount is actually loyalty points
                                $debitamount= 0;
                            
                                //see if we need to bring the loyalty points in from HO
                                $my_business = $this->check_if_ho();
                                //bring the points from ho
                                if($my_business != $this->session->userdata('businessid')){
                                    $this->bring_in_ho_points($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                                }   

                                $this->create_loyalty_used_voucher($this->session->userdata('businessid'),$loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                                $debitamount= 0; // make sure
                            }                 
                        }
                    }
                }
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                if($credit[2]=="grosstotal_retail"){$creditamount= $org_subtotal + $total_service_additions;}                
                if($credit[2]=="sales_tax"){$creditamount= $taxtotal;}
                if($credit[2]=="cc_fee"){$creditamount= $cc_charge;}
                if($credit[2]=="retained_amount"){$creditamount= $customer_advance==='true' ? $returnamount: 0;}
                if($credit[2]=="cc_tip"){$creditamount= $cctip;}
                //if($credit[2]=="additional_charges"){$creditamount= $totaladdition;}
                
                if($totalpaidnow > $totalpayable+$roundedadjustment){
                    if($credit[2]=="return_cash"){$creditamount= $customer_advance==='false' ? $returnamount: 0;}
                }
                if($credit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment > 0){
                        
                        $creditamount=$roundedadjustment; 
                    }                    
                }
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            ///create loyalty voucher
            if(defined('LOYALTY_VOUCHER')){                    
                if(LOYALTY_VOUCHER==TRUE){
                    if($loyaltyearned > 0){
                        $my_business= $this->check_if_ho();            
                        $this->add_loyalty_points_ho($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
                    }
                }
            } 


            
        // ======================> Creating Cost Of good Voucher Start <=====================================
        $product_cog =[];
        foreach ($selected_batch_data as $item) {
           $track_inventry = $item['track_inventory']; 
          if($track_inventry == "Yes"){ 
                        $sql="SELECT  `business_products`.`product_type` ,  `business_products`.`track_inventory` , ifnull(commission,0) as commission , `business_products`.`category` , `business_products`.`purchase_price`  FROM `business_products`  where id_business_products=?";
                        $resp = $this->db->query($sql, array($item['productid']));
                        $products_data_with_type_and_inventry = $resp->row(); 

                        $product_name = $item['product_name'];
                        $qty =  $item['qty'];
                        $productid = $item['productid'];
                        $batch_id = $item['batch_id'];
                        $batch_number =  $item['batch_number'];
                        $store_id =  $item['store_id'];
                        $total_price = $item['total_price'];
                        $product_cog[$batch_id] = $total_price;
                        $batch_amount = $total_price; 
                        if($batch_id>0){
                            $this->db->select('product, category, ifnull(commission,0) as commission, ifnull(batch_amount,0) as batch_amount, track_inventory');
                            $this->db->join('product_batch', 'product_id = id_business_products');
                            $this->db->where('id_business_products', $productid);
                            $this->db->where('id_batch', $batch_id); 
                        }else{
                            $this->db->select('product, category, ifnull(commission,0) as commission, ifnull(purchase_price,0) as batch_amount, track_inventory');
                            $this->db->where('id_business_products', $productid);                
                        }
                        $query = $this->db->get('business_products');
                        $product = $query->row();
                        //print_r($product); exit();
                        $commission_perc = $product->commission;
                        $product_batch_amount = $product->batch_amount;
                        $product_cog[$batch_id] = $product_batch_amount * $qty;
                        //get batch amount
                        $tot_prod_batch_amount = (float)$product_batch_amount * $qty;
                        $batch_amount = round($tot_prod_batch_amount,2); 

                        $debit_accounts=[];
                        $credit_accounts=[];
                        $sql="SELECT account_head_id, transaction_type, entity_name, description FROM account_event_mapping
                        where account_event_id = 23 and business_id=".$this->session->userdata('businessid').";";
                        $query=$this->db->query($sql);
                        $account_heads = $query->result_array();
                        //var_dump ($account_heads); exit();
                        foreach($account_heads as $ah){
                            if($ah['transaction_type']=='debit'){
                                array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                            } else {
                                array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                            }
                        }
                        $bank_name='';
                        $batch_amount = round($batch_amount,2);
                        //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
                        $data = array(
                            'business_id' => $this->session->userdata('businessid'),
                            'description' => 'Cost of Goods Solds Voucher against reference voucher ID '. $account_voucherid . ' invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                            'voucher_date' => date('Y-m-d H:i:s'),
                            'voucher_amount' => $batch_amount,
                            'voucher_status' => 'Active',
                            'created_by' => $this->session->userdata('username'),
                            'cost_center'=> '1',
                            'cost_center_name'=> 'Front Desk',
                            'business_partner'=> 1,
                            'business_partner_id'=>$customerid,
                            'business_partner_name'=>$customername,
                            'voucher_type'=>3,
                            'payment_mode'=>$paymentmode,
                            'bank_name'=>$bank_name,
                            'invoice_id'=>$invoiceid,
                            'auto_voucher'=>'Yes',
                            //'sale_type'=>'sale'
                        );
                        $this->db->insert('account_vouchers', $data);
                        $cogs_voucherid =  $this->db->insert_id();
                        //enter debit entries
                        $total_cog = 0;
                        foreach($debit_accounts as $debit_account){
                            $debitamount=0;
                            $debit = explode("|", $debit_account);
                            //check entity
                            if($debit[2]=="cogs"){
                                //    foreach($tableData as $row){
                                $debitamount= $product_cog[$batch_id];
                                $total_cog = $total_cog + $product_cog[$batch_id];
                                // $debitamount= $debitamount * $product_cog[$row['batch_id']];
                                $data_detail=array(
                                    'account_voucher_id' => $cogs_voucherid,
                                    'account_head_id' => $debit[0],
                                    'instrument_number' => $instrumentnumber,
                                    'detail_remarks' =>$product_name,
                                    'debit' => round($debitamount,2),
                                    'credit' => 0
                                );
                                //insert debit detail
                                if($debitamount>0){
                                    $this->db->insert('account_voucher_detail', $data_detail);
                                }
                            }
                            //    }
                        }
                        //enter credit entries
                        foreach($credit_accounts as $credit_account){
                            $creditamount=0;
                            $credit = explode("|", $credit_account);
                            //check entity
                            //if($credit[2]=="inventory"){$creditamount= $batch_amount;}
                            if($credit[2]=="inventory"){$creditamount= $total_cog;}
                            $data_detail=array(
                                'account_voucher_id' => $cogs_voucherid,
                                'account_head_id' => $credit[0],
                                'instrument_number' => $instrumentnumber,
                                'debit' => 0,
                                'credit' => round($creditamount,2)
                            );
                            //insert credit detail
                            if($creditamount>0){
                                $this->db->insert('account_voucher_detail', $data_detail);
                            }
                        }
                        // ======================>  Add dispatch intery  <==========================================
                        $product_name = $item['product_name'];
                        $qty =  $item['qty'];
                        $productid = $item['productid'];
                        $batch_id = $item['batch_id'];
                        $batch_number =  $item['batch_number'];
                        $store_id =  $item['store_id'];
                        $total_price = $item['total_price'];
                        // $unit_type  = $item['unit_type'];
                        // $measure_unit = $item['measure_unit'];

                        $product_type = $item['product_type'];
                        if($product_type == "Compiled Kit"){
                            $data = array(
                                'product_id'=> $productid,
                                'dispatch_to_staff' =>   $staff_id_for_dispatch,
                                'dispatch_qty' => $qty,
                                'dispatch_measure' => $this->input->post('dispatch_measure'),
                                // 'unit_type' => $unit_type,
                                // 'measure_unit' =>$measure_unit,
                                'dispatch_date' => date('Y-m-d H:i:s'),
                                'batch' =>$batch_number,
                                'batch_id' =>  $batch_id,
                                'business_id' => $this->session->userdata('businessid'),
                                'created_by' => $this->session->userdata('username'),
                                'dispatch_comment'=> "Cost Of Good for kit",
                                'order_id'=> $orderid,
                                // 'visit_id'=> $this->input->post('visit_id'),
                                // 'visit_service_id'=> $this->input->post('visit_service_id'),
                                // 'request_id'=>$request_id
                            );
                            $this->db->insert('dispatch_notes', $data);
                        }
            }
        // ======================> Creating Cost Of good Voucher End <=====================================
         }
        }
        
        
        //update customer order (mark as invoiced)
        $this->db->set('order_status', 'invoiced');
        $this->db->where('id_customer_order', $orderid);
        $this->db->update('customer_orders');
        //return "success|".$invoiceid;
        
        
        $mypaid = $customer_advance==='true' ? $advance_amount + $returnamount + $paid : $advance_amount + $paid;
        return $invoiceid.'|'.$loyaltyearned.'|'.$totalpayable.'|'.$mypaid.'|'.$balance;
    }
    
    // ===============> jun-14-2024  end <==================


}
