<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

function get_booking_tables(){
    return array(
            'bill_abishegam'            => 'ba````name_1', // Table Prefix | Booking Date Column Name | NO_BOOK_STATUS (If no booking status column) | Receipt Column name | Name 
            'bill_festival_function'    => '```receipt_no`devotee_name1',
            'bill_hall_booking'         => 'bh`from_date`NO_BOOK_STATUS',
            'bill_kattalai'             => 'bk````name_1',
            'bill_madappalli'           => 'bm````dev_name',
            'bill_mega_function'        => '```receipt_no`devotee_name1',
            'bill_outdoor_services'     => '```receipt_no`devotee_name',
            'bill_prasadam'             => 'bp`fn_date```dev_name_1',
            'bill_ubayam'               => '```receipt_no`devotee_name1',
            'bill_wedding_booking'      => 'bwh`from_date`NO_BOOK_STATUS``groom_name',
	    'bill_donation'		=> '`created_on``receipt_no`name',
            'bill_other_services'	=> '```receipt_no`devotee_name',
            //'bill_temple_shop_sales'    => '',
        );
}

function _get( $tbl_name, $where = array(), $args = array() ) {
    $ci = get_ci_instance();
    $where['status'] = !empty( $where['status'] ) ? $where['status'] : 1;
    
    if( !empty( $args['order_by'] ) ) :
        $ci->db->order_by( $args['order_by'] );
    endif;
    
    if( !empty( $args['select'] ) ) :
        $ci->db->select( $args['select'] );
    endif;
    
    if( $args['is_single'] ) :
        $args['limit'] = 1;
    endif;
    
    if( !empty( $args['limit'] ) ) :
        $ci->db->limit( $args['limit'] );
    endif;

    $q = $ci->db->get_where( $tbl_name, $where );
    //echo "Q: ". $ci->db->last_query(); die;
    
    if( $args['limit'] == 1 ) :
        return $q->row_array();
    else :
        return $q->result_array();
    endif;
}

function generate_rec_no($tbl_name = '', $wh = array()){
    $ci = get_ci_instance();
    
    $ci->db->select('COUNT(id) AS last_count');
    $q = $ci->db->get_where( $tbl_name, $wh );
    $last_no = $q->row_array()['last_count'];
    $receipt_no = (($last_no + 1)  > 9999) ? ($last_no + 1)  : sprintf('0%03d', ($last_no + 1) );
    return $receipt_no;
}

/*
 * Print Receipt
 */
define( 'REMOTE_ADDR', $_SERVER['REMOTE_ADDR'] == "::1" || $_SERVER['REMOTE_ADDR'] == "127.0.0.1" ? gethostbyname(gethostname()) : $_SERVER['REMOTE_ADDR'] );
/* function set_copy($html = ''){
    preg_match_all( '/data-copy="(.*?)">(.*)<\//i', $html, $mtchs );
    if( !empty($mtchs[1][0]) ) :
        $html = str_replace( $mtchs[0][0], '>'. $mtchs[1][0] .'</', $html );
    endif;
    
    return $html;
} */

function set_copy($html = ''){
    preg_match_all( '/data-copy="(.*?)">(.*)<\//i', $html, $mtchs );
    preg_match_all( '/data-rmv-foot="(.*?)">(.*)<\//i', $html, $rmmtchs );
    
    $cpyright_txt = (IS_SHORT) ? '' : 'This is a Computer generated receipt. Signature is not required.';    
    
    if( !empty($mtchs[1][0]) ) :
        $cpyright_txt = '';
        $html = str_replace( $mtchs[0][0], '>'. $mtchs[1][0] .'</', $html );
    endif;
    $html = str_replace( $rmmtchs[0][0], '>'. $cpyright_txt .'</', $html );
    return $html;
}

function fill_ack($args, $msg = ''){   
    if( empty( $msg ) ) :
        return array();
    endif;
    
    if( !array_key_exists( 'ack_msg', $args) ) :
        
        $e      = explode(',', $args['data']['name'][0]);
        $name   = $e[0];

        $module = $args['title'];
        if( !empty( $module ) ) :
            $e = explode('-', $module);
            if( !empty( $e[1] ) ) :
                $module = $e[1];
            endif;
        else :
            $seg = $args['ci']->uri->segments;
            $module = ucfirst(str_replace('billing_', '', $seg[1]));
        endif;

        $date   = $args['data']['date'];
        $time   = $args['data']['time'];

        if( empty( $date ) && empty( $time ) ) :
            // Find in Section

            $sec    = !empty( $args['data']['section'] ) ? $args['data']['section'] : $args['data']['fields'];
        
            if( !empty( $sec ) ) :
                $sec = is_array( $sec[0] ) ? $sec[0] : $sec;
                foreach( $sec as $k => $s ) :
                    if( strpos($k, 'name') >= 0 && empty( $name ) ) :
                        $name = $s;
                    
                    elseif( strpos($k, 'date') >= 0 && empty( $date ) ) :
                        $date = $s;
                    
                    elseif( strpos($k, 'time') >= 0 && empty( $time ) ) :
                        $time = $s;
                    endif;

                endforeach;
            endif;
        endif;    

        if( $args['len'] > 0 ) :
            // Kattalai Archanai like that
            
            $min_date = strtotime(str_replace('/', '-', $date[0][0] ));
            $max_date = 0;
            foreach( $date as $dd ) :
                foreach( $dd as $d ) :
                    $d = str_replace('/', '-', $d);
                    if( strtotime( $d ) > $max_date ) :
                        $max_date = $d;
                    endif;
                    
                    if( strtotime( $d ) <= $min_date ) :
                        $min_date = $d;
                    endif;
                endforeach;
            endforeach;
            
            $date = $min_date == $max_date ? $min_date : $min_date .' to '.$max_date;
            
            $amt = 0;
            foreach( $args['amount'] as $am ) :
                $amt += $am;
            endforeach;
            
            $amt = number_format( $amt, 2 );
            
            
        else :    
            $amt = !is_array( $args['amount'] ) ? $args['amount'] : ( $args['type'] == '3' ? $args['amount'][2] : $args['amount'][0] );
        endif;
        
        
        /*$args['settings'] = array( 'contact_no' => $args['settings']['contact_no'], 'contact_email' =>  $args['settings']['contact_email'] );
        $args['ci'] = null;
        echo "<pre>"; print_r( $args );*/

        $args = array( 
            '1'     => $name, 
            '2'     => trim($module), 
            '3'     => $date, 
            '4'     => $time, 
            '5'     => $amt, 
            '6'     => $args['settings']['contact_no'], 
            '7'     => $args['settings']['contact_email'],
            '8'     => $args['rec_no'],
        );
    endif;
    
    foreach( $args as $k => $arg ) :

        $msg = preg_replace( '/\(\('. ($k) .'\)\)/', $arg, $msg);

    endforeach;

    $args['lang']    = substr( $msg, 0, 3);
    $args['ack_msg'] = substr( $msg, 3);
    
    return $args;
    
}


function send_ack( $args, $html = array() ){
    $ci = get_ci_instance();
    $contact_mail = $args['settings']['contact_email'];
    $args['ci'] = $ci;
    
    /*
     * Get Table Name
     */
    $is_booking_module = FALSE; 
    $tbls = get_booking_tables();
	
    $billing_menu = $ci->session->CI->load->billing_menu;
    foreach( $billing_menu as $x => $bmenu ) :
        
        if( $bmenu['controller_name'] == $ci->uri->segments[1] ) :
            // Current Controller
            if(array_key_exists($bmenu['table_name'], $tbls) ) :
                $is_booking_module = TRUE;
            endif;
            
            break;
        endif;
        
    endforeach;
   
    if( $is_booking_module ) :
        // Proceed to sent
    
        $q = $ci->db->get_where( TBL_BILL_SETT, array('slug' => 'ack_sms_msg', 'status' => 1) );
        $msg = $q->row_array()['value'];
    
        $mail_to = $sms_to = '';
        if(array_key_exists( 'email' , $args['data']) ) :
            $mail_to = $args['data']['email'];
        elseif( !empty( $args['data']['fields'] ) ) :
            foreach( $args['data']['fields'] as $x => $val ) :
                if( stripos( $x, 'Contact No' ) !== FALSE ) :
                    $sms_to = $val;
                elseif( stripos( $x, 'Email ID' ) !== FALSE ) :
                    $mail_to = $val;
                endif;
            endforeach;
        endif;

        
        /*
         * Send SMS
         */
		
        if( TO_SEND && ACK_SMS_SEND && !empty($msg) ) :
            if(empty($sms_to) && array_key_exists( 'contact_no' , $args['data']) ) :
                $sms_to = $args['data']['contact_no'];
            endif;
            
            if( !empty( $sms_to ) ) :
                $args = fill_ack($args, $msg);
               send_sms( $sms_to, $args['ack_msg'] );
            endif;
        endif;

        /*
         * Send Mail
         */
        if( ACK_MAIL_SEND && !empty( $mail_to ) ) :

            $q = $ci->db->get_where( TBL_BILL_SETT, array('slug' => 'ack_mail_msg', 'status' => 1) );
            $msg = $q->row_array()['value'];

            $args = fill_ack($args, $msg);
            $sub  = preg_replace('/\{module\}/', $args['2'], MAIL_SUB );
            $msg  = $html['head'] .'<br /><p>' . $args['ack_msg'] . '</p><br />' . $html['body'] . '<br />';
            $msg  .= '<style type="text/css">
                        .page {
                            border: 1px dotted #999;
                            padding: 20px;
                            box-shadow: 1px 1px 3px #999, -2px -2px 6px #999;
                        }
                     </style>';  
            $msg .= $html['foot'] .'<br />';

            $from = !empty( SMS_FROM ) ? SMS_FROM : 'Tiru';
            if( !empty( $contact_mail ) ) :
                $from .= '<'. $contact_mail .'>';
                $hdrs  = 'From: '. $from ."\r\n";
                //$hdrs .= 'Cc: '. $from . "\r\n";
            else :
                $hdrs  = 'From: '. $from ."\r\n";
            endif;
            $hdrs .= 'X-sender: '. $from ."\r\n";
            $hdrs .= 'X-Mailer: PHP/'. phpversion() ."\r\n";
            //$hdrs .= 'X-Priority: 1'."\r\n";
            $hdrs .= 'MIME-Version: 1.0'."\r\n";
            $hdrs .= 'Content-Type: text/html; charset=iso-8859-1'."\r\n";

            mail( $mail_to, $sub, $msg, $hdrs );
        endif;
    endif;
    
}

function send_sms($sms_to, $sms_msg = '') { 
    $return = array();
    
    $sms_to = !is_array( $sms_to ) ? array($sms_to) : $sms_to;
        
    $to = '';
    foreach( $sms_to as $k => $no ) :
        $to  .= MOB_PREFIX . $no . ',';
    endforeach;

    $sms_to = substr( $to, 0, -1);
    
    
    $query_string = "api.aspx?apiusername=".SMS_USER."&apipassword=".SMS_PWD;
    $query_string .= "&senderid=".rawurlencode(SMS_FROM)."&mobileno=".rawurlencode($sms_to);
    $query_string .= "&message=".rawurlencode(stripslashes($sms_msg))."&languagetype=1";       
	
	
    // $url = "http://gateway.onewaysms.com.au:10001/".$query_string; 
   $url = "http://gateway.onewaysms.sg:10002/".$query_string; 

    if( TO_SEND ) :

            $fd = @implode ('', file ($url));
			
            //$fd = 1;
            if ($fd) :
				
                    if ($fd > 0) :
                    // print("MT ID : " . $fd);
                            $status = "success";
                            $msg = 'SMS is sent successfully';
                    else :

                            //print("Please refer to API on Error : " . $fd);
                            $status = "err";
                            $msg = 'Oops: Something went wrong...Please refer to API (Error Code: '. $fd .')';
                    endif;

            else :
				
                    // no contact with gateway                     
                    $status = "error";
                    $msg = 'Oops: Couldn\'t connect with API';      

            endif; // fd
			


    else :
            $status = 'success';
            $msg = $url;
    endif; // to send

    $return['status'] = $status;
    $return['msg'] = $msg;
    
    return $return;
}

function pay_mode_str($pay_results) {
    $pay_mode_str = '';
    foreach( $pay_results as $kk => $pay_result ) :
        $pay_mode_str .= $pay_result['name'];
        if( $pay_result['pay_details'] != '[]' && !empty( $pay_result['pay_details'] ) ) :
            $pay_details = json_decode( $pay_result['pay_details'], TRUE );
            $pay_mode_str .= ' <span style="font-weight: bold; color: #999; font-size: 10px; letter-spacing: 1px; font-style: italic;">[';
            foreach( $pay_details as $kkk => $pay_detail ) :
                //$pay_mode_str .= ucfirst($kkk) . ': ' . $pay_detail . ', ';
                $pay_mode_str .= $pay_detail . ', ';
            endforeach;
            $pay_mode_str = substr($pay_mode_str, 0, -2) . ']</span>';
        endif;

        $pay_mode_str .= ', ';
    endforeach;

    return !empty( $pay_mode_str ) ? substr($pay_mode_str, 0, -2) : $pay_mode_str;
}

function print_rec($args) {
    //error_reporting(E_ERROR);
    $ci = get_ci_instance();
    
    if( !TO_PRINT ) : // Printing is Disabled
        $ci->session->set_flashdata( REMOTE_ADDR . '_flag' , 'NO' );
        return '';
    endif;    
    
    $is_html = FALSE;
    $user_data = get_user_data();
    $post    = $ci->input->post();   
           
    
    if( !is_array( $args ) ) :
        $is_html = TRUE;
        $args = array('raw_html' => $args, 'copy' => FALSE );
    endif;
    $type = !empty( $args['type'] ) ? $args['type'] : '1';
    define('IS_SHORT', ($type == '5' || $args['short'] ? TRUE : FALSE));
    define('WIDTH', IS_SHORT ? '287' : '1000');//'562');
    $args['is_copy'] = ($type == '1' && !isset($args['copy'])) || $args['copy'] ? TRUE : FALSE;
    $args['sepr'] = '&nbsp;/&nbsp;';
    
    ///$file_name = str_replace(':', '_', $_SERVER['REMOTE_ADDR'] ) .'--' . gethostbyaddr($_SERVER['REMOTE_ADDR']) .'--' .$user_data['user_id'].'--'.time();
    $file_name = ( IS_SHORT ? '' : '#' ) . REMOTE_ADDR .'--' .$user_data['user_id'].'--'.time();
    
    $path = TMP_PRINT_DIR; 
    
    if( !file_exists( $path ) ) :
        mkdir($path, 0777, TRUE);
        chdir($path, 0777);
    endif;
    $path .= $file_name;
    
    /** Settings **/
    $q = $ci->db->get_where( TBL_SETTINGS_BASIC );
    $args['settings'] = $q->row_array();
    
    $q = $ci->db->get_where( TBL_SETTINGS_DESIGN );
    $args['settings'] = array_merge( $args['settings'], $q->row_array() );
    
    /*$q = $ci->db->get_where( TBL_SETTINGS_GENERAL );
    $args['settings'] = array_merge( $args['settings'], $q->row_array() );*/
    
    $pages = 0;
    $copy_html = array();
    /*$top = 235;
    
    if( !empty( $args['data']['desc'] ) ):
        $top -= ( 13 * ceil( strlen( $args['data']['desc'] ) / 95 ) );
    endif;
    
    $args['top'] = $top;*/
    
    $seg = $ci->uri->segments;
    $method = $seg[2];
    $service_id = $method == 'add' || $method == 'insert' ?  $seg[3] : $seg[4];
    $page_id    = $seg[3];
    
    if( !IS_SHORT ) :
        
        /*
         * Get Payment Modes
         */
        if( $method == "print_list" ) :
            // Coming from List page
        
            $whr = array(
                'p.pay_ref_type'  => $service_id,
                'p.pay_ref_id'    => $page_id,
                //'pt.status !='    => 2,
            );
        
            $ci->db->select('pt.name, p.pay_details');//p.id AS payment_id, p.pay_ref_type, p.pay_ref_id, p.pay_type_id, p.pay_amount, pt.id, pt.name');
            $ci->db->group_by('p.pay_type_id');
            $ci->db->select('pt.name');//p.id AS payment_id, p.pay_ref_type, p.pay_ref_id, p.pay_type_id, p.pay_amount, pt.id, pt.name');
            $ci->db->join( TBL_PAY_TYPE . ' AS pt', 'pt.id = p.pay_type_id' );
            $q = $ci->db->get_where( TBL_PAY . ' AS p', $whr );
            $pay_results = $q->result_array(); 
            
        else :
            
            $pay_type = !empty( $args['pay_type'] ) ? $args['pay_type'] : $post['pay_type'];
            
            if( $pay_type ) :
                
                $pay_mode_ids = array();
                foreach($pay_type as $pay_type_id => $amt):
                    if( !empty( $amt ) ) :
                        $pay_mode_ids[] = $pay_type_id;
                    endif;
                endforeach; 

                $ci->db->select('pt.name');
                $ci->db->where_in('pt.id', $pay_mode_ids);
                $q = $ci->db->get_where( TBL_PAY_TYPE . ' AS pt', array('pt.status !=' => 2) );
                $pay_results = $q->result_array(); 
            
            endif;
            
        endif;
        
        $pay_mode_str = pay_mode_str($pay_results);
        
        $args['pay_mode_str'] = '<span style="font-size: 12px; padding-left: 10px;"><b>Mode:</b> '.$pay_mode_str.'</span>';
        
    endif;
    
    $head = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
             <html xmlns="http://www.w3.org/1999/xhtml">
                <head>
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                    <meta http-equiv="X-UA-Compatible" content="IE=9, Chrome=1" />
                    <title>Printing</title>
                    <link rel="stylesheet" href="'. BASE_URL .'assets/billing/fonts/Amudham-font.ttf" type="application/octet-stream" />
                    <style type="text/css">
                        .lbl{
                            font-weight:bold;
                            font-size: 15px;
                        }
                        
                        .sub-lbl {
                            font-size: 12px; 
                            color: #333;
                            font-weight: bold;
                            /*margin-top: -36px;*/
                            margin-top: 3px;
                        }

                        .linear-lbl {
                            font-size: 14px;
                            color: #333;
                        }

                    </style>
                </head>
            <body id="fullheight">';
    
    $foot = $args['html']. '</body></html>';
    
    $copy_line = '<table class="copy-line" width="'. WIDTH .'" style="margin-bottom: 20px; margin-top: -15px;"><tr><td width="'. WIDTH .'" style="border-bottom: 2px dashed #333;">&nbsp;</td></tr></table>';
            
    $header = $ci->load->view('templates/print/header', $args, TRUE);
    $footer = $ci->load->view('templates/print/footer', $args, TRUE);
    
	$printType = $args['printType'];
	
    $script = '<style type="text/css">.lang-tamil, .lang-tamil input {font-family : amudham !important;font-weight : bolder !important;font-size : 22px !important;letter-spacing: 1px;}</style>';
    $script .= '<script type="text/javascript">window.onload = new function(){';
    
    if( !IS_SHORT && !$printType) :
        
        //$script .= 'var aH = 740 /* 510 */ /* Page Half */,   cl = document.getElementsByClassName(\'copy-line\'),   pages = document.getElementsByClassName(\'page\'); if(pages.length > 1 ) { var mT = 0,   vary = 10,   pH = pages[0].offsetHeight,   btms = document.getElementsByClassName(\'auto-btm\');   var btmH = btms[0].offsetHeight; /*console.log("Paper(Half Size): "+aH+"\n Page Height: "+pH);*/  if( (pH+vary) <= aH || (pH-vary) <= aH ) { /* Fill to Half page */ pH = aH-pH <= vary ? pH+vary : pH;  mT = aH - pH; var aAdj = document.getElementsByClassName(\'auto-adj\'); for(var x=0; x< aAdj.length; x++) { var $e = aAdj[x];  $e.parentNode.removeChild($e); } }else { /* Make it as full page */ mT = (2*aH) - pH; }  mT = Math.floor(mT); for(var i = 0; i < btms.length; i++) { btms[i].style.marginTop = mT+\'px\';}  }  if(cl.length > 1){  var $e = cl[cl.length-1];  $e.parentNode.removeChild($e); }';
        $script .= 'var aH = 700 /* 510 */ /* Page Half */,  
                    cl = document.getElementsByClassName(\'copy-line\'), 
                    pages = document.getElementsByClassName(\'page\'),
                    stable = document.getElementById(\'subtable\');                    
                     
                    if(pages.length >= 1 ) { 
                        var mT = 0,
                            btms = document.getElementsByClassName(\'auto-btm\'),
                                vary = btms[0] ? btms[0].offsetHeight : 0,   
                                pH = pages[0].offsetHeight;

                        //console.log("Paper(Half Size): "+aH+"\n Page Height: "+pH+"\nVary Height: "+vary) ;

                        if( pH <= aH ) {
                            //console.log("Try to extend to Half page");
                            mT = aH-(pH+vary);

                            var $e = btms[btms.length-1];
                            if($e) {
                                $e.parentNode.removeChild($e);
                            }
                        }else{
                            var adjH = 0
                            ,   aAdj = document.getElementsByClassName(\'auto-adj\')
                            ,   tRws  = document.getElementsByClassName(\'tbl-row\');

                            for(var x=0; x< aAdj.length; x++) { 
                                adjH += aAdj[x].offsetHeight;
                            }
                            //console.log(tRws.length);
                            if( pH-(vary+adjH) <= aH && pages.length >= 2 && tRws.length <= 14 ) { 
                               //console.log("Is it possible to Fit to Half page");
                                var noCpy = pages[1].getElementsByClassName(\'no-copy\');
                                mT = -vary;

                                while( aAdj[0] ) {
                                    var $e = aAdj[0];
                                    $e.parentNode.removeChild($e);
                                }

                                while( noCpy[0] ) {
                                    var $e = noCpy[0];
                                    $e.parentNode.removeChild($e);
                                }

                                var $e = btms[btms.length-1];
                                $e.parentNode.removeChild($e);

                            }else {
                                //console.log("Make it as full page");
                                ';
                                
                                $copy_line .= '<style type="text/css">.copy-line {margin-bottom: 60px !important; }</style>';
                                
                                $script .='
                                mT = (2*aH) - pH; 
                                
                                if(document.getElementById(\'subhht\')) {
                                    var tbl1 = document.getElementById(\'tdhgt\').offsetHeight;
                                    var tbl2 = document.getElementById(\'subhht\').offsetHeight;
                                    var bodyheight = document.getElementById(\'fullheight\').offsetHeight;
                                    var mainheight = bodyheight - tbl2;
                                    var tbd = pH - tbl2;
                                    tbd -= 20;
                                    if(tbd < tbl2) {
                                        stable.style.minHeight = tbd+\'px\';
                                    }
                               }   
                                    
                                
                            }
                        }

                        mT = Math.floor(mT); 
                        //console.log("Margin Top: "+mT+"px");
                        for(var i = 0; i < btms.length; i++) {
                            btms[i].style.marginTop = mT+\'px\';
                        }
                    } 

                    if(cl.length > 1){ 
                        var $e = cl[cl.length-1]; 
                        $e.parentNode.removeChild($e);
                    }';
					
	elseif($args['type'] == '2') :
                  	$script .= 'var aH = 699 /* 510 */ /* Page Half */,  
                    cl = document.getElementsByClassName(\'copy-line\'), 
                    pages = document.getElementsByClassName(\'page\'),
                    stable = document.getElementById(\'subtable\');                    
                    
                    if(pages.length >= 1 ) { 
                        var mT = 0,
                            btms = document.getElementsByClassName(\'auto-btm\'),
                                vary = btms[0] ? btms[0].offsetHeight : 0,   
                                pH = pages[0].offsetHeight;
                                ';
                                
                                $copy_line .= '<style type="text/css">.copy-line {margin-bottom: 70px !important; }</style>';
                                
                                $script .='
                                mT = (2*aH) - pH;
                        

                        mT = Math.floor(mT); 
                        //console.log("Margin Top: "+mT+"px");
                        for(var i = 0; i < btms.length; i++) {
                            btms[i].style.marginTop = mT+\'px\';
                        }
                    } 

                    if(cl.length > 1){ 
                        var $e = cl[cl.length-1]; 
                        $e.parentNode.removeChild($e);
                    }';
    else :
        $script .= 'var aH = 650 /* 510 */ /* Page Half */,  
                    cl = document.getElementsByClassName(\'copy-line\'), 
                    pages = document.getElementsByClassName(\'page\'),
                    stable = document.getElementById(\'subtable\');                    
                    
                    if(pages.length >= 1 ) { 
                        var mT = 0,
                            btms = document.getElementsByClassName(\'auto-btm\'),
                                vary = btms[0] ? btms[0].offsetHeight : 0,   
                                pH = pages[0].offsetHeight;
                                ';
                                
                                $copy_line .= '<style type="text/css">.copy-line {margin-bottom: 70px !important; }</style>';
                                
                                $script .='
                                mT = (2*aH) - pH;
                        

                        mT = Math.floor(mT); 
                        //console.log("Margin Top: "+mT+"px");
                        for(var i = 0; i < btms.length; i++) {
                            btms[i].style.marginTop = mT+\'px\';
                        }
                    } 

                    if(cl.length > 1){ 
                        var $e = cl[cl.length-1]; 
                        $e.parentNode.removeChild($e);
                    }';
    endif; // !IS_SHORT
    
    $script .= '};</script>';
    
    
    if( $is_html ) :
        
        $script .= '<script type="text/javascript">';
        $script .= file_get_contents( BASE_URL . 'assets/js/library/jquery-1.11.1.min.js' );
        
        $seg = $ci->uri->segments;
        
        $script .= 'var controller = \''. $seg[1] .'\';';
        
        $script .= '$(document).on("ready", function(){ filtered_columns(); });';
        
        $script .= 'function filtered_columns() {
                        if( controller.substring(controller.length-7, controller.length) == "_report" ) {
                            var html =  \'\';
                            var data_th_name = \'\';

                            if(controller == \'donation_report\' && $(\'.hidden_print_pledge\').val() !== undefined && $(\'.hidden_print_pledge\').val() == 1) {
                                $(\'#filterTable>thead>tr>th\').not(\':first\').each(function(index,element){
                                    var $this =  $(this);
                                    field_name = $(this).text().replace(/ /g , "_");
                                    var field_name = field_name.replace(\'_/_\', \'_\');
                                    field_name = field_name.replace(\'(\', \'_\');
                                    field_name = field_name.replace(\')\', \'\');
                                    field_name = field_name.replace(\'_&_\', \'_\');
                                    $(this).addClass(field_name.replace(/_+$/, \'\'));
                                    $(this).parents().find(\'.filterTable tbody tr td.expand_container table thead tr th\').removeClass();

                                    var checked = \'\';
                                    if($(\'.hidden_print\').val() == 1) {
                                        $(\'.hidden_filter_array\').each(function() {
                                            if($(this).val() == $this.text()) {
                                                checked = \'checked \';
                                            }
                                        });
                                    } else {
                                        if(index < 7 ||  $(this).text() == \'Amount\') {
                                            checked = \'checked \';
                                        } 
                                    }

                                    html +=  \'<div class="col-md-2" style="margin: 1%;">\';
                                    html +=  \'<input type="hidden" name="filter_columns[]" value="\' + field_name.replace(/_+$/, \'\') + \'" />\';
                                    html +=  \'<input type="checkbox" class="check" value="\' + $(this).text() + \'" name="\' + field_name.replace(/_+$/, \'\') + \'"\' + checked + \'/>&nbsp;\' + $(this).text();
                                    html += \'</div>\';
                                    data_th_name += field_name.replace(/_+$/, \'\') + \',\';
                               });
                            }            
                            else {

                                $(\'.filterTable:first thead tr th\').not(\':first\').each(function(index,element){
                                    var $this =  $(this);
                                    field_name = $(this).text().replace(/ /g , "_");
                                    var field_name = field_name.replace(\'_/_\', \'_\');
                                    field_name = field_name.replace(\'(\', \'_\');
                                    field_name = field_name.replace(\')\', \'\');
                                    field_name = field_name.replace(\'_&_\', \'_\');
                                    if(field_name != \'S.No\') {
                                        $(this).addClass(field_name.replace(/_+$/, \'\'));
                                    }
                                    $(this).parents().find(\'.filterTable tbody tr td.expand_container table thead tr th\').removeClass();

                                    var checked = \'\';
                                    if($(\'.hidden_print\').val() == 1) {
                                        $(\'.hidden_filter_array\').each(function() {
                                            if($(this).val() == $this.text()) {
                                                checked = \'checked \';
                                            }
                                        });
                                    } else {
                                        if(index < 7 ||  $(this).text() == \'Amount\') {
                                            checked = \'checked \';
                                        } 
                                    }
                                    if(field_name != \'S.No\') {
                                        html +=  \'<div class="col-md-2" style="margin: 1%;">\';
                                        html +=  \'<input type="hidden" name="filter_columns[]" value="\' + field_name.replace(/_+$/, \'\') + \'" />\';
                                        html +=  \'<input type="checkbox" class="check" value="\' + $(this).text() + \'" name="\' + field_name.replace(/_+$/, \'\') + \'"\' + checked + \'/>&nbsp;\' + $(this).text();
                                        html += \'</div>\';
                                    }
                                    data_th_name += field_name.replace(/_+$/, \'\') + \',\';
                                })

                            }

                            $(\'.filterTable\').attr(\'data_th_name\',data_th_name);
                            $(\'.filterTable:first tbody tr\').not(\'.remove_container\').each(function(index,element){
                                var th_name = $(\'.filterTable\').attr(\'data_th_name\').split(\',\');
                                var field_name = \'\';
                                for(var i = 0; i < th_name.length; i++) {
                                    field_name = th_name[i].replace(/ /g , "_")
                                    field_name = field_name.replace(\'_/_\', \'_\');
                                    field_name = field_name.replace(\'(\', \'_\');
                                    field_name = field_name.replace(\')\', \'\');
                                    field_name = field_name.replace(\'_&_\', \'_\');
                                    $(this).not(\'.subTable\').find(\'td\').not(\':first\').eq(i).addClass(field_name.replace(/_+$/, \'\'));
                                }

                            })

                            $(\'.grpChkBox\').html(html);
                            
                            $(".grpChkBox input[type=\'checkbox\']").not(\':checked\').each(function() {
                                var colToHide = $("#filterTable").find("." + $(this).attr("name"));
                                $(colToHide).hide();
                                if($(this).attr("name") == \'Amount\') {
                                    $(\'.filterTable:first tfoot\').hide();
                                }
                                 if(controller == \'prasadam_sale_report\') {
        
                                    if($(this).attr("name") != \'Quantity\') {
                                        var $checked_length = ($(".grpChkBox input[type=\'checkbox\']:checked").length - 1);
                                    } else {
                                        var $checked_length = $(".grpChkBox input[type=\'checkbox\']:checked").length;
                                        $(\'.filterTable:first tfoot tr td:nth-child(2)\').hide();
                                    }
                                } else { 
                                    var $checked_length = $(".grpChkBox input[type=\'checkbox\']:checked").length;
                                }
                                $(\'.filterTable:first tfoot tr td:first\').attr(\'colspan\',$checked_length);
                            });
                            
                        }

                     }';
    
        $script .= '</script>';
        
        $html = $header. $args['raw_html'] . $footer;
        $html = $head. $html . $script . $foot;
        
        file_put_contents( $path . '.html' , $html );
    else :    
        // Billing Receipts
        
        $mail_body = '';
        if( $args['type'] == '2' || $args['type'] == '5' ) :
            // Kattalai Archanai || Archanai
            
            if( IS_SHORT ) :
                // Receipt Message
                $q = $ci->db->get_where(TBL_BILL_SETT, array('slug' => 'rec_msg', 'status' => '1'));
                $args['data']['rec_msg'] = $q->row_array()['value'];
            endif;
            
            $html = '';
            $actual_args = $args;
            $s_no = 0;
            $len = count($actual_args['data']['items']);
            $actual_args['len'] = $len;
            $fruitgrpExists = 0;
            $coconutgrpExists = 0;
            #error_log(print_r($actual_args['data']['items'],1));die;
            if ($len > 0) :
                foreach( $actual_args['data']['items'] as $k => $item ) :
                    $html = '';
                    if( $actual_args['type'] == '2' ) :
                        // Kattalai Archanai
                        $args['amount']         = $actual_args['amount'][$k];    
                        $args['data']['date']   = $actual_args['data']['date'][$k];
                        $args['data']['day']    = $actual_args['data']['day'][$k];
                        $args['data']['days']   = $actual_args['data']['days'][$k];
                        $args['data']['items']  = $actual_args['data']['items'][$k];
                    else :
                        // Archanai
                        $is_group = count( $item )  > 1 ? TRUE : FALSE;
                    
                        //$prefix = $is_group ? '' : $item[0]['cat_prefix'];
                        
                        if( $is_group ) :
                            // Group
                            $rec_no = array(
                                $item[0]['rec_no'], // First of First Rec No
                                $item[count($item)-1]['rec_no'], // Last of Last Rec No
                            );
                            
                            $rec_no = $rec_no[0][0] != $rec_no[1][count($rec_no[1])-1] ? $rec_no[0][0] . '-' . $rec_no[1][count($rec_no[1])-1] : $rec_no[0][0];
                            
                        else :
                            
                            $rec_no = $item[0]['rec_no'];
                            sort($rec_no);
                            $rec_no = $rec_no[0] != $rec_no[count($rec_no)-1] ? $rec_no[0] . '-' . $rec_no[count($rec_no)-1] : $rec_no[0];
                        
                        endif;
                            
                        $args['is_group']   = $is_group;
                        $args['rec_no']     = $rec_no;
                        $args['total_qty']  = $item[0]['total_qty'];

                        $args['data']['items']  = $item;
                        
                        
                        // update Header Total Qty
                        $header = $ci->load->view('templates/print/header', $args, TRUE);
                        
                    endif;

                    $html .= $header;
                    
                   
                    $html .= $ci->load->view('templates/print/format-'.$type, $args, TRUE);


                    //if( $item[0]['is_enable_footer'] && $pages+1 ==  $len ) :
					/*
                     if( $item[0]['is_enable_footer'] ) :

                        // Include Footer
                        $args['incl_footer'] = TRUE;
                        $args['amount']   = $extra['total_price'];

                        $html .= '</td></tr>
                            <tr height="5"></tr>  
                            <tr>
                                <td colspan="4"><div style="text-align: center; width: 210px; padding-left: 25px;"><img style="max-width: 100%;" src="'.BASE_URL.'assets/billing/images/break.png" /></div></td>
                            </tr></table>'.$header;
                        $html .= $ci->load->view('templates/print/format-'.$type, $args, TRUE);
                        //$html .= $footer;

                        $args['incl_footer'] = FALSE;
                    endif; 
					*/
                    $html .= $footer;
                    //$html .= ( ++$s_no < $len ? '<table style="width: 100%" data-null=""><tr><td width="100" style="border-bottom: 3px dotted #eee;">&nbsp;</td></tr></table>' : ( $args['is_copy'] ? $copy_line : '' ) );
                    $html .= $args['is_copy'] ? $copy_line : '';
                    ++$pages;

                    $mail_body = $html;
                    if( $args['is_copy'] ) :
                        $html .= set_copy($html);
                    endif;

                    $html = $head. $html . $script . $foot;
                    //echo $html; die;
                    file_put_contents( $path.'-'.$pages.'.html', $html );
                    
                    /** Seperate (Page) Footer for "Fruit Archanai" and "Coconut Archanai" - Start **/
                    /*
					 if( $is_group ) :
                        $fruitgrpExists = ($item[0]['cat']['category_name'] == 'Fruit Archanai') ? 1 : 0;
                        $coconutgrpExists = ($item[0]['cat']['category_name'] == 'Coconut Archanai') ? 1 : 0;
                        if($item[0]['cat']['category_name'] == 'Fruit Archanai' || $item[0]['cat']['category_name'] == 'Coconut Archanai') {
                            $html = '';
                            $type = 9;
                            if( $item[0]['is_enable_footer'] ) :

                                // Include Footer
                                $args['incl_footer'] = TRUE;
                                $args['amount']   = $item[0]['total_price'];

                                $html .= $header;
                                $html .= $ci->load->view('templates/print/format-'.$type, $args, TRUE);
                                //$html .= $footer;

                                $args['incl_footer'] = FALSE;
                            endif;

                            //$html .= $footer;
                            
                            ++$pages;
                            
                            //$mail_body = $html;
                            
                            $html = $head. $html . $script . $foot;
                            
                            file_put_contents( $path.'-'.$pages.'.html', $html );
                            
                        }
                        
                    endif;
                    */
                    /** Seperate (Page) Footer for "Fruit Archanai" and "Coconut Archanai" - End **/
                    
                endforeach;
                
                if($args['type'] != '2') :
                #if($fruitgrpExists) :
                    /*** Footer - Fruit Archanai ***/
					
                    $footer_rec_no = array();
                    $totalAmount = 0;
                    $totalQty = 0;
                    $footergroup = 0;
                    $disfooter = 0;
                    $isGroup = 0;
                    foreach( $actual_args['data']['items'] as $l => $fitem ) :
                        $Grp = (count($fitem) > 1) ? TRUE : FALSE;
                        //echo "<pre>";print_r($fitem);exit;
                        //if($fitem[0]['cat']['category_name'] == 'Fruit Archanai') {
                            $rec_no1 = array(
                                $fitem[0]['rec_no'], // First of First Rec No
                                $fitem[count($fitem)-1]['rec_no'], // Last of Last Rec No
                            );
                            if($Grp) {
                                $rec_no1 = $rec_no1[0][0] != $rec_no1[1][count($rec_no1[1])-1] ? $rec_no1[0][0] . '-' . $rec_no1[1][count($rec_no1[1])-1] : $rec_no1[0][0];
                                $isGroup = 1;
                            } else {
                                $rec_no1 = $rec_no1[0][0] != $rec_no1[1][count($rec_no1[1])-1] ? $rec_no1[0][0] . '-' . $rec_no1[1][count($rec_no1[1])-1] : $rec_no1[0][0];
                                $isGroup = 0;
                            }
                            $footer_rec_no[] = $rec_no1;
                            $totalAmount += $fitem[0]['total_price'];
                            $totalQty += $fitem[0]['total_qty'];
                            $footergroup += (count( $fitem ) > 1 ? 1 : 0);
							
							if($fitem[0]['is_enable_footer'] == 1){
                            	$disfooter = 1;
							}
                       // }
                    endforeach;
					
                   # $fruitgrpExists = 0;
				                     
                    if($disfooter == 1) :
                        $type = 9;
                        
                        if($isGroup) {
                            $args['rec_no']     = $footer_rec_no;
                        } else {
                            $first_ele = reset($footer_rec_no);
                            $last_ele = end($footer_rec_no);
                            $args['rec_no']     = $first_ele . '-' . $last_ele;
                        }
                        $args['total_qty']  = $totalQty;
                        $args['amount']     =  $totalAmount;
                        
                        $html = '';
                        $header = $ci->load->view('templates/print/header', $args, TRUE);
                        $html .= $header;
                        $html .= $ci->load->view('templates/print/format-'.$type, $args, TRUE);
                        $args['incl_footer'] = FALSE;
                        ++$pages;
                        $html = $head. $html . $script . $foot;
                        file_put_contents( $path.'-'.$pages.'.html', $html );                        
                    endif;
					
						/*** Footer - Fruit Archanai ***/
                #endif;
                
                #if($coconutgrpExists) :
                    /*** Footer - Coconut Archanai ***/
                    /*
					$cfooter_rec_no = array();
                    $ctotalAmount = 0;
                    $ctotalQty = 0;
                    $cfootergroup = 0;
                    $cdisfooter = 0;
                    $iscGroup = 0;
                    foreach( $actual_args['data']['items'] as $m => $citem ) :
                        $cGrp = (count($citem) > 1) ? TRUE : FALSE;
                        if($citem[0]['cat']['category_name'] == 'Coconut Archanai') {
                            $crec_no1 = array(
                                $citem[0]['rec_no'], // First of First Rec No
                                $citem[count($citem)-1]['rec_no'], // Last of Last Rec No
                            );
                            if($cGrp) {
                                $crec_no1 = $rec_no1[0][0] != $crec_no1[1][count($crec_no1[1])-1] ? $crec_no1[0][0] . '-' . $crec_no1[1][count($crec_no1[1])-1] : $crec_no1[0][0];
                                $iscGroup = 1;
                            } else {
                                $crec_no1 = $crec_no1[0][0] != $crec_no1[1][count($crec_no1[1])-1] ? $crec_no1[0][0] . '-' . $crec_no1[1][count($crec_no1[1])-1] : $crec_no1[0][0];
                                $iscGroup = 0;
                            }
                            $cfooter_rec_no[] = $crec_no1;
                            $ctotalAmount += $citem[0]['total_price'];
                            $ctotalQty += $citem[0]['total_qty'];
                            $cfooterInc += 1;
                            $cfootergroup += (count( $item ) > 1 ? 1 : 0);
                            $cdisfooter = 1;
                        }
                    endforeach;
                    #$coconutgrpExists =  0; 
                    
                    if($cdisfooter == 1) :
                        $type = 9;
                        
                        if($iscGroup) {
                            $args['rec_no']     = $cfooter_rec_no;
                        } else {
                            $first_ele = reset($cfooter_rec_no);
                            $last_ele = end($cfooter_rec_no);
                            $args['rec_no']     = $first_ele . '-' . $last_ele;
                        }
                        $args['total_qty']  = $ctotalQty;
                        $args['amount']     =  $ctotalAmount;
                        
                        $html = '';
                        $header = $ci->load->view('templates/print/header', $args, TRUE);
                        $html .= $header;
                        $html .= $ci->load->view('templates/print/format-'.$type, $args, TRUE);
                        $args['incl_footer'] = FALSE;
                        ++$pages;
                        $html = $head. $html . $script . $foot;
                        file_put_contents( $path.'-'.$pages.'.html', $html );                        
                    endif;
					*/
					/*** Footer - Coconut Archanai ***/
                #endif;
                endif;
            else :
                $html = '';
                if( $actual_args['type'] == '2' ) :
                    // Kattalai Archanai
                    $args['amount']         = $actual_args['amount'][0];    
                    $args['data']['date']   = $actual_args['data']['date'][0];
                    $args['data']['day']    = $actual_args['data']['day'][0];
                    $args['data']['days']   = $actual_args['data']['days'][0];
                    $args['data']['items']  = $actual_args['data']['items'][0];
                endif;
                
                $html .= $header;
                    
                    
                    $html .= $ci->load->view('templates/print/format-'.$type, $args, TRUE);
                    $html .= $footer;
                    $html .= $args['is_copy'] ? $copy_line : '';
                    ++$pages;

                    $mail_body = $html;
                    if( $args['is_copy'] ) :
                        $html .= set_copy($html);
                    endif;

                    $html = $head. $html . $script . $foot;
                    file_put_contents( $path.'-'.$pages.'.html', $html );
            endif;
            
        else :
            //for($i = 0; $i<2; $i++) :
            $content= $ci->load->view('templates/print/format-'.$type, $args, TRUE);
            $html .= $header.$content.$footer.($args['is_copy'] ? $copy_line : '' );
            ++$pages;

            $mail_body = $html;
            if( $args['is_copy'] ) :
                $html .= set_copy($html);
            endif;

            $html = $head. $html . $script . $foot;
            //echo $html; die;
            file_put_contents( $path . '-'.$pages.'.html' , $html );
            
            //endfor;
        endif;
        
        /*
         * Send Acknowledgement SMS & Mail
         */
        if( $args['type'] != '5' ) :
            
           send_ack( !empty( $actual_args ) ? $actual_args : $args, array( 'head' => $head, 'body' => $mail_body, 'foot' => $foot ));
        
        endif;
        
    endif;    
    
    
   /* if( $args['is_copy'] ) :
        $copy_script .= 'var c = document.getElementsByClassName(\'copy-type\');for(var i='.$pages.'; i<c.length;i++){var obj = c[i];obj.innerHTML = \'Official Copy\'; }';
        $copy_script .= '}</script>';
        
        $html .= $html.$copy_script;
    
        /*$nxt_page = $pages;
        for( $i = 1; $i <= $pages; $i++ ) :
            // Make Duplicate
            //copy( $path . '-'.$page.'.html', $path . '-'. (++$nxt_page) .'.html' );
            file_put_contents( $path . '-'. (++$nxt_page) .'.html', $copy_html[$i]);//.$copy_script );
            
        endfor;
        
        $pages = $pages*2;*/
    /*endif;*/
    
    /*if( $pages > 1 ) :
        //$copy_script .= 'var p = document.getElementsByClassName(\'page\'), doc = document.body.innerHTML, $parent = window.opener, $pStatus = $parent.document.getElementById("print-sno"); /*for(var i=0; i<p.length;i++){ /** Print Page **/ /*var obj = p[i]; document.body.innerHTML = obj.innerHTML; window.print(); if( $pStatus.length > 0 ){$pStatus.innerHTML = 1; }*/ /*document.body.innerHTML = doc; }';
      /*  $copy_script .= 'var p = document.getElementsByClassName(\'page\'), doc = document.body.innerHTML, $parent = window.opener, $pStatus = $parent.document.getElementById("print-sno"); /** Print Page **/ /*var i = 0;  function setPrint() {
                if( i < p.length ) {
                    // Next Print
                    var obj = p[i]; 
                    document.body.innerHTML = obj.innerHTML; 
                    window.print(); 
                    if( $pStatus.length > 0 ){
                        $pStatus.innerHTML = i; 
                    } 
                    document.body.innerHTML = doc; 
                    
                }else {
                    alert(\'All are Printed\');
                }
            }
            
            var afterPrint = function() {
                    /*var d = new Date();
                    console.log(\'Printed!\'+(d.getHours()+\':\'+d.getMinutes()+\':\'+d.getSeconds()+\':\'+d.getMilliseconds()));*/
        
                    
      /*              setPrint();
                    ++i;
                }
                
                if( window.matchMedia ) {
                    console.log(window.matchMedia);
                    
                    var mqList = window.matchMedia(\'print\');
                    console.log(mqList);
                    
                    mqList.addListener(function(a){
                        if(a.matches) {
                           // beforePrint();
                        }else {
                            afterPrint();
                        }
                    })
                }
                
                //window.onbeforeprint = beforePrint;
                window.onafterprint  = afterPrint;';
    //endif;
       
    $copy_script .= '}</script>';
       
    $html .= $html.$copy_script;*/
    
    //echo $html; die;
    //echo "<pre>Data: "; print_r($args); die;
    //$path .= '.html';
    
    //file_put_contents( $path, $html );
    //$path .= '`'.$pages;
    
    $str = 'NOT';
    if(file_exists( TMP_PRINT_DIR . 'flag.txt' ) ) :
        $lines = file( TMP_PRINT_DIR . 'flag.txt' );
        foreach( $lines as $k => $line ) :
            preg_match_all('/^'. REMOTE_ADDR .'(.*?)/' , $line, $mtchs);
            if( $mtchs[0] ) :
                $str = trim($line);
                break;
            endif;
        endforeach;
    endif;    
                
    $ci->session->set_flashdata( REMOTE_ADDR . '_flag', $str );
    
    return $path;
    
}


function tamil($value = '', $style = 'border: none; font-weight: bolder; font-size: 18px;', $attr = 'readonly' ) {
    $value = strpos( $value, '&quot;' ) ? $value : htmlspecialchars($value);
    return '<input type="text" value="'. $value .'" '. $attr .' style="font-family: amudham; '. $style .'">';
}

function get_alt_server($group = TRUE, $is_all = FALSE) {
    $ci = get_ci_instance();
    $ci->db->where_in('slug', array('alt_url', 'alt_host', 'alt_user', 'alt_pass', 'alt_db', 'server_down'));
    $q = $ci->db->get_where( TBL_BILL_SETT, $is_all ? array( 'status !=' => '2' ) : array( 'status' => 1)  );
    $results = $q->result_array();
    
    if( $group ) :
        // Set slug as "key"
        $return = array();
        foreach( $results as $k => $res ) :
            $return[$res['slug']] = $res;
        endforeach;

        return $return;
    else :
        return $results;
    endif;
}

function set_user_data($user) {
    $ci = get_ci_instance();
    $q = $ci->db->get_where( TBL_SETTINGS_DESIGN );
    $desgn_settings = $q->row_array();
    
    $gen_settings = get_general_setting();
    $alt_server   = get_alt_server();  
    
    $userdata = array(
        'role' => $user->role,
        'user_id' => $user->id,
        'name' => $user->name,
        'log_type' => $user->log_type,
        'is_kiosk' => !empty($user->is_kiosk) ? $user->is_kiosk : FALSE,
        'keyboard_clr' => $desgn_settings['keyboard_color'],
        'numpad'       => $gen_settings->num_pad,
        'category_on'  => $gen_settings->is_category,
        
        'alt_count'     => $alt_server['alt_count']['value'],
        'server_down'   => $alt_server['server_down']['value'],
    );
    
    if (!empty($ci->input->post('time_zone_offset'))) {
        $userdata['time_zone_offset'] = $ci->input->post('time_zone_offset');
    }
    $ci->session->set_userdata(TBL_PREFIX . 'user_logged_in', $userdata);
}

function get_user_data() {
    $ci = get_ci_instance();
    return $ci->session->userdata(TBL_PREFIX . 'user_logged_in');
}

function get_bill_list_url() {
    $uri = $_SERVER['REQUEST_URI'];
    $ci = get_ci_instance();
    $segs = $ci->uri->segments;
    $service_id = empty( stripos( $uri, '/add/') ) ? $segs[4] : $segs[3];
    return preg_replace('/\/(add|edit|view)\/(.*)/', '/index/'.$service_id, $uri);
}

function get_ci_instance() {
    $ci = &get_instance();
    return $ci;
}

function get_session_userdata() {
    $ci = get_ci_instance();
    return $ci->session->userdata(TBL_PREFIX . 'user_logged_in');
}

function unserialize_str($string) {
    return (!empty(unserialize($string))) ? unserialize($string) : array();
}

function check_permission() {
    $ci = get_ci_instance();
     
    if (empty($ci->session->userdata(TBL_PREFIX . 'user_logged_in' ))) {
        $ci->session->set_userdata('request_uri', current_url());
        redirect('admin', 'refresh');
    }

    // To access session data as global
    $ci->user_data = get_session_userdata();
    $user = $ci->user_model->get_by_id($ci->user_data['user_id']);
    $ci->permissions = unserialize_str($user->permissions);
    
    
    $main_controllers = array_keys($ci->permissions);
    
    $master_permissions = unserialize_str($user->master_permissions);
    $master_controllers = array_keys($master_permissions);
    $ci->master_menu = $ci->master_settings_model->permissions_by_controller($master_controllers);
    
    $inventory_permissions = unserialize_str($user->inventory_permissions);
    $inventory_controllers = array_keys($inventory_permissions);
    $ci->inventory_menu = $ci->inventory_settings_model->permissions_by_controller($inventory_controllers);
    
    $statue_permissions = unserialize_str($user->statue_permissions);
    $statue_controllers = array_keys($statue_permissions);
    $ci->statue_menu = $ci->inventory_settings_model->statue_permissions_by_controller($statue_controllers);
    
    $billing_controllers = $billing_permissions = array();
    if( !IS_KSK_ADMIN ) :
        $billing_permissions = unserialize_str($user->billing_permissions);
        $billing_controllers = array_keys($billing_permissions);
        $ci->billing_menu = $ci->service_settings_model->permissions_by_controller($billing_controllers);
    endif;
    
    $report_permissions = unserialize_str($user->report_permissions);
    
    $report_controllers = array_keys($report_permissions);
    
    $ci->report_menu = $ci->report_settings_model->permissions_by_controller($report_controllers);
    
    $all_permissions = array_merge($ci->permissions, $master_permissions, $inventory_permissions, $billing_permissions, $report_permissions, $statue_permissions );
    $all_controllers = array_merge($main_controllers, $master_controllers, $inventory_controllers, $billing_controllers, $report_controllers, $statue_controllers);
    $controller = $ci->router->fetch_class();
    $controller = $controller == 'kiosk' ? 'home' : ( $controller == 'billing_settings' ? 'sett' : $controller );
    $action = $ci->router->fetch_method();
    
    $ci->permission = array();
    if ($ci->user_data['role'] == 3) {
        // To set custom permission dynamically for super admin
        $ci->permission = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    }
    else if (in_array($controller, $all_controllers)) {
        $ci->permission = $all_permissions[$controller];
    }
    /*else if($action != 'logout'){
        show_403_error();
    }*/
    //echo "<pre>Data: "; print_r($ci->permission); die;

    
    switch($action) {
        case 'index':
            if (!in_array(1, $ci->permission)) {
                show_403_error();
            }
            break;
        
        case 'view':
            if (!in_array(1, $ci->permission)) {
                show_403_error();
            }
            break;
        
        case 'add':
            if (!in_array(2, $ci->permission)) {
                show_403_error();
            }
            break;
        
        case 'edit':
            if (!in_array(3, $ci->permission)) {
                show_403_error();
            }
            break;
        
        case 'delete':
            if (!in_array(4, $ci->permission)) {
                show_403_error();
            }
            break;
        
        case 'pdf':
            if (!in_array(5, $ci->permission)) {
                show_403_error();
            }
            break;
        
        default:
            break;
    }
    
    return $all_permissions;
}

function get_page_title() {
    $ci = get_ci_instance();
    $action = $ci->router->fetch_method();
    $page_title = ucfirst($ci->router->fetch_class());
    switch($action) {
        case 'view':
            $page_title .= ' ' . ucfirst($action);
            break;
        
        case 'add':
            $page_title .= ' ' . ucfirst($action);
            break;
        
        case 'edit':
            $page_title .= ' ' . ucfirst($action);
            break;
        
        default:
            break;
    }
    
    return $page_title;
}

function css_url() {
    $ci = get_ci_instance();
    return $ci->config->item('css_url');
}

function js_url() {
    $ci = get_ci_instance();
    return $ci->config->item('js_url');
}

function images_url($image_name = '', $folder_path = '') {
    $ci = get_ci_instance();
    $images_url = $ci->config->item('images_url');
    if (!empty($image_name)) {
        $file_path = (empty($folder_path)) ? FCPATH . IMG_FOLDER_PATH . $image_name : $folder_path . $image_name;
        if (file_exists($file_path)) {
            $images_url .= $image_name;
        }
        else {
            $images_url .= NO_IMG;
        }
    }
    
    return $images_url;
}

function get_header_data() {
    $ci = get_ci_instance();
    $data = array();
    $data['page_title'] = get_page_title();
    $data['current_controller'] = $ci->router->fetch_class();
    $data['current_method'] = $ci->router->fetch_method();
    #print_r($data);
    return $data;
}

function current_date() {
    return date('d-m-Y');
}

function text($text = '', $empty = 'N/A') {
    return (!empty($text)) ? trim($text) : $empty;
}

function text_date($date = '', $empty = 'N/A') {
    return (!empty($date)) ? date('d-m-Y', strtotime($date)) : $empty;
}

function text_amount($amt = 0, $empty = '0.00') {
    return (!empty($amt)) ? number_format($amt, 2, '.', '') : $empty;
}

function text_limit($text, $link = '', $limit = 50) {
    if (empty($text)) 
        $text = 'N/A';
    else if(strlen($text) > $limit){
        $link = ($link != '') ? $link: '#';
        $text = substr($text, 0, $limit) . "..&nbsp;<a href='$link' title='Read More' style='color: #428bca;'>Read More</a>";
    }
    
    return trim($text);
}

function get_url_key($url_key) {
    $url_key = strtolower(trim(trim($url_key, '-')));
    
    $patterns = array();
    $patterns[0] = '/( (\(|\/|\[|\{|&|\*)?)/';
    $patterns[1] = '/[()\'"\[\]{},*&]|[^a-z0-9\-]/';
    $patterns[2] = '/-+/';
    $replacements = array();
    $replacements[2] = '-';
    $replacements[1] = '';
    $replacements[0] = '-';
    $url_key = preg_replace($patterns, $replacements, $url_key);
    return $url_key;
}

function download_file($file_path = '') {
    if (!empty($file_path)) {
        $file_path_parts = explode('/', $file_path);
        $file_name = array_pop($file_path_parts);
        $file_name = urldecode($file_name);
        
        array_push($file_path_parts, $file_name);
        $file_path = implode('/', $file_path_parts);
        
        ob_clean();
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file_name . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file_path));
        readfile($file_path);
    }
}

function image_extensions() {   
    return array('jpeg', 'png', 'jpg', 'gif', 'ico');
}

function recursive_conversion($num, $tri) {
    $ones = array('', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine', ' Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen');
    $tens = array('', '', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety');
    $triplets = array('', ' Thousand', ' Million', ' Billion', ' Trillion', ' Quadrillion', ' Quintillion', ' Sextillion', ' Septillion', ' Octillion', ' Nonillion');
    
    // chunk the number, ...rxyy
    $r = (int) ($num / 1000);
    $x = ($num / 100) % 10;
    $y = $num % 100;
    
    // init the output string 
    $str = '';
    
    // do hundreds 
    if ($x > 0) 
        $str = $ones[$x] . ' Hundred ';   
    
    // do ones and tens 
    if ($y < 20) 
        $str .= $ones[$y];
    else
        $str .= $tens[(int) ($y / 10)] . $ones[$y % 10];
    
    
    // add triplet modifier only if there // is some output to be modified... 
    if ($str != '')
        $str .= $triplets[$tri];
    
    // continue recursing?
    if ($r > 0)
        return recursive_conversion($r, $tri + 1) . $str;
    else
        return $str;
}
    
// returns the number as an anglicized string
function convert_amount_to_word($num) {
    $num = (float) $num;
    if ($num == 0)
        return 'zero';
    
    $amounts = explode('.', $num);
    $amount_in_words = recursive_conversion($amounts[0], 0);
    $amount_in_words .= ' Dollars';
    if (!empty($amounts[1])) {
        $amount_in_words .= ' and';
        $amount_in_words .= recursive_conversion($amounts[1], 0);
        $amount_in_words .= ' Cents';
    }
    
    return $amount_in_words . ' Only';
}

function convert_amount_to_word_rupees($num) {
    $num = (float) $num;
    if ($num == 0)
        return 'zero';
    
    $amounts = explode('.', $num);
    $amount_in_words = recursive_conversion($amounts[0], 0);
    $amount_in_words .= ' Rupees';
    if (!empty($amounts[1])) {
        $amount_in_words .= ' and';
        $amount_in_words .= recursive_conversion($amounts[1], 0);
        $amount_in_words .= ' Paise';
    }
    
    return $amount_in_words . ' Only';
}

function breadcrumb_links() {
    $breadcrumb_items = array();
    $url_items = array();
    $url_items = array_filter(explode('/', str_replace(base_url(), '', current_url())));
    $link = '';
    foreach($url_items as $key => $value) {
        if ((is_numeric($value)) || ($value == 'index') || ($value == 'home'))
            continue;
        
        $link .= $value;
        $value_arr = explode('_', $value);
        
        $value_arr = array_map(function($word) {
                return ucfirst($word);
            },
            $value_arr
        );
        
        $value = implode(' ', $value_arr);
        $menu = array(
            'menu_name' => $value,
            'link' => base_url() . $link
        );
        
        array_push($breadcrumb_items, $menu);
 
        $link .= '/';
    }
    
    $breadcrumb_hmtl = '<ol class="breadcrumb">';
    $breadcrumb_hmtl .= '<li><a href="' . base_url() . '"><i class="fa fa-home"></i> Home</a></li>';
    $total_link = count($breadcrumb_items);
    foreach($breadcrumb_items as $key => $value) {
        $con_name = $value['menu_name'];        
        if($value['menu_name'] == 'Billing Festival Function') {
            $con_name =  'Billing Panguni Uthiram';
        }        
        if($value['menu_name'] == 'Festival Function Report') {
            $con_name =  'Panguni Uthiram Report';
        }        
        if ($key != ($total_link - 1)) {
            $breadcrumb_hmtl .= '<li><a href="' . $value['link'] . '">' . $con_name . '</a></li>';
        }
        else {
            $breadcrumb_hmtl .= '<li class="active">' . $con_name . '</li>';
        }
    }
    $breadcrumb_hmtl .= '</ol>';
    
    return $breadcrumb_hmtl;
}

function get_basic_setting() {
    $ci = &get_instance();
    $ci->load->model('basic_settings_model', '', TRUE);
    return $ci->basic_settings_model->get_by_id();
}

function get_general_setting() {
    $ci = &get_instance();
    $ci->load->model('general_settings_model', '', TRUE);
    return $ci->general_settings_model->get_by_id();
}

function get_design_setting() {
    $ci = &get_instance();
    $ci->load->model('design_settings_model', '', TRUE);
    return $ci->design_settings_model->get_by_id();
}

function country_list() {
    $countries = array(
    'AF' => 'Afghanistan',
    'AX' => 'Aland Islands',
    'AL' => 'Albania',
    'DZ' => 'Algeria',
    "AS" => "American Samoa",
    "AD" => "Andorra",
    "AO" => "Angola",
    "AI" => "Anguilla",
    "AQ" => "Antarctica",
    "AG" => "Antigua and Barbuda",
    "AR" => "Argentina",
    "AM" => "Armenia",
    "AW" => "Aruba",
    "AU" => "Australia",
    "AT" => "Austria",
    "AZ" => "Azerbaijan",
    "BS" => "Bahamas",
    "BH" => "Bahrain",
    "BD" => "Bangladesh",
    "BB" => "Barbados",
    "BY" => "Belarus",
    "BE" => "Belgium",
    "BZ" => "Belize",
    "BJ" => "Benin",
    "BM" => "Bermuda",
    "BT" => "Bhutan",
    "BO" => "Bolivia",
    "BA" => "Bosnia and Herzegovina",
    "BW" => "Botswana",
    "BV" => "Bouvet Island",
    "BR" => "Brazil",
    "IO" => "British Indian Ocean Territory",
    "BN" => "Brunei Darussalam",
    "BG" => "Bulgaria",
    "BF" => "Burkina Faso",
    "BI" => "Burundi",
    "KH" => "Cambodia",
    "CM" => "Cameroon",
    "CA" => "Canada",
    "CV" => "Cape Verde",
    "KY" => "Cayman Islands",
    "CF" => "Central African Republic",
    "TD" => "Chad",
    "CL" => "Chile",
    "CN" => "China",
    "CX" => "Christmas Island",
    "CC" => "Cocos (Keeling) Islands",
    "CO" => "Colombia",
    "KM" => "Comoros",
    "CG" => "Congo",
    "CD" => "Congo, The Democratic Republic of The",
    "CK" => "Cook Islands",
    "CR" => "Costa Rica",
    "CI" => "Cote D'ivoire",
    "HR" => "Croatia",
    "CU" => "Cuba",
    "CY" => "Cyprus",
    "CZ" => "Czech Republic",
    "DK" => "Denmark",
    "DJ" => "Djibouti",
    "DM" => "Dominica",
    "DO" => "Dominican Republic",
    "EC" => "Ecuador",
    "EG" => "Egypt",
    "SV" => "El Salvador",
    "GQ" => "Equatorial Guinea",
    "ER" => "Eritrea",
    "EE" => "Estonia",
    "ET" => "Ethiopia",
    "FK" => "Falkland Islands (Malvinas)",
    "FO" => "Faroe Islands",
    "FJ" => "Fiji",
    "FI" => "Finland",
    "FR" => "France",
    "GF" => "French Guiana",
    "PF" => "French Polynesia",
    "TF" => "French Southern Territories",
    "GA" => "Gabon",
    "GM" => "Gambia",
    "GE" => "Georgia",
    "DE" => "Germany",
    "GH" => "Ghana",
    "GI" => "Gibraltar",
    "GR" => "Greece",
    "GL" => "Greenland",
    "GD" => "Grenada",
    "GP" => "Guadeloupe",
    "GU" => "Guam",
    "GT" => "Guatemala",
    "GG" => "Guernsey",
    "GN" => "Guinea",
    "GW" => "Guinea-bissau",
    "GY" => "Guyana",
    "HT" => "Haiti",
    "HM" => "Heard Island and Mcdonald Islands",
    "VA" => "Holy See (Vatican City State)",
    "HN" => "Honduras",
    "HK" => "Hong Kong",
    "HU" => "Hungary",
    "IS" => "Iceland",
    "IN" => "India",
    "ID" => "Indonesia",
    "IR" => "Iran, Islamic Republic of",
    "IQ" => "Iraq",
    "IE" => "Ireland",
    "IM" => "Isle of Man",
    "IL" => "Israel",
    "IT" => "Italy",
    "JM" => "Jamaica",
    "JP" => "Japan",
    "JE" => "Jersey",
    "JO" => "Jordan",
    "KZ" => "Kazakhstan",
    "KE" => "Kenya",
    "KI" => "Kiribati",
    "KP" => "Korea, Democratic People's Republic of",
    "KR" => "Korea, Republic of",
    "KW" => "Kuwait",
    "KG" => "Kyrgyzstan",
    "LA" => "Lao People's Democratic Republic",
    "LV" => "Latvia",
    "LB" => "Lebanon",
    "LS" => "Lesotho",
    "LR" => "Liberia",
    "LY" => "Libyan Arab Jamahiriya",
    "LI" => "Liechtenstein",
    "LT" => "Lithuania",
    "LU" => "Luxembourg",
    "MO" => "Macao",
    "MK" => "Macedonia, The Former Yugoslav Republic of",
    "MG" => "Madagascar",
    "MW" => "Malawi",
    "MY" => "Malaysia",
    "MV" => "Maldives",
    "ML" => "Mali",
    "MT" => "Malta",
    "MH" => "Marshall Islands",
    "MQ" => "Martinique",
    "MR" => "Mauritania",
    "MU" => "Mauritius",
    "YT" => "Mayotte",
    "MX" => "Mexico",
    "FM" => "Micronesia, Federated States of",
    "MD" => "Moldova, Republic of",
    "MC" => "Monaco",
    "MN" => "Mongolia",
    "ME" => "Montenegro",
    "MS" => "Montserrat",
    "MA" => "Morocco",
    "MZ" => "Mozambique",
    "MM" => "Myanmar",
    "NA" => "Namibia",
    "NR" => "Nauru",
    "NP" => "Nepal",
    "NL" => "Netherlands",
    "AN" => "Netherlands Antilles",
    "NC" => "New Caledonia",
    "NZ" => "New Zealand",
    "NI" => "Nicaragua",
    "NE" => "Niger",
    "NG" => "Nigeria",
    "NU" => "Niue",
    "NF" => "Norfolk Island",
    "MP" => "Northern Mariana Islands",
    "NO" => "Norway",
    "OM" => "Oman",
    "PK" => "Pakistan",
    "PW" => "Palau",
    "PS" => "Palestinian Territory, Occupied",
    "PA" => "Panama",
    "PG" => "Papua New Guinea",
    "PY" => "Paraguay",
    "PE" => "Peru",
    "PH" => "Philippines",
    "PN" => "Pitcairn",
    "PL" => "Poland",
    "PT" => "Portugal",
    "PR" => "Puerto Rico",
    "QA" => "Qatar",
    "RE" => "Reunion",
    "RO" => "Romania",
    "RU" => "Russian Federation",
    "RW" => "Rwanda",
    "SH" => "Saint Helena",
    "KN" => "Saint Kitts and Nevis",
    "LC" => "Saint Lucia",
    "PM" => "Saint Pierre and Miquelon",
    "VC" => "Saint Vincent and The Grenadines",
    "WS" => "Samoa",
    "SM" => "San Marino",
    "ST" => "Sao Tome and Principe",
    "SA" => "Saudi Arabia",
    "SN" => "Senegal",
    "RS" => "Serbia",
    "SC" => "Seychelles",
    "SL" => "Sierra Leone",
    "SG" => "Singapore",
    "SK" => "Slovakia",
    "SI" => "Slovenia",
    "SB" => "Solomon Islands",
    "SO" => "Somalia",
    "ZA" => "South Africa",
    "GS" => "South Georgia and The South Sandwich Islands",
    "ES" => "Spain",
    "LK" => "Sri Lanka",
    "SD" => "Sudan",
    "SR" => "Suriname",
    "SJ" => "Svalbard and Jan Mayen",
    "SZ" => "Swaziland",
    "SE" => "Sweden",
    "CH" => "Switzerland",
    "SY" => "Syrian Arab Republic",
    "TW" => "Taiwan, Province of China",
    "TJ" => "Tajikistan",
    "TZ" => "Tanzania, United Republic of",
    "TH" => "Thailand",
    "TL" => "Timor-leste",
    "TG" => "Togo",
    "TK" => "Tokelau",
    "TO" => "Tonga",
    "TT" => "Trinidad and Tobago",
    "TN" => "Tunisia",
    "TR" => "Turkey",
    "TM" => "Turkmenistan",
    "TC" => "Turks and Caicos Islands",
    "TV" => "Tuvalu",
    "UG" => "Uganda",
    "UA" => "Ukraine",
    "AE" => "United Arab Emirates",
    "GB" => "United Kingdom",
    "US" => "United States",
    "UM" => "United States Minor Outlying Islands",
    "UY" => "Uruguay",
    "UZ" => "Uzbekistan",
    "VU" => "Vanuatu",
    "VE" => "Venezuela",
    "VN" => "Viet Nam",
    "VG" => "Virgin Islands, British",
    "VI" => "Virgin Islands, U.S.",
    "WF" => "Wallis and Futuna",
    "EH" => "Western Sahara",
    "YE" => "Yemen",
    "ZM" => "Zambia",
    "ZW" => "Zimbabwe");
    return $countries;
}

function form_auto_generation_code($id, $prefix = '') {  
    $code = $prefix;
    $code .= ($id  > 999) ? $id :   sprintf('%03d', $id ) ;
    return $code;
}

function file_extensions() {   
    return array('pdf','odt','xls','xlsx','doc',
       'docx','jpeg', 'png', 'jpg', 'gif');
}

function filter_special_characters($file_name) {
    $filter_file_name = trim($file_name, '-');
    $filter_file_name = strtolower(trim($filter_file_name));
    $patterns = array();
    $patterns[0] = '/( (\(|\/|\[|\{|&|\*)?)/';
    $patterns[1] = '/[()\'"\[\]{},*&]|[^a-z0-9\-\.]/';
    $patterns[2] = '/-+/';
    $replacements = array();
    $replacements[2] = '-';
    $replacements[1] = '';
    $replacements[0] = '-';
    $filter_file_name = preg_replace($patterns, $replacements, $filter_file_name);
    return $filter_file_name;
}

function file_uploads($file_path = '', $temp_path = '') {
    if (!empty($file_path)) {
        $file_path_parts = explode('/', $file_path);
        $file_name = array_pop($file_path_parts);
        $file_name = urldecode($file_name);
        
        $image_name = filter_special_characters($file_name);
        array_push($file_path_parts, $image_name);
        $target_path = implode('/', $file_path_parts);
        move_uploaded_file($temp_path, $target_path);
        return $image_name;
    }
}

$uploaded_fields = array();
function uploads( $config = array() ) {
    $ci = get_ci_instance();
    global $uploaded_fields;
    $errors = 0;

    if( !empty( $config['field'] ) ) :
        // For particular file field.
        $files = array( $config['field'] => $_FILES[$config['field']] );

        //if( strpos( $config['field'], '[' ) < 0 ) :
            // Single
            unset( $_FILES[$config['field']] );
        //endif;

    else :
        $files = $_FILES;
    endif;


    if( !empty( $files ) ) :

        $return = array();
        $user_data  = get_user_data();

        // Load upload library
        if( empty( $ci->upload ) ) :
            $ci->load->library( 'upload' );
        endif;

        $file_name = $config['file_name'];
        $upload_path = trim( str_replace( '\\', '/', $config['upload_path'] ), '/' ) . '/';
        if( empty( $upload_path ) ) :
            $config['upload_path'] = UPLOADS;
        else :
            $config['upload_path'] = $upload_path;
        endif;

        if( !file_exists( $config['upload_path'] ) ) :
            mkdir( $config['upload_path'], TRUE );
            chmod( $config['upload_path'], 0777 );
        endif;

        if( empty( $config['allowed_types'] ) ) :
            $config['allowed_types'] = '*';
        endif;

        foreach( $files as $fk => $file ) : // $fk = file1 

            $upload_clm = $fk;
            if( !is_array( $file['name'] ) ) : 

                $file = $files[$fk] = array( 
                    'name'      => array( $file['name'] ),
                    'type'      => array( $file['type'] ),
                    'tmp_name'  => array( $file['tmp_name'] ),
                    'error'     => array( $file['error'] ),
                    'size'      => array( $file['size'] ),
                );

            elseif( empty( $config['field'] ) ) :
                $upload_clm .= '[]';
            endif;

            //$file_str = $file_path_str = $full_path_str = '';
            foreach( $file['name'] as $k => $name ) : // $k = 0 // $name = Chrysanthemum.jpg

                if( !empty( $name ) ) : 

                    if( array_key_exists( $fk.'_'.$k, $uploaded_fields ) ) :
                        $return[$fk][$k] = $uploaded_fields[$fk.'_'.$k];

                    else :

                        // Do upload
                        if( empty( $file_name ) ) :
                            $config['file_name'] = $user_data['user_id'] .'_' . get_var_name( $name, '_', array('.') );
                        endif;

                        $_FILES[$upload_clm]['name']= $file['name'][$k];
                        $_FILES[$upload_clm]['type']= $file['type'][$k];
                        $_FILES[$upload_clm]['tmp_name']= $file['tmp_name'][$k];
                        $_FILES[$upload_clm]['error']= $file['error'][$k];
                        $_FILES[$upload_clm]['size']= $file['size'][$k];

                        $ci->upload->initialize( $config );
                        $ci->upload->do_upload( $upload_clm );


                        $return[$fk][$k] = $ci->upload->data();

                        if( empty( $return[$fk][$k]['file_size'] ) || !file_exists( $return[$fk][$k]['full_path'] ) ) :
                            // Error while uploading
                            $return[$fk][$k]['error'] = '1';
                            ++$errors;
                        else :
                            $return[$fk][$k]['error'] = '0';

                        endif;

                        $uploaded_fields[$fk.'_'.$k] = $return[$fk][$k];

                    endif;    

                    if( $return[$fk][$k]['error'] === '0' ) :
                        $return[$fk]['file_arr'][$k] = $return[$fk][$k]['file_name'];
                    
                        /*$file_str       .= $return[$fk][$k]['file_name'] . ',';
                        $file_path_str  .= $upload_path . $return[$fk][$k]['file_name'] . ',';
                        $full_path_str  .= $return[$fk][$k]['full_path'] . ',';*/
                    endif;

                endif;    

            endforeach;

            /*$return[$fk]['file_str'][]        = substr( $file_str, 0, -1 );
            $return[$fk]['file_path_str'][]   = substr( $file_path_str, 0, -1 );
            $return[$fk]['full_path_str'][]   = substr( $full_path_str, 0, -1 );*/

        endforeach;

    endif;

    //echo "<pre>fles: "; print_r( $_FILES );
    $return['error'] = $errors;
    return $return;
}

function convert_time_12_to_24($time) {
    $time_arr = explode(':', $time);
    $time_period = explode(' ', array_pop($time_arr));
    $hr = array_shift($time_arr);
    $min = array_shift($time_period);
    if (end($time_period) == 'PM') {
        if ($hr != 12) 
            $hr = $hr + 12;
        
        $hr = $hr;
    }
    else if ($hr == 12) 
        $hr = 0;
    else 
        $hr = $hr;
    
    return $hr . ':' . $min;
}

function fill_digits( $value, $fill_count = '5' ) {
                
        if( empty( $value ) ) :
                return $value;
        endif;

        $fill_digits = pow(10, $fill_count);
        if( $value < $fill_digits ) :
                $digits = '';
                for( $i = 0; $i < ( $fill_count - strlen( $value ) ); $i++ ) :
                        $digits .= '0';
                endfor;

                $digits .= $value;
        else :
                return $value;
        endif; 

        return $digits;
}

function inr_format( $str, $digits = 2, $sepr = ',' ) {
        $return = '';
        $str = number_format( $str, $digits, '.', '' );
        if( empty( $str ) ) :
            return $str;
        endif;

        $e = explode( '.', $str );
        $len = strlen( $e[0] );
        $lst = substr( $e[0], -3 );
        $str = substr( $str, 0, $len-3 );
        for( $i = ($len-4); $i >= 0; $i -= 2 ) :
            $return = ( $str[$i-1] !== NULL ? $str[$i-1] : '' ).( $str[$i] != '-' ? $str[$i].$sepr : $str[$i] ).$return;
        endfor;

        return $return.$lst.'.'.$e[1];
    }
    
    function get_var_name( $str, $replace_with = '-', $allows = '' ) {
        if( empty( $str ) ) :
            return '';
        endif;
        
        $ignores = array(' ',',','\\','`','.','*','#','@','[',']','-','!','$','^','%','/','{','}','"','\'','?','(',')');
        
        if( !empty( $allows ) ) :
            $ignores = array_diff( $ignores, $allows );
        endif;
        
        $pattern = '/'.implode( '|\\', $ignores ).'/';
        $replace_with = $replace_with == '' ? '_' : $replace_with;
        
        //$pattern = '/ |,|\\\|`|\.|\*|\#|@|\[|\]|\-|\!|\$|\^|\%|\/|\{|\}|\"|\'|\?|\(|\)/i';
        return strtolower( trim( preg_replace( '/'. $replace_with.$replace_with .'+/', $replace_with, preg_replace( $pattern, $replace_with, $str ) ), $replace_with ) );
    }
    
    function get_master_controller_id($controller){
        $ci = &get_instance();
        $ci->load->model('login_details_model', '', TRUE);
        return $ci->login_details_model->get_master_controller_id($controller);
    }
    
    function get_inventory_controller_id($controller){
        $ci = &get_instance();
        $ci->load->model('login_details_model', '', TRUE);
        return $ci->login_details_model->get_inventory_controller_id($controller);
    }
    
    function get_statue_controller_id($controller){
        $ci = &get_instance();
        $ci->load->model('login_details_model', '', TRUE);
        return $ci->login_details_model->get_statue_controller_id($controller);
    }
    
    function get_billing_controller($controller) {
        $ci = &get_instance();
        $ci->load->model('login_details_model', '', TRUE);
        return $ci->login_details_model->get_billing_controller($controller);
    }
    
    function get_file_preview( $url, $style = '', $show_delete = TRUE ) {
        
        $style = empty( $style ) ? 'width: 60px; height: 60px;' : $style;
        $html = '<div class="file-preview" style="'. $style .'">';
        if( !empty( $url ) ) :
            $html .= '<input type="hidden"  name="hidden_file[]" value="'. $url .'"/>';
        
            $ext = explode('.', $url);
            $ext = end( $ext );
            
            $file_url = '';
            if( $ext == 'png' || $ext == 'jpg' || $ext == 'jpeg' || $ext == 'gif' ) :
                $file_url .= $url;
            else:
                
                $file_url .= 'assets/images/file-icons/'; 
                if( !file_exists( $file_url. $ext.'.png' ) ) :
                    $ext = 'other';
                endif;
                
                $file_url .= $ext.'.png';
            endif;
            
            $html .= '<img src="'. BASE_URL . $file_url .'" style="width: 100%; max-height: 100%;" />';
            if( $show_delete ) :
                $html .= '<i class="fa fa-times rm-file-icn" style="position: absolute; cursor: pointer; margin-left: -10px; background: #ccc; color: #fff; padding: 5px; border-radius: 15px; min-width: 24px; text-align: center;"></i>';
            endif;
        endif;
        $html .= '</div>';
        
        return $html;
    }