<?php

class Accounting_model extends CI_Model {

    function __construct() {

        // Call the Model constructor
        parent::__construct();
    }
    
    
    function get_account_voucher_type(){
        
        $this->db->select('*');
        $query = $this->db->get('account_voucher_type');

        return $query->result_array();
        
    }
    
    function get_cash_in_hand(){
        $this->db->select('*');
        $this->db->join('account_sub_control','account_sub_control.id_account_sub_control = account_heads.account_sub_control_id');
        $this->db->where('account_heads.business_id', $this->session->userdata('businessid'));
        
        
            $this->db->where('lower(account_head)', 'cash in hand');
        
        $query = $this->db->get('account_heads');

        return $query->row();
        
        
    }
    
    function get_account_business_partners(){
        
        $this->db->select('*');
        $query = $this->db->get('account_business_partner');

        return $query->result_array();
        
    }
    
    
    /////Main Account////////
    function get_account_main($mainid='all') {
        
        $this->db->select('*');
        if($mainid!=='all'){
            $this->db->where('id_account_main', $mainid);
        }
        $query = $this->db->get('account_main');

        return $query->result_array();
    }
    
    function account_main_insert(){
        
        $data = array(           
           'account_main' => $this->input->post('account_main', TRUE),
           'account_main_number' => $this->input->post('account_main_number', TRUE),          
           'business_id' => $this->session->userdata('businessid')
        );
        $this->db->insert('account_main', $data);
        return $this->db->insert_id();
        
        
    }
    
    function account_main_update(){
        $data = array(           
           'account_main' => $this->input->post('account_main', TRUE),
           'account_main_number' => $this->input->post('account_main_number', TRUE)   
          
        );
        $this->db->where('id_account_main', $this->input->post('id_account_main'));
        $this->db->update('account_main', $data);
        return $this->input->post('id_account_main');
        
    }
    
    function delete_account_main($mainid){
        
        $this->db->where('id_account_main', $mainid);
        $this->db->delete('account_main');
        return $mainid;
        
    }
    ////////Main Account/////////
    
    ///////Control Account///////
    function get_account_control($mainid='all', $controlid='all'){
        
        $this->db->select('*');
        if($mainid!=='all'){
            $this->db->where('account_main_id', $mainid);
        }
        if($controlid!=='all'){
            $this->db->where('id_account_control', $controlid);
        }
        $query = $this->db->get('account_control');

        return $query->result_array();
        
    }
    
    function account_control_insert(){
        
        $data = array(           
           'account_main_id' => $this->input->post('id_account_main', TRUE),
           'account_control' =>  $this->input->post('account_control', TRUE),
           'account_control_number' => $this->input->post('account_control_number', TRUE),          
           'business_id' => $this->session->userdata('businessid')
        );
        $this->db->insert('account_control', $data);
        return $this->db->insert_id();
        
        
    }
    
    function account_control_update(){
        $data = array(           
           'account_control' => $this->input->post('account_control', TRUE),
           'account_control_number' => $this->input->post('account_control_number', TRUE)   
          
        );
        $this->db->where('id_account_control', $this->input->post('id_account_control'));
        $this->db->update('account_control', $data);
        return $this->input->post('id_account_control');
        
    }
    
    function delete_account_control($controlid){
        
        $this->db->where('id_account_control', $controlid);
        $this->db->delete('account_control');
        return $controlid;
        
    }
    ////////Control Account End//////////
    
    
    /////// Sub Control Account///////
    function get_account_sub_control($controlid='all', $subcontrolid='all'){
        
        $this->db->select('*');
        
        if($controlid!=='all'){
            $this->db->where('account_control_id', $controlid);
        }
        if($subcontrolid!=='all'){
            $this->db->where('id_account_sub_control', $subcontrolid);
        }
        $query = $this->db->get('account_sub_control');

        return $query->result_array();
        
    }
    
    function account_sub_control_insert(){
        
        $data = array(           
           'account_control_id' => $this->input->post('id_account_control', TRUE),
           'account_sub_control' =>  $this->input->post('account_sub_control', TRUE),
           'account_sub_control_number' => $this->input->post('account_sub_control_number', TRUE),          
           'business_id' => $this->session->userdata('businessid')
        );
        $this->db->insert('account_sub_control', $data);
        return $this->db->insert_id();
        
        
    }
    
    
    
    function account_sub_control_update(){
        $data = array(           
           'account_sub_control' => $this->input->post('account_sub_control', TRUE),
           'account_sub_control_number' => $this->input->post('account_sub_control_number', TRUE)   
          
        );
        $this->db->where('id_account_sub_control', $this->input->post('id_account_sub_control'));
        $this->db->update('account_sub_control', $data);
        return $this->input->post('id_account_sub_control');
        
    }
    
    function delete_account_sub_control($subcontrolid){
        
        $this->db->where('id_account_sub_control', $subcontrolid);
        $this->db->delete('account_sub_control');
        return $subcontrolid;
        
    }
    
    
    ////////End Sub Control Accounts //////
    
    /////// Account Heads ////////////
    
    function get_account_heads($subcontrolid='all', $accountheadid='all', $business_id=null){

        $this->db->select('*');
        $this->db->join('account_sub_control','account_sub_control.id_account_sub_control = account_heads.account_sub_control_id');
        $this->db->join('business','business.id_business=account_heads.business_id');
        
        if($this->session->userdata('ho')=='No'){
            $this->db->where('account_heads.business_id', $this->session->userdata('businessid'));
        } elseif($business_id!==null){
            $this->db->where('account_heads.business_id', $business_id);
        } elseif ($this->input->post('business_id')!==null && $this->input->post('business_id')!=='' && $this->input->post('business_id')>0){            
            $this->db->where('account_heads.business_id', $this->input->post('business_id'));
        } else {
            $this->db->where('business.common_products', 'Yes'); 
        }
        
        
        if($subcontrolid!=='all'){
            $this->db->where('account_heads.account_sub_control_id', $subcontrolid);
        }
        if($accountheadid!=='all'){
            $this->db->where('id_account_heads', $accountheadid);
        }
        
        $this->db->order_by('id_account_sub_control','id_account_heads');
        $query = $this->db->get('account_heads');

        return $query->result_array();
        
    }

    function get_account_heads_control($controlid='all', $accountheadid='all', $business_id=null){

        $this->db->select('*');
        $this->db->join('account_sub_control','account_sub_control.id_account_sub_control = account_heads.account_sub_control_id');
        $this->db->join('account_control','account_control.id_account_control = account_sub_control.account_control_id');
        $this->db->join('business','business.id_business=account_heads.business_id');
        
        if($this->session->userdata('ho')=='No'){
            $this->db->where('account_heads.business_id', $this->session->userdata('businessid'));
        } elseif($business_id!==null){
            $this->db->where('account_heads.business_id', $business_id);
        } elseif ($this->input->post('business_id')!==null && $this->input->post('business_id')!=='' && $this->input->post('business_id')>0){            
            $this->db->where('account_heads.business_id', $this->input->post('business_id'));
        } else {
            $this->db->where('business.common_products', 'Yes'); 
        }
        
        
        if($controlid!=='all'){
            $this->db->where('account_sub_control.account_control_id', $controlid);
        }
        if($accountheadid!=='all'){
            $this->db->where('id_account_heads', $accountheadid);
        }
        
        $this->db->order_by('id_account_control','id_account_heads');
        $query = $this->db->get('account_heads');

        return $query->result_array();
        
    }
    
    function get_account_heads_main($mainid='all', $accountheadid='all', $business_id=null){

        $this->db->select('*');
        $this->db->join('account_sub_control','account_sub_control.id_account_sub_control = account_heads.account_sub_control_id');
        $this->db->join('account_control','account_control.id_account_control = account_sub_control.account_control_id');
        $this->db->join('account_main','account_main.id_account_main = account_control.account_main_id');
        $this->db->join('business','business.id_business=account_heads.business_id');
        
        if($this->session->userdata('ho')=='No'){
            $this->db->where('account_heads.business_id', $this->session->userdata('businessid'));
        } elseif($business_id!==null){
            $this->db->where('account_heads.business_id', $business_id);
        } elseif ($this->input->post('business_id')!==null && $this->input->post('business_id')!=='' && $this->input->post('business_id')>0){            
            $this->db->where('account_heads.business_id', $this->input->post('business_id'));
        } else {
            $this->db->where('business.common_products', 'Yes'); 
        }        
        
        if($mainid!=='all'){
            $this->db->where('account_control.account_main_id', $mainid);
        }
        if($accountheadid!=='all'){
            $this->db->where('id_account_heads', $accountheadid);
        }
        
        $this->db->order_by('id_account_control','id_account_heads');
        $query = $this->db->get('account_heads');

        return $query->result_array();
        
    }

    function account_head_insert(){
        $data = array(           
           'account_sub_control_id' => $this->input->post('id_account_sub_control', TRUE),
           'account_head' =>  $this->input->post('account_head', TRUE),
           'account_head_number' => $this->input->post('account_head_number', TRUE),          
           'business_id' => $this->session->userdata('businessid')
        );
        $this->db->insert('account_heads', $data);
        return $this->db->insert_id();        
    
    }
    
    
    function account_head_update(){
        
        $data = array(           
           'account_head' => $this->input->post('account_head', TRUE),
           'account_head_number' => $this->input->post('account_head_number', TRUE),
           'account_sub_control_id' =>  $this->input->post('account_sub_control', TRUE)
          
        );
        $this->db->where('id_account_heads', $this->input->post('id_account_heads'));
        $this->db->update('account_heads', $data);
        return $this->input->post('id_account_heads');
        
    }
    
    function delete_account_head($accounheadid){
        
        $this->db->select('*');
        $this->db->where('account_head_id', $accounheadid);
        $query = $this->db->get('account_event_mapping');
        $mapped=$query->row();
        
        if(sizeof($mapped)==0){
            $this->db->where('id_account_heads', $accounheadid);
            $this->db->delete('account_heads');

            return $accounheadid;
        } else {
            return 0;
        }
        
    }
    
    
    
    /////// End Account Heads ///////////
    
    
    ////////Account Vouchers /////////////////////////////////////////
    
    function get_account_vouchers($mainid='all', $controlid='all', $subcontrolid='all', $accounthead='all', $businessid='all'){
        
         $sql = "SELECT id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, 
                date_format(voucher_date,'%d-%m-%Y %h:%i') voucher_date, 
                date_format(av.created_on,'%d-%m-%Y %h:%i') created_on, av.created_by,
                account_head_number, account_head, debit, credit
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                join account_heads ah on ah.id_account_heads = avd.account_head_id 
                join account_sub_control ascont on ascont.id_account_sub_control = ah.account_sub_control_id 
                join account_control ac on ac.id_account_control = ascont.account_control_id 
                join account_main am on am.id_account_main = ac.account_main_id 
                where voucher_status= 'Active' ";
         
         if($mainid!=='all'){
            $sql.=" and am.id_account_main = ".$mainid." ";
         }
         if($controlid!=='all'){
            $sql.=" and ac.id_account_control = ".$controlid." ";
         }
         if($subcontrolid!=='all'){
            $sql.=" and ascont.id_account_sub_control = ".$subcontrolid." ";
         }
         
         if($accounthead!=='all'){
            $sql.=" and ah.id_account_heads = ".$accounthead." ";
         }
         
         if($businessid!=='all'){
            $sql.=" and av.businessid = ".$this->session->userdata('businessid')." ";
         }
         //echo $sql; exit();
        $query = $this->db->query($sql);
        
        return $query->result_array();
    }
    
    function get_voucher($voucher_id){
        
        $sql = "SELECT *, id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, 
                date_format(voucher_date,'%d-%m-%Y') voucher_date, 
                date_format(av.created_on,'%d-%m-%Y %h:%i') created_on, av.created_by,
                account_head_number, account_head, debit, credit, av.voucher_type
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                join account_heads ah on ah.id_account_heads = avd.account_head_id 
                join account_sub_control ascont on ascont.id_account_sub_control = ah.account_sub_control_id 
                join account_control ac on ac.id_account_control = ascont.account_control_id 
                join account_main am on am.id_account_main = ac.account_main_id 
                where voucher_status= 'Active' 
                and av.id_account_vouchers = ". $voucher_id ."  order by avd.id_account_voucher_detail;";
        
        $query = $this->db->query($sql);
        
        return $query->result_array();
    }
    
    function get_any_voucher($voucher_id){
        
        $sql = "SELECT *, id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, 
                date_format(voucher_date,'%d-%m-%Y') voucher_date, 
                date_format(av.created_on,'%d-%m-%Y %h:%i') created_on, av.created_by,
                account_head_number, account_head, debit, credit, av.voucher_type
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                join account_heads ah on ah.id_account_heads = avd.account_head_id 
                join account_sub_control ascont on ascont.id_account_sub_control = ah.account_sub_control_id 
                join account_control ac on ac.id_account_control = ascont.account_control_id 
                join account_main am on am.id_account_main = ac.account_main_id 
                where av.id_account_vouchers = ". $voucher_id ."  order by avd.id_account_voucher_detail;";
        
        $query = $this->db->query($sql);
        
        return $query->result_array();
    }
   
    
    function cancel_account_voucher($voucherid){
        
        $this->db->where('id_account_vouchers',$voucherid);
        $this->db->set('voucher_status','cancelled');
        $this->db->set('cancelled_by', $this->session->userdata('username'));
        $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
        
        $this->db->update('account_vouchers');
        
       return $this->db->affected_rows();
    }
    
    //////////////////////////////////System Events////////////////////////////////////////////////////////////////////
    
    function get_system_events($systemevent){
        
        $this->db->select("*");
            $this->db->join('account_events','account_events.id_account_events = account_event_mapping.account_event_id');
            $this->db->where('account_event', $systemevent);
         $query= $this->db->get('account_events');
            
             return $query->result_array();
            
    }
    
    
    
    
    
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    function get_account_category() {
        
        $this->db->select('*');
        $query = $this->db->get('account_category');

        return $query->result_array();
    }
    
    function get_account_types() {
        
        $this->db->select('*');
        $query = $this->db->get('account_type');

        return $query->result_array();
    }
    
    function get_account_subtypes($master_account_id = 0) {
        
        $this->db->select('*');
        if($master_account_id > 0){
            $this->db->where('account_type_id',$master_account_id);
        }
        $query = $this->db->get('account_sub_types');

        return $query->result_array();
    }
    
    function get_all_account_heads($account_type = null, $business_id = null){
        
        $this->db->select("*, concat(ac.account_main_number, '-', at.account_control_number, '-',ast.account_sub_control_number ,'-', account_head_number) as account_number", False);
//        $this->db->join("account_sub_types ast","ast.id_account_sub_types = account_heads.account_sub_type");
//        $this->db->join("account_type at","at.id_account_type = ast.account_type_id");
//        $this->db->join("account_category ac","ac.id_account_category = at.account_category_id");
        $this->db->join("account_sub_control ast","ast.id_account_sub_control = account_heads.account_sub_control_id");
        $this->db->join("account_control at","at.id_account_control = ast.account_control_id");
        $this->db->join("account_main ac","ac.id_account_main = at.account_main_id");
        
        
        if($this->session->userdata('ho')=='No'){
            $this->db->where('account_heads.business_id', $this->session->userdata('businessid'));
        }elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
            $this->db->where('account_heads.business_id', $this->input->post('business_id'));
        } elseif($business_id!==null){
            $this->db->where('account_heads.business_id', $business_id);
        }
        
        if($account_type!==null && is_string($account_type)){
            $this->db->where('account_heads.account_type', $account_type);
        }else if($account_type !== null && is_numeric($account_type)){
            $this->db->where('account_heads.account_sub_type', $account_type);
        }
        
        $query = $this->db->get('account_heads');

        
        //print_r($query->result_array()); exit();
        return $query->result_array();
        
    }
    
    function get_all_till_account_heads(){
        
        $this->db->select("*, concat(ac.account_main_number, '-', at.account_control_number, '-',ast.account_sub_control_number ,'-', account_head_number) as account_number", False);
        
//        $this->db->join("account_sub_types ast","ast.id_account_sub_types = account_heads.account_sub_type");
//        $this->db->join("account_type at","at.id_account_type = ast.account_type_id");
//        $this->db->join("account_category ac","ac.id_account_category = at.account_category_id");
        $this->db->join("account_sub_control ast","ast.id_account_sub_control = account_heads.account_sub_control_id");
        $this->db->join("account_control at","at.id_account_control = ast.account_control_id");
        $this->db->join("account_main ac","ac.id_account_main = at.account_main_id");
        $this->db->where('account_heads.business_id', $this->session->userdata('businessid'));
        $this->db->where('account_heads.till_account', 'Yes');
    
        
        $query = $this->db->get('account_heads');

        return $query->result_array();
        
    }
    
    
    function get_all_account_heads_params($from_account=null,$to_account=null, $business_id = null){
        
        $sub_control = $this->input->post('selected_account_sub_control');
        
        $this->db->select("*, concat(ac.account_main_number, '-',at.account_control_number, '-',ast.account_sub_control_number ,'-', account_head_number) as account_number", False);
        $this->db->join("account_sub_control ast","ast.id_account_sub_control = account_heads.account_sub_control_id");
        $this->db->join("account_control at","at.id_account_control = ast.account_control_id");
        $this->db->join("account_main ac","ac.id_account_main = at.account_main_id");
        $this->db->join("business","account_heads.business_id = business.id_business"); 
        
        if($this->session->userdata('ho')=='No'){
            $this->db->where('account_heads.business_id', $this->session->userdata('businessid'));
        }elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
            $this->db->where('account_heads.business_id', $this->input->post('business_id'));
        } elseif($business_id!==null){
            $this->db->where('account_heads.business_id', $business_id);
        }
        
        
        if(null!==$sub_control && $sub_control>0){
            
            $this->db->where('account_heads.account_sub_control_id =', $sub_control);
            
        } else {
        
            if(null!==$from_account && $from_account >0){
                $this->db->where('account_heads.id_account_heads >=', $from_account);
            }
            if(null!==$to_account && $to_account > 0){
                $this->db->where('account_heads.id_account_heads <=', $to_account);
            }
        }
        $query = $this->db->get('account_heads');

        return $query->result_array();
        
    }
    
    function get_account_head($id){
        $this->db->select('*');
        $this->db->where('account_heads.id_account_heads', $id);
        $query = $this->db->get('account_heads');

        return $query->result_array();
        
    }
    
    function account_head_update_old(){
        
        $data = array(           
           'account_head' => $this->input->post('account_head', TRUE),
           'account_sub_type' => $this->input->post('account_head_type', TRUE),
           'account_head_number' => $this->input->post('account_head_number', TRUE),
            'account_type' => $this->input->post('account_type', TRUE)
        );
        $this->db->where('id_account_heads', $this->input->post('id_account_heads', TRUE));
        $this->db->update('account_heads', $data);
        return $this->db->affected_rows();
        
    }
    
    function account_head_insert_old(){
        
        $data = array(           
           'account_head' => $this->input->post('account_head', TRUE),
           'account_sub_type' => $this->input->post('account_head_type', TRUE),
           'account_head_number' => $this->input->post('account_head_number', TRUE),
           'account_type' => $this->input->post('account_type', TRUE),
           'business_id' => $this->session->userdata('businessid')
        );
        $this->db->insert('account_heads', $data);
        return $this->db->insert_id();
        
    }
    
    function get_voucher_types(){
        
        $this->db->select('*');
        $query = $this->db->get('account_voucher_type');
        
        return $query->result_array();
    }
    
    function get_all_account_vouchers($business_id=null, $startdate=null, $enddate=null){
        
        if(null == $startdate){
            $startdate = $this->input->post('startdate'); 
        }
        if(null == $enddate){
            $enddate = $this->input->post('enddate'); 
        }

      
        $voucher_type = $this->input->post('voucher_type');
        $auto_voucher=$this->input->post('auto_voucher');
        
        if(null !== $this->input->post('dateselected') && $this->input->post('dateselected')!==""){
            $date_selected = $this->input->post('dateselected');
        }else {
            $date_selected = "Voucher";
        }
        
//        
//        
        if($startdate==""){
            $startdate= date('Y-m-d');
        }
        if($enddate==""){
            $enddate= date('Y-m-d');
        }
//        
        
        $sql = "SELECT id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, date_format(voucher_date,'%d-%m-%Y %h:%i') voucher_date, 
                date_format(av.created_on,'%d-%m-%Y %h:%i') created_on, av.created_by,
                account_head_number, account_head, debit, credit, auto_voucher, id_business, business_name,
                av.voucher_status
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                join account_heads ah on ah.id_account_heads = avd.account_head_id
                join business on av.business_id = business.id_business
                where id_account_vouchers>= 1 ";
        
        
                if($date_selected=="Voucher"){
                    if($startdate && $startdate!==""){
                        $sql .= " and date(voucher_date) >= '".$startdate."' ";
                    }
                    if($enddate && $enddate!==""){
                        $sql .= " and date(voucher_date) <='".$enddate."' ";
                    }
                } else if ($date_selected=="Create"){
                    if($startdate && $startdate!==""){
                        $sql .= " and date(av.created_on) >='".$startdate."' ";
                    }
                    if($enddate && $enddate!==""){
                        $sql .= " and date(av.created_on) <='".$enddate."' ";
                    }
                    
                }
                
                if($auto_voucher=="yes"){
                    $sql .= " and av.auto_voucher = 'Yes' ";
                } else if ($auto_voucher=="no"){
                    $sql .= " and av.auto_voucher = 'No' ";
                }
                
                if($this->session->userdata('ho')=='No'){
                    $sql .= " and av.business_id=".$this->session->userdata('businessid');
                } elseif ($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                    $sql .= " and av.business_id=".$this->input->post('business_id');
                } 
//                elseif($business_id!==null && $business_id!==''){
//                    $sql .= " and ah.business_id = " . $business_id ;
//                } 
                else {
                    $sql.= " and business.common_products = 'Yes' ";
                }
                
                if($voucher_type && $voucher_type>0){
                    $sql .= " and av.voucher_type='".$voucher_type."' ";
                }
//                $sql .= " group by id_account_vouchers, description, account_voucher_type, 
//                cost_center_name, business_partner_name, voucher_date, av.created_by
//                order by id_account_vouchers";
                $sql .= " order by id_account_vouchers"; 
                
//                echo $sql; exit();
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    
    
    function get_ref_account_vouchers($business_id=null){
        
        $reftype= $this->input->post('reftype');
        $refid=$this->input->post('refid');
        
        $sql = "SELECT id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, date_format(voucher_date,'%d-%m-%Y %h:%i') voucher_date, 
                date_format(av.created_on,'%d-%m-%Y %h:%i') created_on, av.created_by,
                account_head_number, account_head, debit, credit, auto_voucher, id_business, business_name,
                av.voucher_status
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                join account_heads ah on ah.id_account_heads = avd.account_head_id
                join business on av.business_id = business.id_business
                where id_account_vouchers>= 1 ";
        
                if($this->session->userdata('ho')=='No'){
                    $sql .= " and av.business_id=".$this->session->userdata('businessid');
                } elseif ($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                    $sql .= " and av.business_id=".$this->input->post('business_id');
                } elseif($business_id!==null){
                    $this->db->where('account_heads.business_id', $business_id);
                } else {
                    $sql.= " and business.common_products = 'Yes' ";
                }
                
                if($reftype !== 'business_partner_id'){
                    $sql .= " and ".$reftype." = ".$refid." ";
                } else {
                    $sql .= " and ".$reftype." = ".$refid." and business_partner = 1 ";
                }
                
                
                $sql .= " order by id_account_vouchers"; 
                
 //               echo $sql; exit();
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    
    function get_all_vouchers_created($business_id=null){
        
        $startdate = $this->input->post('startdate'); 
        $enddate = $this->input->post('enddate');
        $voucher_type = $this->input->post('voucher_type');
        
        if($startdate==""){
            $startdate= date('Y-m-d');
        }
        if($enddate==""){
            $enddate= date('Y-m-d');
        }
        
        
        $sql = "SELECT id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, date_format(voucher_date,'%d-%m-%Y %h:%i') voucher_date, 
                date_format(av.created_on,'%d-%m-%Y %h:%i') created_on, av.created_by,
                account_head_number, account_head, debit, credit
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                join account_heads ah on ah.id_account_heads = avd.account_head_id
                join business on business.id_business = av.business_id
                where voucher_status= 'Active' ";
                if($startdate && $startdate!==""){
                    $sql .= " and created_on>='".$startdate."' ";
                }
                if($enddate && $enddate!==""){
                    $sql .= " and created_on<='".$enddate."' ";
                }
               
                 if($this->session->userdata('ho')=='No'){
                    $sql .= " and av.business_id=".$this->session->userdata('businessid');
                } elseif ($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                    $sql .= " and av.business_id=".$this->input->post('business_id');
                } elseif($business_id!==null){
                    $this->db->where('account_heads.business_id', $business_id);
                } else {
                    $sql.= " and business.common_products = 'Yes' ";
                }
                
                
                if($voucher_type && $voucher_type>0){
                    $sql .= " and av.voucher_type='".$voucher_type."' ";
                }
//                $sql .= " group by id_account_vouchers, description, account_voucher_type, 
//                cost_center_name, business_partner_name, voucher_date, av.created_by
//                order by id_account_vouchers";
                $sql .= " order by id_account_vouchers"; 
        $query=$this->db->query($sql);
        return $query->result_array();
        
    }
    
    function get_all_account_vouchers_opening_balance(){ //General Ledger
        
        $startdate = $this->input->post('startdate'); 
        $enddate = $this->input->post('enddate');
        //$voucher_type = $this->input->post('voucher_type');
        
        $from_account = $this->input->post('from_accounts');
        $to_account = $this->input->post('to_accounts');
        
        $sub_control = $this->input->post('selected_account_sub_control');
        
        if($startdate==""){
            $startdate= date('Y-m-d');
        }
        if($enddate==""){
            $enddate= date('Y-m-d');
        }
      
        if($from_account==""){
            $from_account= 1;
        }
        if($to_account==""){
            $to_account= 1;
        }
        
        if($sub_control>0){
            $sql = "SELECT * from account_heads ";
            $sql .= "join account_sub_control on account_sub_control.id_account_sub_control = account_heads.account_sub_control_id ";
            $sql .= "join business on business.id_business = account_heads.business_id ";
            $sql .= "where account_heads.account_sub_control_id = ". $sub_control." ";
            if($this->session->userdata('ho')=="No"){
                $sql.= " and account_heads.business_id=".$this->session->userdata('businessid')." ";
            } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                $sql.= " and account_heads.business_id=".$this->input->post('business_id')." ";
            } else {
                $sql.= " and business.common_products = 'Yes' ";
            }
            
            $sql .= " order by id_business, account_head;";
            
            
        } else if($from_account ==0 and $to_account==0){
            $sql = "SELECT * from account_heads ";
            $sql .= "join business on business.id_business = account_heads.business_id ";
            if($this->session->userdata('ho')=="No"){
                $sql.= " where business_id=".$this->session->userdata('businessid')." ";
            } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                $sql.= " where business_id=".$this->input->post('business_id')." ";
            } else {
                $sql.= " where business.common_products = 'Yes' ";
            }
            
            $sql .= " order by id_business, account_head;";
        }else{
            $sql = "SELECT * from account_heads ";
            $sql .= "join business on business.id_business = account_heads.business_id";
            $sql .=" where id_account_heads >=$from_account and id_account_heads <=$to_account ";
            if($this->session->userdata('ho')=="No"){
                $sql .=" and account_heads.business_id=".$this->session->userdata('businessid')." ";
            } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                $sql.= " and account_heads.business_id=".$this->input->post('business_id')." ";
            } else {
                $sql.= " and business.common_products = 'Yes' ";
            }
            
            $sql .= " order by id_business, account_head;";
        }
        $query = $this->db->query($sql);
        
        $accounts =  $query->result_array();
        $data = array();
        foreach($accounts as $account):
        
            $sql = "SELECT id_account_vouchers, description, account_voucher_type, 
                    avd.cost_center as cost_center_name, business_partner_name, date_format(voucher_date,'%d-%m-%Y') voucher_date, date_format(av.created_on,'%d-%m-%Y %h:%i') created_on,
                    av.created_by, av.payment_mode, 
                    account_head_number, account_head, 
                    Case
                    when account_main = 'Assets' Then
                        ifnull(sum(ifnull(Debit,0))-sum(ifnull(Credit,0)),0) 
                    when account_main = 'Expenses' Then
                        ifnull(sum(ifnull(Debit,0))-sum(ifnull(Credit,0)),0) 
                    Else
                        ifnull(sum(ifnull(Credit,0))-sum(ifnull(Debit,0)),0) 
                        
                    End as 'opening',
                    account_main as account_type, business_name, id_business
                    FROM account_vouchers av
                    join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                    join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                    join account_heads ah on ah.id_account_heads = avd.account_head_id
                    join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id 
                    join business on business.id_business = av.business_id 
                    ";
            
            $sql .=" where voucher_status= 'Active' ";
                    if($startdate && $startdate!==""){
                        $sql .= " and date(voucher_date)<'".$startdate."' ";
                    }
                    
                    if($this->session->userdata('ho')=='No'){
                        $sql .= " and av.business_id=".$this->session->userdata('businessid');
                    }elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                        $sql.= " and av.business_id=".$this->input->post('business_id')." ";
                    }
                    
                    //ID or Number
                    if($this->session->userdata('ho')=="No"){
                        $sql .= " and avd.account_head_id='".$account['id_account_heads']."' ";
                    } else if($this->input->post('business_id')==null) {
                        $sql .= " and ah.account_head_number='".$account['account_head_number']."' ";
                        $sql .= " and business.common_products='Yes' ";
                    }else{
                        $sql .= " and avd.account_head_id='".$account['id_account_heads']."' ";
                    }
                    
                    if($this->input->post('business_partner_id')>0){
                        $sql .= " and av.business_partner_id='".$this->input->post('business_partner_id')."' ";
                        $sql .= " and av.business_partner= '".$this->input->post('bptype')."' ";
                    }
                    
                    if($this->input->post('cost_center_type')>0){
                       
                        $sql .= " and av.cost_center_name= '".$this->input->post('cost_center_name')."' ";
                    }
                    
                    
                    $sql .= " order by CAST(voucher_date AS DATE),  av.id_account_vouchers"; 
            
                   // echo $sql; exit();
            $query=$this->db->query($sql);
            $openingBalance = $query->result_array();
            foreach($openingBalance as $detail):
                    $sql = "SELECT id_account_vouchers, description, instrument_number, account_voucher_type, 
                    avd.cost_center as cost_center_name, business_partner_name, date_format(voucher_date,'%d-%m-%Y') voucher_date, date_format(av.created_on,'%d-%m-%Y %h:%i') created_on,
                    av.created_by, av.payment_mode, 
                    account_head_number, account_head, ifnull(debit,0) as debit, ifnull(credit,0) as credit, account_main.account_main as 'account_type',
                    id_business, business_name 
                    FROM account_vouchers av
                    join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                    join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                    join account_heads ah on ah.id_account_heads = avd.account_head_id
                    join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id 
                    where voucher_status= 'Active' ";
                    if($startdate && $startdate!==""){
                        $sql .= " and voucher_date>='".$startdate." ' ";
                    }
                    if($enddate && $enddate!==""){
                        $sql .= " and voucher_date<='".$enddate." 23:59' ";
                    }
                    if($this->session->userdata('ho')=='No'){
                        $sql .= " and av.business_id=".$this->session->userdata('businessid');
                    }elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                        $sql.= " and av.business_id=".$this->input->post('business_id')." ";
                    }
                    
                    //ID or Number
                    if($this->session->userdata('ho')=="No"){
                        $sql .= " and avd.account_head_id='".$account['id_account_heads']."' ";
                    } else if($this->input->post('business_id')==null) {
                        $sql .= " and ah.account_head_number='".$account['account_head_number']."' ";
                        $sql .= " and business.common_products='Yes' ";
                    }else{
                        $sql .= " and avd.account_head_id='".$account['id_account_heads']."' ";
                    }

                    // if($this->session->userdata('ho')=="No"){
                    //     $sql .= " and avd.account_head_id='".$account['id_account_heads']."' ";
                    // } else {
                    //     $sql .= " and ah.account_head_number='".$account['account_head_number']."' ";
                    //     $sql .= " and business.common_products='Yes' ";
                    // }
                    
                    if($this->input->post('business_partner_id')>0){
                        $sql .= " and av.business_partner_id='".$this->input->post('business_partner_id')."' ";
                        $sql .= " and av.business_partner= '".$this->input->post('bptype')."' ";
                    }
                    if($this->input->post('cost_center_type')>0){
                        
                        $sql .= " and av.cost_center_name= '".$this->input->post('cost_center_name')."' ";
                    }
                    $sql .= " order by CAST(voucher_date AS DATE),  av.id_account_vouchers"; 
                
                    // echo $sql; exit();
                    
                $query = $this->db->query($sql);
                $details =  $query->result_array();
               // if($detail['opening'] > 0){
                    $opening = $detail['opening'];
                //}else{
                //    $opening = 0;
                //}
                $acc = $account['account_head_number']. '|' .  $account['account_head'] . '|'. $account['business_name'];
                
                $data[$acc]['opening_balance'] = [$opening];
                $data[$acc]['details'] = $details;
                
            endforeach;    
        endforeach;
       // var_dump($data[$acc]['details']);
       // exit();
        return $data;
    }
    public function getOpening_balance_asset($startdate,$account_id){
        $sql = "SELECT ah.account_head,
            ifnull(sum(debit)- sum(credit),0) as 'balance', business_name, sum(debit) debit, sum(credit) credit
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
            join account_control ac on ac.id_account_control = asct.account_control_id
            join account_main on account_main.id_account_main = ac.account_main_id
            join business on business.id_business = av.business_id
            where voucher_status= 'Active' ";

            if($startdate && $startdate!==""){
                $sql .= " and voucher_date<'".$startdate." ' ";
            }
            
            if($this->input->post('business_partner_id')>0){
                $sql .= " and av.business_partner_id='".$this->input->post('business_partner_id')."' ";
                $sql .= " and av.business_partner= '".$this->input->post('bptype')."' ";
            }
            if($this->input->post('cost_center_type')>0){

                $sql .= " and av.cost_center_name= '".$this->input->post('cost_center_name')."' ";
            }
            if($this->session->userdata('ho')=='No'){
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
            } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                $sql .= " and av.business_id=".$this->input->post('business_id');
            } else {
                $sql.= " and business.common_products = 'Yes' ";
            }
            
            $sql .= " and avd.account_head_id='".$account_id."' ";
            $sql .= " group by ah.id_account_heads,ah.account_head"; 
            $sql .= " order by CAST(voucher_date AS DATETIME),  av.id_account_vouchers";    
            
            //echo $sql; exit();
            
        $query=$this->db->query($sql);
        return $query->result_array();
    }
   
    public function getOpening_balance_liability($startdate,$account_id){
        $sql = "SELECT ah.account_head,
            ifnull(sum(credit)- sum(debit),0) as 'balance', business_name
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id
            where voucher_status= 'Active' ";

            if($startdate && $startdate!==""){
                $sql .= " and voucher_date<'".$startdate." ' ";
            }
            
            
             if($this->input->post('business_partner_id')>0){
                $sql .= " and av.business_partner_id='".$this->input->post('business_partner_id')."' ";
                $sql .= " and av.business_partner= '".$this->input->post('bptype')."' ";
            }
            if($this->input->post('cost_center_type')>0){

                $sql .= " and av.cost_center_name= '".$this->input->post('cost_center_name')."' ";
            }
            
            if($this->session->userdata('ho')=='No'){
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
            } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                $sql .= " and av.business_id=".$this->input->post('business_id');
            } else {
                $sql.= " and business.common_products = 'Yes' ";
            }
            
            $sql .= " and avd.account_head_id='".$account_id."' ";
            $sql .= " group by ah.id_account_heads,ah.account_head"; 
            $sql .= " order by CAST(voucher_date AS DATETIME),  av.id_account_vouchers";         
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    
    public function getCurrent_balance_asset($startdate,$enddate,$account_id, $subcontrolid=null){
        $sql = "SELECT ah.account_head,
            ifnull(sum(debit)- sum(credit),0) as 'balance', business_name, sum(debit) as debit, sum(credit) as credit, asct.account_sub_control
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
            join account_control ac on ac.id_account_control = asct.account_control_id
            join account_main on account_main.id_account_main = ac.account_main_id
            join business on business.id_business = av.business_id
            where voucher_status= 'Active' ";

            if($startdate && $startdate!==""){
                $sql .= " and voucher_date>='".$startdate." ' ";
            }
            if($enddate && $enddate!==""){
                $sql .= " and voucher_date<='".$enddate." 23:59' ";
            }
            
            if($this->input->post('business_partner_id')>0){
                $sql .= " and av.business_partner_id='".$this->input->post('business_partner_id')."' ";
                $sql .= " and av.business_partner= '".$this->input->post('bptype')."' ";
            }
            if($this->input->post('cost_center_type')>0){

                $sql .= " and av.cost_center_name= '".$this->input->post('cost_center_name')."' ";
            }
            if($this->session->userdata('ho')=='No'){
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
            } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                $sql .= " and av.business_id=".$this->input->post('business_id');
            } else {
                $sql.= " and business.common_products = 'Yes' ";
            }
            
            if(null !== $subcontrolid){
                $sql .= " and asct.id_account_sub_control= ".$subcontrolid." ";
            }
            if(null !== $account_id){
            $sql .= " and avd.account_head_id='".$account_id."' ";
            }
            $sql .= " group by ah.id_account_heads,ah.account_head"; 
                    
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    public function getCurrent_balance_liability($startdate,$enddate,$account_id=null, $subcontrolid=null){
        $sql = "SELECT ah.account_head,
            ifnull(sum(credit)-sum(debit),0) as 'balance', business_name,  sum(debit) as debit, sum(credit) as credit, asct.account_sub_control
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id
            where voucher_status= 'Active' ";

            if($startdate && $startdate!==""){
                        $sql .= " and voucher_date>='".$startdate." ' ";
                    }
            if($enddate && $enddate!==""){
                $sql .= " and voucher_date<='".$enddate." 23:59' ";
            }
            
            
             if($this->input->post('business_partner_id')>0){
                $sql .= " and av.business_partner_id='".$this->input->post('business_partner_id')."' ";
                $sql .= " and av.business_partner= '".$this->input->post('bptype')."' ";
            }
            if($this->input->post('cost_center_type')>0){

                $sql .= " and av.cost_center_name= '".$this->input->post('cost_center_name')."' ";
            }
            
            if($this->session->userdata('ho')=='No'){
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
            } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                $sql .= " and av.business_id=".$this->input->post('business_id');
            } else {
                $sql.= " and business.common_products = 'Yes' ";
            }
            
            if(null !== $subcontrolid){
                $sql .= " and asct.id_account_sub_control= ".$subcontrolid." ";
            }
            if(null !== $account_id){
            $sql .= " and avd.account_head_id='".$account_id."' ";
            }
            $sql .= " group by ah.id_account_heads,ah.account_head"; 
                    
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    public function balanceSheet($startdate,$account_id,$type){
        
        if($type === 'Assets' || $type === 'Expenses'){
            $sql = "SELECT 
            round(ifnull(sum(debit)-sum(credit),0),2) as 'balance'
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id
            where voucher_status= 'Active' ";
        }else{
            $sql = "SELECT 
            round(ifnull(sum(credit)-sum(debit),0),2) as 'balance'
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id
            where voucher_status= 'Active' ";
        }
            if($startdate && $startdate!==""){
                $sql .= " and voucher_date<='".$startdate." 23:59' ";
            }
            
            if($this->session->userdata('ho')=='No'){
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
            }elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!=='' && $this->input->post('business_id')>0){
                $sql .= " and av.business_id=".$this->input->post('business_id');
            } else {
                $sql.= " and business.common_products = 'Yes' ";
            }
            
            
            $sql .= " and avd.account_head_id='".$account_id."' ";
           // $sql .= " group by ah.id_account_heads,ah.account_head"; 
                 
        $query=$this->db->query($sql);
        return $query->result_array();
        
    }
    
    public function revenue_breakup($startdate,$enddate, $sale_type){
        $type = $sale_type == 'service' ? 'Service Sale' : 'Retail Sale';
        $sql = "SELECT '".$type."' as 'Type',
            ifnull(sum(credit)-sum(debit),0) as 'amount'
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
            where voucher_status= 'Active'  and account_main.id_account_main=5";
        if($startdate && $startdate!==""){
            $sql .= " and date(voucher_date)>='".$startdate."' ";
        }
        if($enddate && $enddate!==""){
            $sql .= " and date(voucher_date) <='".$enddate."' ";
        }
            
        $sql .= " and av.business_id=".$this->session->userdata('businessid');
        //$sql .= " and avd.account_head_id='".$account_id."' ";
        $sql .= " and av.sale_type='".$sale_type."' ";
        $query=$this->db->query($sql);
        return $query->result_array();
        
    }
    
    public function profit_and_loss($startdate,$enddate,$account_id,$type,$account_type){
        
        if($account_type === 'Revenue'){
            $sql = "SELECT 
            ifnull(sum(credit)-sum(debit),0) as 'amount', business_name, sum(debit) as debit, sum(credit) as credit, asct.account_sub_control, account_head
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id 
            where voucher_status= 'Active'  and account_main.id_account_main=5";
        }elseif($account_type === 'Expenses'){
            $sql = "SELECT 
            ifnull(sum(debit)-sum(credit),0) as 'amount', business_name
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id 
            where voucher_status= 'Active'  and account_main.id_account_main=3";
    } elseif( $account_type === 'Liabilities' ){
        $sql = "SELECT 
            ifnull(sum(credit)-sum(debit),0) as 'amount', business_name
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id 
            where voucher_status= 'Active'  and account_main.id_account_main=2";
        } elseif( $account_type === 'Assets' ){
        $sql = "SELECT 
            ifnull(sum(credit)-sum(debit),0) as 'amount', business_name
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
            join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id 
            where voucher_status= 'Active'  and account_main.id_account_main=1";
        }else{
            $sql = "SELECT 
            ifnull(sum(debit)-sum(credit),0) as 'amount', business_name
            FROM account_vouchers av
            join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
            join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
            join account_heads ah on ah.id_account_heads = avd.account_head_id
           join account_sub_control asct on ah.account_sub_control_id = asct.id_account_sub_control
                    join account_control ac on ac.id_account_control = asct.account_control_id
                    join account_main on account_main.id_account_main = ac.account_main_id
                    join business on business.id_business = av.business_id 
            where voucher_status= 'Active'  ";
        }
        
        if($startdate && $startdate!==""){
            $sql .= " and date(voucher_date)>='".$startdate."' ";
        }
        if($enddate && $enddate!==""){
            $sql .= " and date(voucher_date)<='".$enddate."' ";
        }
        
        if($this->session->userdata('ho')=='No'){
            $sql .= " and av.business_id=".$this->session->userdata('businessid');
        } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
            $sql .= " and av.business_id=".$this->input->post('business_id');
        } else {
                $sql.= " and business.common_products = 'Yes' ";
            }
        
        $sql .= " and avd.account_head_id='".$account_id."' ";
        
                    
        $query=$this->db->query($sql);
        return $query->result_array();
        
    }
    
    function get_account_voucher($id=null){
        
        $this->db->select('*');
        $this->db->join('account_voucher_detail','id_account_vouchers = account_voucher_id');
        $this->db->join('account_heads', 'account_head_id = id_account_heads');
        if(null !== $id){
            $this->db->where('id_account_vouchers',$id);
        }
        $query=$this->db->get('account_vouchers');
        
        //print_r($query->result_array()); exit();
        return $query->result_array();
        
    }
  
    
    
    public function create_account_voucher(){
        
        $voucher_data = $this->input->post('voucherdata', TRUE);  
        ///get reference ids
        $refid=0; $ref_feild='purchase_order_id';
        if($voucher_data['reference_type'] !== 'none' && $voucher_data['ref_id']>0){
            $refid=$voucher_data['ref_id'];
            $ref_feild=$voucher_data['reference_type'];
        }
        
        $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' => stripcslashes($voucher_data['description']),
            'voucher_date' => $voucher_data['account_voucher_date'],
            'voucher_amount' => $voucher_data['amount'],
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> $voucher_data['cost_center_type'],
            'cost_center_name'=> $voucher_data['cost_center'],
            'business_partner'=> $voucher_data['business_partner_type'],
            'business_partner_id'=> $this->input->post('business_partner_id'),
            'business_partner_name'=> stripcslashes($this->input->post('business_partner_name')),
            'voucher_type'=> $voucher_data['account_voucher_type'],
            'bank_name'=> $bank_name,
            'payment_mode'=> $voucher_data['voucher_payment_mode_val'],
            $ref_feild => $refid
        );
        
        $this->db->insert('account_vouchers', $data);
        $voucher_id =  $this->db->insert_id();
       
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('voucherdetails', TRUE));
         // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        
        foreach($tableData as $row){
           if($row['account_head']!==""){
                $data = array(
                    'account_voucher_id' => $voucher_id,
                    'account_head_id' => $row['account_head'],
                    'debit' => $row['debit'],
                    'credit' => $row['credit'],
                    'cost_center' => stripcslashes($row['cost_center']),
                    'cost_center_type' => $row['cost_center_type'],
                    'instrument_number' => stripcslashes($row['instrument_number']),
                    'detail_remarks' => stripcslashes($row['remarks']),
                    'payment_mode' => $row['payment_mode']
                );
                $this->db->insert('account_voucher_detail', $data);
           }
        }
        return $voucher_id;
        
    }
    
    public function edit_account_voucher(){
        
        
        $voucher_data = $this->input->post('voucherdata', TRUE);  
       // print_r($voucher_data);

       // exit();
        
        $voucher_id=$this->input->post('voucher_id', TRUE);
        
        
        //remove old details
//        $this->db->where('account_voucher_id', $voucher_id);
//        $this->db->delete('account_voucher_detail');
        
        
        $this->db->select('id_account_voucher_detail');
        $this->db->where('account_voucher_id',$voucher_id);
        $q=  $this->db->get('account_voucher_detail');
        $old_detail_ids = $q->result_array();
        
        
        //parse_str(urldecode($this->input->post('voucherdata', TRUE)) , $voucher_data);
        //$voucher_data = $this->input->post('voucherdata', TRUE);
        $bank_name='';
        if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
         
       
        $data = array( 
            
            'description' => stripcslashes($voucher_data['description']),
            'voucher_date' => $voucher_data['account_voucher_date'],
            'voucher_amount' => $voucher_data['amount'],
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> $voucher_data['cost_center_type'],
            'cost_center_name'=> stripcslashes($voucher_data['cost_center']),           
            'voucher_type'=> $voucher_data['account_voucher_type'],            
            'payment_mode'=> $voucher_data['voucher_payment_mode_val']
        );
        if($bank_name!==''){array_push($data, ['bank_name'=> $bank_name]);}
        if(null !== $this->input->post('business_partner_id') && $this->input->post('business_partner_id')!==''){
            $data['business_partner']= $voucher_data['business_partner_type'];
            $data['business_partner_id']=  $this->input->post('business_partner_id');
            $data['business_partner_name']= stripcslashes($voucher_data['business_partner']);
        }
        
        //get reference ids
        $refid=0; $ref_feild='purchase_order_id';
        if($voucher_data['reference_type'] !== 'none' && $voucher_data['ref_id']>0){
            $refid=$voucher_data['ref_id'];
            $ref_feild=$voucher_data['reference_type'];
            
            $data[$ref_feild]=$refid;
        }
        
        //var_dump($data);
        $this->db->where('id_account_vouchers', $voucher_id);
        $this->db->update('account_vouchers', $data);
        
       
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('voucherdetails', TRUE));
         // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        
       
        $totalinserts= 0;

        foreach($tableData as $row){
           if($row['account_head']!=="" && $row['id_account_voucher_detail'] > 0){
                $data = array(
                    'account_voucher_id' => $voucher_id,
                    'account_head_id' => $row['account_head'],
                    'debit' => $row['debit'],
                    'credit' => $row['credit'],
                    'cost_center' => stripcslashes($row['cost_center']),
                    'cost_center_type' => $row['cost_center_type'],
                    'instrument_number' => stripcslashes($row['instrument_number']),
                    'detail_remarks' => stripcslashes($row['remarks']),
                    'payment_mode' => $row['payment_mode']
                );
                $this->db->where('id_account_voucher_detail', $row['id_account_voucher_detail']);
                $this->db->update('account_voucher_detail', $data);
                // $insertid = $this->db->insert_id();
                if($this->db->affected_rows()>0){
                    $totalinserts++;
                }
                // var_dump($data);
           } elseif($row['account_head']!=="" && $row['id_account_voucher_detail'] == 0){
                $data = array(
                    'account_voucher_id' => $voucher_id,
                    'account_head_id' => $row['account_head'],
                    'debit' => $row['debit'],
                    'credit' => $row['credit'],
                    'cost_center' => stripcslashes($row['cost_center']),
                    'cost_center_type' => $row['cost_center_type'],
                    'instrument_number' => stripcslashes($row['instrument_number']),
                    'detail_remarks' => stripcslashes($row['remarks']),
                    'payment_mode' => $row['payment_mode']
                );               
                $this->db->insert('account_voucher_detail', $data);
                $insertid = $this->db->insert_id();
                if($this->db->insert_id()>0){
                    $totalinserts++;
                 }
                // var_dump($data);
            } 
        }
        
        $sql = "insert into voucher_edit_log select * from account_voucher_detail where account_voucher_id = ".$voucher_id;
        $this->db->query($sql);
        
        return $old_detail_ids;        
        
        
    }
    
    public function get_bank_accounts_old(){
        
        $this->db->select("*");
        $this->db->where("account_type=","Bank");
        $this->db->where("business_id",$this->session->userdata('businessid'));
        $query=$this->db->get("account_heads");
        return $query->result_array();
        
        
    }
    public function get_cost_center_types(){
        
        $this->db->select("*");
        $query=$this->db->get("account_cost_center");
        return $query->result_array();
        
        
    }
    public function get_payments(){
        $startdate = $this->input->post('startdate'); 
        $enddate = $this->input->post('enddate');
        $supplier = $this->input->post('supplier');
        
        if($startdate==""){
            $startdate= date('Y-m-d');
        }
        if($enddate==""){
            $enddate= date('Y-m-d');
        }
        $sql = "SELECT id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, date_format(voucher_date,'%d-%m-%Y %h:%i') voucher_date, av.created_by,
                account_head_number, account_head, debit, credit
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                join account_heads ah on ah.id_account_heads = avd.account_head_id
                where voucher_status= 'Active' ";
                if($startdate && $startdate!==""){
                    $sql .= " and voucher_date>='".$startdate."' ";
                }
                if($enddate && $enddate!==""){
                    $sql .= " and voucher_date<='".$enddate."' ";
                }
                if($supplier !== ""){
                    $sql .= " and business_partner_id='".$supplier."' ";
                }
                
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
                $sql .= " and av.voucher_type=1 ";
                $sql .= " order by id_account_vouchers"; 
        $query=$this->db->query($sql);
        return $query->result_array();
        
    }
    
    function getstatementpayments($startdate, $enddate, $vouchertype){
        
        $sql="SELECT sum(debit) 'payments' 
            FROM account_vouchers
            join account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
            where voucher_type = ".$vouchertype."
            and voucher_date >= '".$startdate."' 
            and voucher_date <= '".$enddate."' 
            and business_id=".$this->session->userdata('businessid')." 
            order by id_account_vouchers desc";
        
        
        $query =$this->db->query($sql);
        
        return $query->result_array();
    }
    
    
    
    
    function get_month_services($startdate, $enddate){
        //WHERE voucher_date  >= '".$startdate."' AND voucher_date <= '".$enddate."'
        $sql="SELECT  
            sum(paid_amount)  as 'Total', 
            sum(paid_amount) Paid, 
            sum(advance_amount) advance, 
            ifnull(voucher_amount,0) voucher,
            ifnull(sum(cctip),0) cctip,
            sum(paid_cash) cash, sum(paid_card) card, sum(paid_check) bank, sum(paid_voucher) voucher_pay,
            sum(paid_cash) + sum(paid_card) + sum(paid_check) + sum(paid_voucher) paymentmodetotal
            FROM invoice left join ( 
                    select sum(ifnull(amount,0)) voucher_amount, voucher_date from order_vouchers 
                    where order_vouchers.business_id = '".$this->session->userdata('businessid')."'
                    and voucher_date  >= '".$startdate."' AND voucher_date <= '".$enddate."'  group by year(voucher_date) 
            ) as vouchers on month(vouchers.voucher_date) = month(invoice.invoice_date) 
            and year(vouchers.voucher_date) = year(invoice.invoice_date) 
            WHERE invoice_date  >= '".$startdate."'
            AND invoice_date <= '".$enddate."'
            AND invoice_status = 'valid' 
            And invoice_type='service' 
            AND invoice.business_id = '".$this->session->userdata('businessid')."' ;";
                
        
                
        $query =$this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    
    function get_month_sales($startdate, $enddate){
        //WHERE month(voucher_date)  >= '".$startdate."'  AND year(voucher_date) <= '".$enddate."' 
        $sql="SELECT date_format(invoice_date, '%M') as 'Month', 
                sum(paid_amount) + sum(advance_amount) + ifnull(voucher_amount,0) as 'Total', 
                sum(paid_amount) Paid, 
                sum(advance_amount) advance, 
                voucher_amount voucher,
                sum(cctip) cctip,
                sum(paid_cash) cash, sum(paid_card) card, sum(paid_check) bank,
                sum(paid_cash) + sum(paid_card) + sum(paid_check) paymentmode
                FROM invoice left join ( 
                    select sum(ifnull(amount,0)) voucher_amount, voucher_date from order_vouchers 
                    where order_vouchers.business_id = '".$this->session->userdata('businessid')."'
                    and month(voucher_date)  >= '".$startdate."'  AND year(voucher_date) <= '".$enddate."'  group by year(voucher_date) 
                ) as vouchers on month(vouchers.voucher_date) = month(invoice.invoice_date) and year(vouchers.voucher_date) = year(invoice.invoice_date) 
                WHERE invoice_date  >= '".$startdate."' 
                AND invoice_date <= '".$enddate."' 
                AND invoice_status = 'valid' 
                And invoice_type='sale' 
                AND invoice.business_id =  '".$this->session->userdata('businessid')."' ;";
                
        
                
        $query =$this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    function get_month_advance($startdate, $enddate){
        
        $sql="select sum(visit_advance.advance_amount) advance from visit_advance
            join customer_visits on customer_visits.id_customer_visits = visit_advance.customer_visit_id
            where visit_advance.advance_date >= '".$startdate."' 
            and visit_advance.advance_date <= '".$enddate."' 
            and customer_visits.visit_status !='canceled'
            AND customer_visits.business_id = '".$this->session->userdata('businessid')."' ;";
                
        
                
        $query =$this->db->query($sql);
        
        return $query->result_array();
        
    }
    
    function get_sale_order_receivings($order_id){
        $account_heads = $this->accounting_model->get_mapped_accounts(37);
        $account_head_id=0;
        foreach($account_heads as $ah){
            if($ah['entity_name']=='total_receivable'){
              $account_head_id = $ah['account_head_id'];
            }
        }
        
         $sql = "SELECT id_account_vouchers, id_account_voucher_detail, ah.account_head, 
                '' as account_main_number, '' as account_control_number,  '' as account_sub_control_number,
                account_head_number, avd.instrument_number,
                description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, 
                date_format(voucher_date,'%d-%m-%Y') voucher_date, av.created_by,
                debit, credit,
                debit-credit as balance, purchase_order_id, auto_voucher
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
                join account_heads ah on ah.id_account_heads = avd.account_head_id
                
                where voucher_status= 'Active' and account_head_id = ". $account_head_id. " ";
                
                if($order_id !== ""){
                    $sql .= " and franchise_order_id='".$order_id."' ";
                }
                
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
               // $sql .= " group by id_account_vouchers";
                $sql .= " order by id_account_vouchers"; 
            //   echo $sql; exit();
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    
    function get_purchase_order_payments($purchase_order_id){
        
        $account_heads = $this->accounting_model->get_mapped_accounts(20);
        $account_head_id=0;
        foreach($account_heads as $ah){
            if($ah['entity_name']=='payables'){
              $account_head_id = $ah['account_head_id'];
            }
        }
        
         $sql = "SELECT id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, 
                date_format(voucher_date,'%d-%m-%Y %h:%i') voucher_date, av.created_by,
                debit, credit,
                credit-debit as balance, grn_id, purchase_order_id, auto_voucher
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
               
                where voucher_status= 'Active' and account_head_id = ". $account_head_id. " ";
                
                if($purchase_order_id !== ""){
                    $sql .= " and purchase_order_id='".$purchase_order_id."' ";
                }
                
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
               // $sql .= " group by id_account_vouchers";
                $sql .= " order by id_account_vouchers"; 
            //   echo $sql; exit();
        $query=$this->db->query($sql);
        return $query->result_array();
        
    }

    public function get_grn_details_payments($purchase_order_id){
        
        $account_heads = $this->accounting_model->get_mapped_accounts(20);
        $account_head_id=0;
        foreach($account_heads as $ah){
            if($ah['entity_name']=='payables'){
              $account_head_id = $ah['account_head_id'];
            }
        }
        
         $sql = "SELECT id_account_vouchers, description, account_voucher_type, 
                avd.cost_center as cost_center_name, business_partner_name, 
                date_format(voucher_date,'%d-%m-%Y %h:%i') voucher_date, av.created_by,
                round(sum(debit),2) as opening,  
                case when sum(debit)-sum(credit) < 0 then 0 
                else  round(sum(debit)-sum(credit),2) end as paid, 
                round(sum(credit),2) as payable, 
                grn_id, purchase_order_id, auto_voucher
                FROM account_vouchers av
                join account_voucher_type avt on avt.id_account_voucher_type = av.voucher_type
                join account_voucher_detail avd on avd.account_voucher_id = av.id_account_vouchers
               
                where voucher_status= 'Active' and account_head_id = ". $account_head_id. " ";
                
                if($purchase_order_id !== ""){
                    $sql .= " and purchase_order_id='".$purchase_order_id."' ";
                }
                
                $sql .= " and av.business_id=".$this->session->userdata('businessid');
               // $sql .= " group by id_account_vouchers";
                $sql .= " group by id_account_vouchers order by id_account_vouchers"; 
               //echo $sql; exit();
        $query=$this->db->query($sql);
        return $query->result_array();
        
    
    }
    
    public function insert_po_payment(){
      // exit();
        $payable = $this->input->post('txtpayable');
        $discount = $this->input->post('txtdiscount');
        $addition = $this->input->post('txtadditionalcharge');
        $discountedprice = $this->input->post('txtdiscount');
        $discountedprice = $discountedprice  + $addition;
        
        $salestax=$this->input->post('txtsalestax');
        $withholdingtax=$this->input->post('txtwithholdingtax');
        $finalprice=$this->input->post('txtfinalprice');
        
        
        $remainingpayable = ($payable + $salestax) - ($finalprice+$discount+$withholdingtax-$addition);
        
        if($this->input->post('voucher_payment_mode')=="Cash"){
            $ac_head=$this->input->post('cash_accounts');
        } else if($this->input->post('voucher_payment_mode')=="Card") {
            $ac_head=$this->input->post('card_accounts');
        } else {
            $ac_head=$this->input->post('bank_accounts');
        }
        
        $data = array( 
            'business_id' => $this->session->userdata('businessid'),
            'description' => $this->input->post('description'),
            'voucher_date' => $this->input->post('account_voucher_date'),
            'voucher_amount' => $finalprice,
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> $this->input->post('cost_center_type'),
            'cost_center_name'=> $this->input->post('cost_center'),
            'business_partner'=> 2,
            'business_partner_name'=> $this->input->post('business_partner'),
            'business_partner_id'=> $this->input->post('business_partner_id'),
            'voucher_type'=> 1,
            'purchase_order_id'=>$this->input->post('txtpurchaseorderid'),
            'payment_mode'=>$this->input->post('voucher_payment_mode'),
            'auto_voucher'=>'No'
        );
        
        $this->db->insert('account_vouchers', $data);
        $account_voucherid =  $this->db->insert_id();
       
                
       $account_heads=$this->get_mapped_accounts(24);
       
       $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']);
            }
        }
            
        //Debit Supplies//
         
        if($this->input->post('voucher_payment_mode')==='Bank'){$ac_head=$this->input->post('bank_accounts');}
        if($this->input->post('voucher_payment_mode')==='Cash'){$ac_head=$this->input->post('cash_accounts');}
        if($this->input->post('voucher_payment_mode')==='Card'){$ac_head=$this->input->post('card_accounts');}
        
        
        foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                
                if($debit[2]=="payable"){$debitamount= $payable-$remainingpayable;}
                if($debit[2]=="purchase_salestax"){$debitamount= $salestax;}
               if($debit[2]=="purchase_charges"){$debitamount= $addition;}
                
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0,
                    'instrument_number' => $this->input->post('instrument_number')
                );
                //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]=="purchase_discount"){$creditamount= $discount;}
               if($credit[2]=="purchase_withholdingtax"){$creditamount= $withholdingtax;}
               //if($credit[2]=="payable" && $remainingpayable>0){$creditamount= $remainingpayable;} 
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2),
                    'instrument_number' => $this->input->post('instrument_number')
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }

            //Credit Fixed//
        $data = array(
            'account_voucher_id' => $account_voucherid,
            'account_head_id' => $ac_head,
            'debit' => 0,
            'credit' => $finalprice,
            'cost_center_type'=> $this->input->post('cost_center_type'),
            'cost_center'=> $this->input->post('cost_center'),
            'instrument_number' => $this->input->post('instrument_number'),
            'payment_mode'=>$this->input->post('voucher_payment_mode')
        );
        $this->db->insert('account_voucher_detail', $data);
        
        return $account_voucherid;
        
    }
    
    public function insert_supplier_payable(){
         
        $data = array( 
            'business_id' => $this->session->userdata('businessid'),
            'description' => $this->input->post('description'),
            'voucher_date' => $this->input->post('account_voucher_date'),
            'voucher_amount' => $this->input->post('txtpaymentamount'),
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> $this->input->post('cost_center_type'),
            'cost_center_name'=> $this->input->post('cost_center'),
            'business_partner'=> 2,
            'business_partner_name'=> $this->input->post('business_partner'),
            'business_partner_id'=> $this->input->post('business_partner_id'),
            'payment_mode' => $this->input->post('voucher_payment_mode'),
            'voucher_type'=> 3
        );
        
        $this->db->insert('account_vouchers', $data);
        $voucher_id =  $this->db->insert_id();
       
        //Supplies increase Asset Debit//
        
        $data = array(
            'account_voucher_id' => $voucher_id,
            'debit' => $this->input->post('txtpaymentamount'),
            'credit' => 0,
            'cost_center'=> $this->input->post('cost_center_type'),
            'cost_center_name'=> $this->input->post('cost_center'),
            'instrument_number' => $this->input->post('instrument_number'),
            'payment_mode' => $this->input->post('voucher_payment_mode'),
            'account_head_id' => $ac_head
        );
        $this->db->insert('account_voucher_detail', $data);
       
        //Accounts Payable increase liability Credit//
        $data = array(
            'account_voucher_id' => $voucher_id,
            'account_head_id' => 11,
            'debit' => $this->input->post('txtpaymentamount'),
            'credit' => 0,
            'cost_center'=> $this->input->post('cost_center_type'),
            'cost_center_name'=> $this->input->post('cost_center'),
            'instrument_number' => $this->input->post('instrument_number')
        );
        $this->db->insert('account_voucher_detail', $data);
        
        return $voucher_id;
        
    }
    
    function cancel_voucher($voucher_id){
        
        $this->db->set('voucher_status','cancelled');
        $this->db->set('cancelled_by', $this->session->userdata('username'));
        $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
       // $this->db->set('voucher_status','cancelled');
        $this->db->where('id_account_vouchers', $voucher_id);
        $this->db->update('account_vouchers');
        
        return $this->db->affected_rows();
        
    }
    
    function get_cash_info($startdate,$enddate,$t=null){
        
        $today = $startdate." 00:00";
        $tomorrow = $enddate." 23:59";

        $business_id = $this->session->userdata('businessid');
        
        //balances
        $sub_query1 = ""
                . "SELECT SUM(balance) FROM invoice "
                . "WHERE "
                . "invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //paid amount
        $sub_query2 = ""
                . "SELECT SUM(paid_amount) FROM invoice "
                . "WHERE reference_invoice_number != '' AND "
                . "invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //total sale payable services
        $sub_query3 = ""
                . "SELECT SUM(total_payable) FROM invoice "
                . "WHERE invoice_type = 'service'   AND reference_invoice_number = '' And "
                . "invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //total sale payable retail
        $sub_query4 = ""
                . "SELECT SUM(total_payable) FROM invoice "
                . "WHERE invoice_type = 'sale' AND reference_invoice_number = '' AND "
                . "invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
       

        //Paid cash
        //use in accounts
        $sub_query5 = ""
                ."
                    SELECT ifnull(SUM(paid_cash),0) as 'Cash' 
                    FROM invoice WHERE payment_mode in ('Cash','Mixed') AND invoice_date >= '".$today."'
                    AND invoice_date <= '".$tomorrow."' AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ";
        
        //Card changing paid_amount to paid_card
        //use in accounts
        $sub_query6 = ""
                ."SELECT ifnull(SUM(paid_card),0) as 'Card' 
                    FROM invoice WHERE payment_mode in ('Card','Mixed') AND invoice_date >= '".$today."'
                    AND invoice_date <= '".$tomorrow."' AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ";
       
        //Check changing paid_amount to paid_check
        //use in accounts
        $sub_query7 = ""
                ."SELECT ifnull(SUM(paid_check),0) as 'Check' 
                    FROM invoice WHERE payment_mode = 'Check' AND invoice_date >= '".$today."'
                    AND invoice_date <= '".$tomorrow."' AND business_id = ".$business_id." AND invoice_status = 'valid' 
                    ";
        //advance adjusted
        $sub_query8 = ""
                . "SELECT SUM(advance_amount) FROM invoice "
                . "WHERE "
                . "invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //Todays Sale
        $sub_query9 = ""
                . "SELECT SUM(gross_amount) FROM invoice "
                . "WHERE reference_invoice_number = ''  AND "
                . "invoice_date >= '$today' AND invoice_date <= '$tomorrow' 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 "
                . "invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //totalAdvance from visit_advance
        //use in accounts
        $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_advance.advance_date >= '$today' AND visit_advance.advance_date <= '$tomorrow' AND "
                . "business_id = $business_id";
        
        //retained amount
        $sub_query12 = "" 
                . "SELECT SUM(retained_amount) FROM invoice "
                . "WHERE invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //cctip amount
        $sub_query13 = "" 
                . "SELECT SUM(cctip) FROM invoice "
                . "WHERE invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        //cctip amount
        $sub_query14 = "" 
                . "SELECT SUM(cc_charge) FROM invoice "
                . "WHERE invoice_date >= '$today' AND invoice_date <= '$tomorrow' AND "
                . "business_id = $business_id AND invoice_status = 'valid'";
        
        $this->db->select("SUM(paid_amount) AS totalPaid, "
                . "($sub_query5) AS Cash, "
                . "($sub_query6) AS Card, "
                . "($sub_query7) AS Checks, "
                . "($sub_query11) AS Advance "
                . "");
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('invoice_date >=', $today);
        $this->db->where('invoice_date <=', $tomorrow);
        $this->db->where('invoice_status', 'valid');
        $this->db->where('payment_mode', 'Cash');
        
        $query = $this->db->get('invoice');
       
       
        return $query->row();
        
    }
    
    function get_cash_voucher($startdate,$enddate,$t = null){

        $business_id = $this->session->userdata('businessid');
        $today = $startdate;
        $tomorrow = $enddate;
        
        
        $sub_query1 = ""
                . "SELECT ifnull(SUM(amount),0) FROM order_vouchers "
                . "WHERE payment_mode = 'Cash'  AND "
                . "date_format(voucher_date, '%Y-%m-%d') >= '$today' AND "
                . "date_format(voucher_date, '%Y-%m-%d') <= '$tomorrow' 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 "
                . "date_format(voucher_date, '%Y-%m-%d') <= '$tomorrow' 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 "
                . "date_format(voucher_date, '%Y-%m-%d') <= '$tomorrow' 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);
        $this->db->where('date_format(voucher_date,"%Y-%m-%d") <=', $tomorrow);
        $query = $this->db->get('order_vouchers');
       // echo $query; exit();
        return $query->row();
        
    }
    
    function add_account_voucher($data, $debit_accounts, $credit_accounts){
      //  exit;
        $this->db->insert('account_vouchers', $data);
        $voucher_id =  $this->db->insert_id();
        
        
        foreach($debit_accounts as $debit){
            $a = explode("|", $debit);
            //if($a[1] > 0){
                $data_detail=array(
                    'account_voucher_id' => $voucher_id,
                    'account_head_id' => $a[0],
                    'debit' => $a[1],
                    'credit' => 0
                );
                $this->db->insert('account_voucher_detail', $data_detail);
            //}
        }
        foreach($credit_accounts as $credit){
            $a = explode("|", $credit);
            //if($a[1] > 0){
                $data_detail=array(
                    'account_voucher_id' => $voucher_id,
                    'account_head_id' => $a[0],
                    'debit' => 0,
                    'credit' => $a[1]
                );
                 $this->db->insert('account_voucher_detail', $data_detail);
            //}
        }
        return $voucher_id;
    }
    
    
    
    
    
    function get_mapped_accounts($eventid, $business_id=null){
        
        if(null==$business_id){
            $business_id=$this->session->userdata('businessid');
        }
        
        
        $sql="SELECT account_head_id, transaction_type, entity_name, description FROM account_event_mapping
                where account_event_id = ".$eventid." and business_id=".$business_id.";";
        
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    
    function get_mapped_account_by_name($account_name, $business_id=null){
       
        $account_name = str_replace("_", " " , ucwords($account_name, "_"));
       //  print_r($account_name);
        if(null==$business_id){
            $business_id=$this->session->userdata('businessid');
        }
        
        
        $sql="SELECT account_head_id, account_heads.account_head, transaction_type, entity_name, description FROM account_event_mapping
                join account_heads on account_heads.id_account_heads = account_event_mapping.account_head_id 
                where account_heads.account_head like '".$account_name."%'  and account_heads.business_id=".$business_id.";";
       // if($account_name=='Mobile Allowance'){echo $sql;}
        $query=$this->db->query($sql);
        return $query->row();
    }
    
    
    
    function get_event_account($eventid, $entity_name){
        $sql="SELECT account_head_id, account_head FROM account_event_mapping
            join account_heads on id_account_heads = account_event_mapping.account_head_id
                where account_event_id = ".$eventid." and entity_name = '".$entity_name."' and account_event_mapping.business_id=".$this->session->userdata('businessid').";";
        
        $query=$this->db->query($sql);
        return $query->row();
        
    }
       
    
    function get_all_events(){
        
        $this->db->select("*");
      //  $this->db->where("business_id", $this->session->userdata('businessid'));
        $query = $this->db->get("account_events");
        
        return $query->result_array();
        
    }
    
    function get_account_event($eventid){
        
        $this->db->select("*");
        $this->db->where("id_account_events", $eventid);
        $query = $this->db->get("account_events");
        
        return $query->result_array();
        
    }
    
    
    function get_event_mappings($idaccountevent=null){
        
        $sql = "SELECT *, account_heads.business_id as idbusiness 
        FROM account_events
        left join account_event_mapping
        on account_event_mapping.account_event_id = id_account_events
        left join account_heads on account_heads.id_account_heads = account_event_mapping.account_head_id
        left join account_sub_control on account_sub_control.id_account_sub_control = account_heads.account_sub_control_id
        where account_event_mapping.business_id=".$this->session->userdata('businessid')." 
        and id_account_events= ".$idaccountevent." 
        order by id_account_events, transaction_type ";
        
        $query = $this->db->query($sql);
        
        
        return $query->result_array();
    }
    
    function invoice_retained($customerid, $sh=false){
      $this->db->select("id_customers as customer_id, customers.customer_name, customers.customer_cell, customers.customer_type, 0 'earned', 0 'used', 0 'loyalty_points', sum(ifnull(retained_amount,0)) - sum(ifnull(retained_amount_used,0)) 'retained'");
         if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
             $this->db->join('invoice','invoice.customer_id = customers.id_customers and invoice_status="valid" and invoice.invoice_seq > 0 and invoice.business_id = '.$this->session->userdata("businessid").'  AND id_invoice not in (select invoice_id from account_vouchers where business_partner_id ="'.$customerid.'") ', 'left') ;
        } else {
             $this->db->join('invoice','invoice.customer_id = customers.id_customers and invoice_status="valid" and invoice.business_id = '.$this->session->userdata("businessid").'   AND id_invoice not in (select invoice_id from account_vouchers where business_partner_id ="'.$customerid.'") ', 'left') ;
        }
               
               
        $this->db->where("id_customers =", $customerid);
        $this->db->where("invoice.business_id =", $this->session->userdata('businessid'));
        $this->db->group_by('id_customers');
        $query = $this->db->get('customers');
       // echo $query; exit();
        return $query->row();
        
        
    }
    
    function voucher_retained($customerid){
        //get retained from vouchers
        $account_head_id=0;
        $sql="select account_head_id from account_event_mapping where entity_name = 'retained_amount' and business_id = ".$this->session->userdata('businessid')."";
        $q=$this->db->query($sql);
        $ah=$q->row();
        
        if($ah){
            $account_head_id=$ah->account_head_id;
        }
        $sql="select id_customers as customer_id, customer_name, customer_cell, customer_type, 0 as earned, 
                0 as used, 0 as loyalty_points,
                            ifnull(sum(credit)-sum(debit),0) as 'retained' 
                                        from customers           
                            left join  
                                        (select business_partner_id, debit, credit 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 = ".$account_head_id." 
                                        and business_partner = 1 
                                        and account_vouchers.voucher_status= 'Active'
                            ) as account_vouchers on customers.id_customers = account_vouchers.business_partner_id 

                                        where id_customers=".$customerid." 
                            group by id_customers, customer_name, customer_cell, customer_type";
        $query1 = $this->db->query($sql);
        return $query1->row();
        
        
    }
    
    function decreasetheretained($frombranch, $tobranch){
        $customername=$this->input->post('customer_name');
        $customerid=$this->input->post('customer_id');
        
        $amount = $this->input->post('transferamount');
        
        $this->db->select('*');
        $this->db->where('id_business', $frombranch);
        $query = $this->db->get('business');
        
        $frombusiness = $query->row();
        
        
        
        $this->db->select('*');
        $this->db->where('id_business', $tobranch);
        $query = $this->db->get('business');
        
        $tobusiness = $query->row();
        
        ///create transfer out account voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(35);
            //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' => 'Retained Amount for customer '.$customername.' customer ID : '. $customerid . ' Transfered to Branch: '.$tobusiness->business_name.' ',
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $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'=>4,
                'payment_mode'=>'Cash',
                'bank_name'=>$bank_name,                
                'auto_voucher'=>'Yes',
                
            );

            $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]=="retained_amount"){$debitamount= $amount;}              
                
                
                $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);
                }
            }
            
            
            
            ////make another transfer voucher for payabale
//            $data = array( 
//                'business_id' => $this->session->userdata('businessid'),
//                'description' => 'Retained Amount for customer '.$customername.' customer ID : '. $customerid . ' Transfered to Branch: '.$tobusiness->business_name.' ',
//                'voucher_date' => date('Y-m-d H:i:s'),
//                'voucher_amount' => $amount,
//                'voucher_status' => 'Active',
//                'created_by' => $this->session->userdata('username'),
//                'cost_center'=> '1',
//                'cost_center_name'=> 'Front Desk',
//                'business_partner'=> 1,
//                'business_partner_id'=>$tobusiness->id_business,
//                'business_partner_name'=>$tobusiness->business_name,
//                'voucher_type'=>4,
//                'payment_mode'=>'Cash',
//                'bank_name'=>$bank_name,
//                'auto_voucher'=>'Yes',
//                
//            );
//
//            $this->db->insert('account_vouchers', $data);
//            $account_voucherid1 =  $this->db->insert_id();
//            
//            
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                if($credit[2]=="payable"){$creditamount= $amount;}
                
            
                $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 increasetheretained($frombranch, $tobranch){
        $customername=$this->input->post('customer_name');
        $customerid=$this->input->post('customer_id');
        
        $amount = $this->input->post('transferamount');
        
        $this->db->select('*');
        $this->db->where('id_business', $frombranch);
        $query = $this->db->get('business');
        
        $frombusiness = $query->row();
        
        
        
        $this->db->select('*');
        $this->db->where('id_business', $tobranch);
        $query = $this->db->get('business');
        
        $tobusiness = $query->row();
        
        ///create transfer in account voucher to branch
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(36, $tobranch);
            //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' => $tobranch,
                'description' => 'Retained Amount for customer '.$customername.' customer ID : '. $customerid . ' Transfered from Branch: '.$frombusiness->business_name.' ',
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $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'=>4,
                'payment_mode'=>'Cash',
                'bank_name'=>$bank_name,                
                'auto_voucher'=>'Yes',
                
            );

            $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]=="receivable"){$debitamount= $amount;}              
                
                
                $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);
                }
            }
            
            
            
            ////make another transfer voucher for customer retained
//            $data = array( 
//                'business_id' => $tobranch,
//                'description' => 'Retained Amount for customer '.$customername.' customer ID : '. $customerid . ' Transfered from Branch: '.$frombusiness->business_name.' ',
//                'voucher_date' => date('Y-m-d H:i:s'),
//                'voucher_amount' => $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'=>4,
//                'payment_mode'=>'Cash',
//                'bank_name'=>$bank_name,
//                'auto_voucher'=>'Yes',
//                
//            );
//
//            $this->db->insert('account_vouchers', $data);
//            $account_voucherid1 =  $this->db->insert_id();
            
            
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                if($credit[2]=="retained_amount"){$creditamount= $amount;}
                
            
                $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 get_account_status($startdate=null, $enddate=null, $account_id=null, $list='', $type='single'){
        
        if($startdate==null){
            if(null !== $this->input->post('startdate')){
                $startdate = $this->input->post('startdate');
                $enddate = $this->input->post('enddate');
            } else {
                $startdate = date('Y-m-d');
            }
        }
        
        if(null==$account_id){
            $account_id = $this->input->post('account_id');
        }
        
         $sql="SELECT sale_type, account_main, account_head, account_head_id, 
            ifnull(sum(credit),0) as credit, 
            ifnull(sum(debit),0) as debit, 
            ifnull(sum(debit),0) - ifnull(sum(credit),0) as assetbalance,
            ifnull(sum(credit),0) - ifnull(sum(debit),0) as liabilitybalance
                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 date(account_vouchers.voucher_date) >= '".$startdate."'   
                AND date(account_vouchers.voucher_date) <= '".$enddate."'   
                AND `account_vouchers`.`voucher_status` = 'Active' ";
                
                if($list!==''){            
                    $sql .=" and account_head_id in (".$list.") ";
                } else {
                    $sql .="  AND account_head_id = ".$account_id." ";
                }
                
                if($type=='single'){
                    $sql.=" group by sale_type, account_main, account_head, account_head_id order by 1,3";
                }else {
                    $sql.=" group by account_main, account_head, account_head_id order by 1,3";
                }
              
         
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }

    function status_cash_register($id_cash_register, $status){
       // echo $id_cash_register; exit();
        $this->db->set('register_status', $status);
        $this->db->where('id_cash_register', $id_cash_register);
        $this->db->update('cash_register');
    }

    function get_retained_income($startdate, $business_id=null) {
        
        
        $sql = "select 
                account_main, account_control, account_sub_control, account_head,
                 sum(ifnull(debit,0)) as debit, sum(ifnull(credit,0)) as credit, 
                 sum(ifnull(debit,0)) - sum(ifnull(credit,0)) as 'AssetBal',
                 sum(ifnull(credit,0)) - sum(ifnull(debit,0)) as 'LiabilityBal'
                from account_voucher_detail
                join account_vouchers on id_account_vouchers = account_voucher_detail.account_voucher_id
                join account_heads on id_account_heads = account_voucher_detail.account_head_id
                join account_sub_control on id_account_sub_control = account_heads.account_sub_control_id
                join account_control on id_account_control = account_sub_control.account_control_id
                join account_main on id_account_main = account_control.account_main_id
                where
                account_main in ('Revenue','Expenses')                
                and account_vouchers.voucher_status='Active'
                and date(account_vouchers.voucher_date) <= '".$startdate."' 
                and account_vouchers.business_id = ".$business_id." 
                group by id_account_main, id_account_control, id_account_sub_control, id_account_heads";
        //    echo $sql; exit();
        $query = $this->db->query($sql);
        $result = $query->result_array();
        
        $revenue = 0;
        $expenses = 0;
        foreach ($result as $row){
            if($row['account_main']=='Revenue'){
                $revenue+=$row['LiabilityBal'];
            } else if($row['account_main']=='Expenses'){
                $expenses+=$row['AssetBal'];
                
            }
        }
        
        $retainedincome = $revenue - $expenses;
        return $retainedincome;
    }
 
    function trial_balance($startdate, $enddate){
        
        $sql = "SELECT business.business_name, concat(account_main.account_main_number,'-', account_control.account_control_number,'-', account_sub_control.account_sub_control_number,'-', account_heads.account_head_number) as account_number,
                account_heads.id_account_heads, account_main.account_main, account_control.account_control, account_sub_control.account_sub_control,  account_heads.account_head,
                CASE 
                    WHEN account_main like 'Asset%' OR account_main like 'Expens%' THEN 'debit'
                    ELSE 'credit' END as account_type,
                IFNULL(opening.opening_debit,0) as opening_debit, 
                IFNULL(opening.opening_credit,0) as opening_credit, 
                IFNULL(opening.opening_balance,0) as opening_balance,
                IFNULL(current_period.current_debit,0) as current_debit, 
                IFNULL(current_period.current_credit,0) as current_credit, 
                IFNULL(current_period.current_balance,0) as current_balance,
                CASE 
                    WHEN account_main like 'Asset%' OR account_main like 'Expens%'
                        THEN (IFNULL(opening_debit,0) + IFNULL(current_debit,0)) - (IFNULL(opening_credit,0) + IFNULL(current_credit,0)) 
                    ELSE
                        (IFNULL(opening_credit,0) + IFNULL(current_credit,0))  - (IFNULL(opening_debit,0) + IFNULL(current_debit,0))
                END
                as net_balance

                FROM account_heads
                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 
                JOIN business ON business.id_business = account_heads.business_id
                LEFT JOIN (
                SELECT 
                    id_account_heads, 
                    ROUND(IFNULL(SUM(debit),0),2) as opening_debit,
                    ROUND(IFNULL(SUM(credit),0),2) as opening_credit,
                    CASE 
                    WHEN account_main.account_main like 'Asset%' OR account_main.account_main like 'Expens%'                    
                    THEN ROUND(IFNULL(SUM(debit),2) - IFNULL(SUM(credit), 0),2)
                    ELSE  ROUND(IFNULL(SUM(credit),2) - IFNULL(SUM(debit), 0),2)
                    END AS 'opening_balance'    
                FROM
                    account_vouchers av
                        JOIN
                    account_voucher_type avt ON avt.id_account_voucher_type = av.voucher_type
                        JOIN
                    account_voucher_detail avd ON avd.account_voucher_id = av.id_account_vouchers
                        JOIN
                    account_heads ah ON ah.id_account_heads = avd.account_head_id
                        JOIN
                    account_sub_control asct ON ah.account_sub_control_id = asct.id_account_sub_control
                        JOIN
                    account_control ac ON ac.id_account_control = asct.account_control_id
                        JOIN
                    account_main ON account_main.id_account_main = ac.account_main_id
                    JOIN business ON business.id_business = ah.business_id   
                WHERE
                    voucher_status = 'Active' ";   
                    if($this->session->userdata('ho')=='No'){
                        $sql .= " and av.business_id=".$this->session->userdata('businessid');
                    } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                        $sql .= " and av.business_id=".$this->input->post('business_id');
                    } else {
                        $sql.= " and business.common_products = 'Yes' ";
                    }
                    $sql .="   AND date(voucher_date) < '".$startdate."'
                GROUP BY ah.id_account_heads) as opening
                ON opening.id_account_heads = account_heads.id_account_heads


                LEFT JOIN (
                SELECT 
                    id_account_heads, 
                    ROUND(IFNULL(SUM(debit),0),2) as current_debit,
                    ROUND(IFNULL(SUM(credit),0),2) as current_credit,
                    CASE 
                    WHEN account_main.account_main like 'Asset%' OR account_main.account_main like 'Expens%'                    
                    THEN ROUND(IFNULL(SUM(debit),2) - IFNULL(SUM(credit), 0),2)
                    ELSE  ROUND(IFNULL(SUM(credit),2) - IFNULL(SUM(debit), 0),2)
                    END AS 'current_balance'    
                FROM
                    account_vouchers av
                        JOIN
                    account_voucher_type avt ON avt.id_account_voucher_type = av.voucher_type
                        JOIN
                    account_voucher_detail avd ON avd.account_voucher_id = av.id_account_vouchers
                        JOIN
                    account_heads ah ON ah.id_account_heads = avd.account_head_id
                        JOIN
                    account_sub_control asct ON ah.account_sub_control_id = asct.id_account_sub_control
                        JOIN
                    account_control ac ON ac.id_account_control = asct.account_control_id
                        JOIN
                    account_main ON account_main.id_account_main = ac.account_main_id
                    JOIN business ON business.id_business = ah.business_id    
                WHERE
                    voucher_status = 'Active'    ";   
                    if($this->session->userdata('ho')=='No'){
                        $sql .= " and av.business_id=".$this->session->userdata('businessid');
                    } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                        $sql .= " and av.business_id=".$this->input->post('business_id');
                    } else {
                        $sql.= " and business.common_products = 'Yes' ";
                    }
                    $sql .="  AND date(voucher_date) >= '".$startdate."'
                        AND date(voucher_date) <= '".$enddate."'
                GROUP BY ah.id_account_heads) as current_period
                ON current_period.id_account_heads = account_heads.id_account_heads
                WHERE ";                
                if($this->session->userdata('ho')=='No'){
                    $sql .= "  account_heads.business_id=".$this->session->userdata('businessid');
                } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                    $sql .= "  account_heads.business_id=".$this->input->post('business_id');
                } else {
                    $sql.= "  business.common_products = 'Yes' ";
                }
                $sql.=" ORDER BY account_main, id_account_heads";
        //echo $sql; exit();
        $query=$this->db->query($sql);
        return $query->result_array();
    }
    
    function trial_balance_new($startdate, $enddate){
        $sql="";
        if($this->session->userdata('ho')=='Yes'){ 
            $sql .= "SELECT group_concat(business_name) business_name, account_head_number account_number, group_concat(id_account_heads) id_account_heads, 
            account_main, account_control, account_sub_control, group_concat(account_head) account_head,
            account_type,
            sum(opening_debit) opening_debit,
            sum(opening_credit) opening_credit,
            sum(opening_balance) opening_balance,
            sum(current_debit) current_debit,
            sum(current_credit) current_credit,
            sum(current_balance) current_balance,
            sum(net_balance) net_balance            
             FROM (";
        }
        
        $sql .= " SELECT account_head_number, business.business_name, concat(account_main.account_main_number,'-', account_control.account_control_number,'-', account_sub_control.account_sub_control_number,'-', account_heads.account_head_number) as account_number,
                account_heads.id_account_heads, account_main.account_main, account_control.account_control, account_sub_control.account_sub_control,  account_heads.account_head,
                CASE 
                    WHEN account_main like 'Asset%' OR account_main like 'Expens%' THEN 'debit'
                    ELSE 'credit' END as account_type,
                IFNULL(opening.opening_debit,0) as opening_debit, 
                IFNULL(opening.opening_credit,0) as opening_credit, 
                IFNULL(opening.opening_balance,0) as opening_balance,
                IFNULL(current_period.current_debit,0) as current_debit, 
                IFNULL(current_period.current_credit,0) as current_credit, 
                IFNULL(current_period.current_balance,0) as current_balance,
                CASE 
                    WHEN account_main like 'Asset%' OR account_main like 'Expens%'
                        THEN (IFNULL(opening_debit,0) + IFNULL(current_debit,0)) - (IFNULL(opening_credit,0) + IFNULL(current_credit,0)) 
                    ELSE
                        (IFNULL(opening_credit,0) + IFNULL(current_credit,0))  - (IFNULL(opening_debit,0) + IFNULL(current_debit,0))
                END
                as net_balance

                FROM account_heads
                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 
                JOIN business ON business.id_business = account_heads.business_id
                LEFT JOIN (
                SELECT 
                    id_account_heads, 
                    ROUND(IFNULL(SUM(debit),0),2) as opening_debit,
                    ROUND(IFNULL(SUM(credit),0),2) as opening_credit,
                    CASE 
                    WHEN account_main.account_main like 'Asset%' OR account_main.account_main like 'Expens%'                    
                    THEN ROUND(IFNULL(SUM(debit),2) - IFNULL(SUM(credit), 0),2)
                    ELSE  ROUND(IFNULL(SUM(credit),2) - IFNULL(SUM(debit), 0),2)
                    END AS 'opening_balance'    
                FROM
                    account_vouchers av
                        JOIN
                    account_voucher_type avt ON avt.id_account_voucher_type = av.voucher_type
                        JOIN
                    account_voucher_detail avd ON avd.account_voucher_id = av.id_account_vouchers
                        JOIN
                    account_heads ah ON ah.id_account_heads = avd.account_head_id
                        JOIN
                    account_sub_control asct ON ah.account_sub_control_id = asct.id_account_sub_control
                        JOIN
                    account_control ac ON ac.id_account_control = asct.account_control_id
                        JOIN
                    account_main ON account_main.id_account_main = ac.account_main_id
                    JOIN business ON business.id_business = ah.business_id   
                WHERE
                    voucher_status = 'Active' ";   
                    if($this->session->userdata('ho')=='No'){
                        $sql .= " and av.business_id=".$this->session->userdata('businessid');
                    } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                        $sql .= " and av.business_id=".$this->input->post('business_id');
                    } else {
                        $sql.= " and business.common_products = 'Yes' ";
                    }
                    $sql .="   AND date(voucher_date) < '".$startdate."'
                GROUP BY ah.id_account_heads) as opening
                ON opening.id_account_heads = account_heads.id_account_heads


                LEFT JOIN (
                SELECT 
                    id_account_heads, 
                    ROUND(IFNULL(SUM(debit),0),2) as current_debit,
                    ROUND(IFNULL(SUM(credit),0),2) as current_credit,
                    CASE 
                    WHEN account_main.account_main like 'Asset%' OR account_main.account_main like 'Expens%'                    
                    THEN ROUND(IFNULL(SUM(debit),2) - IFNULL(SUM(credit), 0),2)
                    ELSE  ROUND(IFNULL(SUM(credit),2) - IFNULL(SUM(debit), 0),2)
                    END AS 'current_balance'    
                FROM
                    account_vouchers av
                        JOIN
                    account_voucher_type avt ON avt.id_account_voucher_type = av.voucher_type
                        JOIN
                    account_voucher_detail avd ON avd.account_voucher_id = av.id_account_vouchers
                        JOIN
                    account_heads ah ON ah.id_account_heads = avd.account_head_id
                        JOIN
                    account_sub_control asct ON ah.account_sub_control_id = asct.id_account_sub_control
                        JOIN
                    account_control ac ON ac.id_account_control = asct.account_control_id
                        JOIN
                    account_main ON account_main.id_account_main = ac.account_main_id
                    JOIN business ON business.id_business = ah.business_id    
                WHERE
                    voucher_status = 'Active'    ";   
                    if($this->session->userdata('ho')=='No'){
                        $sql .= " and av.business_id=".$this->session->userdata('businessid');
                    } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                        $sql .= " and av.business_id=".$this->input->post('business_id');
                    } else {
                        $sql.= " and business.common_products = 'Yes' ";
                    }
                    $sql .="  AND date(voucher_date) >= '".$startdate."'
                        AND date(voucher_date) <= '".$enddate."'
                GROUP BY ah.id_account_heads) as current_period
                ON current_period.id_account_heads = account_heads.id_account_heads
                WHERE ";                
                if($this->session->userdata('ho')=='No'){
                    $sql .= "  account_heads.business_id=".$this->session->userdata('businessid');
                } elseif($this->input->post('business_id')!==null && $this->input->post('business_id')!==''){
                    $sql .= "  account_heads.business_id=".$this->input->post('business_id');
                } else {
                    $sql.= "  business.common_products = 'Yes' ";
                }

                $sql.=" ORDER BY account_main, id_account_heads";

                if($this->session->userdata('ho')=='Yes'){ 
                    $sql .= ") as a group by account_head_number ";
                }
        //echo $sql; exit();
        $query=$this->db->query($sql);
        return $query->result_array();
    }

    

    function new_gl_query($startdate, $enddate, $businessid){

        $sql = "SELECT  account_main.account_main,  account_control.account_control, account_sub_control.account_sub_control, account_heads.account_head,    
        CASE WHEN upper(account_sub_control.account_sub_control) LIKE '%COST OF%' THEN 'COST OF GOODS'
        WHEN upper(account_sub_control.account_sub_control) LIKE '%ADMIN EXPENSE%' THEN 'ADMIN EXPENSE'
        WHEN upper(account_sub_control.account_sub_control) LIKE '%FIXED EXPENSE%' THEN 'FIXED EXPENSE'
        WHEN upper(account_sub_control.account_sub_control) LIKE '%SALARY%' THEN 'SALARY EXPENSE'
        END as 'expense_type',    
        COUNT(id_account_vouchers) voucher_count,    round(ifnull(a.opening,0),2) as opening,
        ROUND(SUM(debit), 2) current_debit, ROUND(SUM(credit), 2) current_credit,
        CASE WHEN UPPER(account_main.account_main) LIKE '%ASSET%' OR UPPER(account_main.account_main) LIKE '%EXPENSE%' THEN ROUND(
            IFNULL(SUM(debit) - SUM(credit), 0), 2) 
            ELSE ROUND(IFNULL(SUM(credit) - SUM(debit), 0), 2)
        END AS current_balance,
        ROUND(ifnull(a.opening,0) + CASE WHEN UPPER(account_main.account_main) LIKE '%ASSET%' OR UPPER(account_main.account_main) LIKE '%EXPENSE%' THEN ROUND(
        IFNULL(SUM(debit) - SUM(credit), 0), 2) ELSE ROUND(
        IFNULL(SUM(credit) - SUM(debit), 0), 2) END, 2) AS total_balance
                FROM account_heads 
                JOIN account_voucher_detail  on account_heads.id_account_heads = account_voucher_detail.account_head_id
                JOIN account_vouchers on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_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
                LEFT JOIN(
                    SELECT account_heads.id_account_heads,
                    ROUND(CASE WHEN upper(account_main.account_main) LIKE '%ASSET%' OR upper(account_main.account_main) LIKE '%EXPENSE%' THEN ifnull(sum(debit)-sum(credit),0) 
                        ELSE ifnull(sum(credit)-sum(debit),0)    
                    END, 2) AS opening
                    FROM account_voucher_detail 
                    JOIN account_vouchers 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 date(account_vouchers.voucher_date) < '".$startdate."'
                    AND account_heads.business_id=  ".$businessid."    
                    AND account_vouchers.voucher_status='Active'
                    GROUP BY id_account_heads
                ) AS a ON a.id_account_heads = account_voucher_detail.account_head_id
                WHERE 
                date(account_vouchers.voucher_date) >= '".$startdate."' 
                AND date(account_vouchers.voucher_date) <= '".$enddate."'
                AND account_vouchers.voucher_status='Active'             
                AND account_vouchers.business_id = ".$businessid."             
                GROUP BY account_heads.id_account_heads
                ORDER BY id_account_main, id_account_control, id_account_sub_control, account_heads.id_account_heads;";
               // echo $sql; exit();
        $query = $this->db->query($sql);
        return $query->result_array();

    }

    function new_pl_query($startdate, $enddate, $businessid){
        echo $businessid;

        $sql = "SELECT  account_main.account_main,  account_control.account_control, account_sub_control.account_sub_control, account_heads.account_head,    
        CASE WHEN upper(account_main.account_main) LIKE '%EXPENS%' && upper(account_sub_control.account_sub_control) LIKE '%COST OF%' THEN 'COST OF GOODS'
        WHEN upper(account_main.account_main) LIKE '%EXPENS%' && upper(account_sub_control.account_sub_control) LIKE '%ADMIN EXPENSE%' THEN 'ADMIN EXPENSE'
        WHEN upper(account_main.account_main) LIKE '%EXPENS%' && upper(account_sub_control.account_sub_control) LIKE '%FIXED EXPENSE%' THEN 'FIXED EXPENSE'
        WHEN upper(account_main.account_main) LIKE '%EXPENS%' && upper(account_sub_control.account_sub_control) LIKE '%SALAR%' THEN 'SALARY EXPENSE'
        WHEN upper(account_main.account_main) LIKE '%EXPENS%' THEN 'GENERAL EXPENSE'
        END as 'expense_type',    
        COUNT(id_account_vouchers) voucher_count,  
        
        ROUND(SUM(debit), 2) current_debit, ROUND(SUM(credit), 2) current_credit,
        CASE WHEN UPPER(account_main.account_main) LIKE '%ASSET%' OR UPPER(account_main.account_main) LIKE '%EXPENSE%' THEN ROUND(
            IFNULL(SUM(debit) - SUM(credit), 0), 2) 
            ELSE ROUND(IFNULL(SUM(credit) - SUM(debit), 0), 2)
        END AS current_balance
                FROM account_heads 
                JOIN account_voucher_detail  on account_heads.id_account_heads = account_voucher_detail.account_head_id
                JOIN account_vouchers on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_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 
                date(account_vouchers.voucher_date) >= '".$startdate."' 
                AND date(account_vouchers.voucher_date) <= '".$enddate."'
                AND account_vouchers.voucher_status='Active'             
                AND account_vouchers.business_id = ".$businessid."             
                GROUP BY account_heads.id_account_heads
                ORDER BY id_account_main, id_account_control, id_account_sub_control, account_heads.id_account_heads;";
              //  echo $sql; exit();



        $sql = "select id_account_main, id_account_control, id_account_sub_control, account_heads.id_account_heads, account_main, account_control, account_sub_control, account_head,
                round(sum(debit), 2) debit, 
                round(sum(credit), 2) credit,
                CASE WHEN upper(account_main.account_main) LIKE '%EXPENS%' && upper(account_sub_control.account_sub_control) LIKE '%COST OF%' THEN 'COST OF GOODS'
        WHEN upper(account_main.account_main) LIKE '%EXPENS%' && upper(account_sub_control.account_sub_control) LIKE '%ADMIN EXPENSE%' THEN 'ADMIN EXPENSE'
        WHEN upper(account_main.account_main) LIKE '%EXPENS%' && upper(account_sub_control.account_sub_control) LIKE '%FIXED EXPENSE%' THEN 'FIXED EXPENSE'
        WHEN upper(account_main.account_main) LIKE '%EXPENS%' && upper(account_sub_control.account_sub_control) LIKE '%SALAR%' THEN 'SALARY EXPENSE'
        WHEN upper(account_main.account_main) LIKE '%EXPENS%' THEN 'GENERAL EXPENSE'
        END as 'expense_type',    
        COUNT(id_account_vouchers) voucher_count,  
                Case When account_main.account_main LIKE 'Expense%' OR account_main.account_main LIKE 'Asset%' THEN Round(sum(debit) - sum(credit)) 
                ELSE Round(sum(credit) - sum(debit)) END as Balance ,
                CASE WHEN UPPER(account_main.account_main) LIKE '%ASSET%' OR UPPER(account_main.account_main) LIKE '%EXPENSE%' THEN ROUND(
                    IFNULL(SUM(debit) - SUM(credit), 0), 2) 
                    ELSE ROUND(IFNULL(SUM(credit) - SUM(debit), 0), 2)
                END AS current_balance
                FROM account_heads 
                LEFT JOIN 
                (select id_account_vouchers, account_voucher_detail.account_head_id, debit, credit, account_vouchers.voucher_date 
                from account_voucher_detail
                    JOIN account_vouchers on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                    Where date(account_vouchers.voucher_date) >= '".$startdate."' 
                    AND date(account_vouchers.voucher_date) <= '".$enddate."'
                    and account_vouchers.business_id  = ".$businessid." 
                ) as account_voucher_detail 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_heads.business_id  = ".$businessid." 
                
                
                GROUP BY id_account_main, id_account_control, id_account_sub_control, account_heads.id_account_heads;" ;
                
               // echo $sql; exit();
        $query = $this->db->query($sql);
        //print_r($query->result_array()); exit();
        return $query->result_array();

    }
}


