<?php

/* 
 * Author       : Jai K
 * Purpose      : Model for Billing Archanai
 * Created On   : 2016-08-22 12:23
 */

class Archanai_Model extends CI_Model {
    
    function __construct() {
        parent::__construct();
        
    }
    
    function get( $tbl_name, $where = array(), $args = array() ) {
        $where['status'] = 1;
        
        if( !empty( $args['order_by'] ) ) :
            $this->db->order_by( $args['order_by'] );
        endif;
        
        $q = $this->db->get_where( $tbl_name, $where );
        return $q->result_array();
            
    }
    
    function get_all( $id= '', $where = array() ) {
        if( !empty( $id ) ) :
            $where['self.id'] = $id;
        endif;
        
        $where['self.status'] = 1;
        
        
        $this->db->select( 'self.*, self.status AS status, serv.name AS service_name, god.name AS god_name, star1.name AS star_name_1, star2.name AS star_name_2' );
        
        $this->db->join( TBL_SERVICE . ' AS serv', 'serv.id = self.service_id', 'left' );
        $this->db->join( TBL_GOD_NAME . ' AS god', 'god.id = self.god_id', 'left' );
        $this->db->join( TBL_STAR . ' AS star1', 'star1.id = self.star_id_1', 'left' );
        $this->db->join( TBL_STAR . ' AS star2', 'star2.id = self.star_id_2', 'left' );
        
        $q = $this->db->get_where( TBL_BA . ' AS self', $where );
        return $q->result_array();
    }
    
    function get_members( $mem_reg_id ){
        $this->db->select('id, name, tamil_name, star AS star_id');
        $q = $this->db->get_where( TBL_BILL_CARD_MEMBERS . ' AS mc', array('mem_reg_id' => $mem_reg_id, 'status' => 1 ) );
        return $q->result_array();
        
    }
    
    
    function get_payments( $ba_id ) {
        $where['self.pay_ref_type'] = 2; // Billing Archanai
        $where['self.pay_ref_id'] = $ba_id;
        $where['self.status'] = 1;
        
        $this->db->join( TBL_PAY_TYPE . ' AS ptype', 'ptype.id = self.pay_type_id' );
        $q = $this->db->get_where( TBL_PAY . ' AS self', $where );
        return $q->result_array();
    }  
    
    function scan($type) {
        $date_now = date("Y-m-d H:i:s");
        $session_data = $this->session->userdata( TBL_PREFIX . 'user_logged_in' );
        
        switch( $type ) :
            
            case 'payment' :
               /*
                *  Enable "Membership Card Payment Type" 
                */
                $this->db->select('id, status');
                $q = $this->db->get_where( TBL_PAY_TYPE, array('slug' => 'membership-card') );
                $pay_types = $q->result_array();
                
                if( empty( $pay_types ) ) :
                    // Insert a new One
                    $args = array(
                        'name'      => 'Membership card',
                        'slug'      => 'membership-card',
                        'url_key'   => 'membership-card',
                        'created_on'=> $date_now,
                        'created_by'=> $session_data['user_id'],
                        'status'    => 1,
                    );
                
                    $this->db->insert( TBL_PAY_TYPE, $args );
                    $pay_id = $this->db->insert_id();
                    
                else :
                    $pay_id = 0;
                    foreach( $pay_types as $k => $pay_type ) :
                        if( $pay_type['status'] == "1" ) :
                            $pay_id = $pay_type['id'];
                            break;
                        endif;
                    endforeach;
                    
                    if( $pay_id == 0 ) :
                        $pay_id = $pay_types[0]['id'];
                        $this->db->update( TBL_PAY_TYPE, array('status' => 1, 'updated_on' => $date_now, 'updated_by' => $session_data['user_id'] ), array('id' => $pay_id ) );
                    endif;
                    
                endif;
                
                return $pay_id;
            break;    
            
        endswitch;
        
    }
    
    
    function ajax() {
        $post = $this->input->post();
        #error_log(print_r($post,1));
        switch( $post['act'] ) :
            
            case 'scan' :
                
                // Get Card Details
                $err_no = 0; // No error
                $result = array();
                
                switch( $post['type'] ) :
                    
                    case 'log' :
                        // Mini Statement
                        
                        $this->db->limit(10);
                        $this->db->order_by('created_on DESC');
                        
                        $this->db->select('DATE_FORMAT( `created_on`, "%d-%b-%Y %h:%i %p") AS date, pay_amount AS amount', FALSE);
                        $this->db->like('pay_desc', 'By Card');
                        $q = $this->db->get_where( TBL_PAY, array( 'mem_card_id'  => $post['id'], 'status' => 1) );
                        $result = $q->result_array();
                        
                        
                        if( $post['print'] == 'true' ) :
                            
                            
                            $body = array();
                            foreach( $result as $k => $row ) :
                                $body[] = array( $row['date'], $row['amount'] );
                            endforeach;
                            
                             $args = array(
                                'type'      => '8', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai, '6' => Common
                                //'rec_no'    => $receipt_no,
                                'title'     => 'MINI STATEMENT',
                                'amount'    => array(''),
                                'copy'      => FALSE,
                                'short'     => TRUE,

                                'data'      => array(
                                    // Type = 7
                                    'html'  => '<style type="text/css">#tbl-card tr, #tbl-card td{ text-align: left; } #items-table tr td:nth-child(3) { text-align: right; }</style>',
                                   'fields'  => array(
                                        'attr'              => ' id="tbl-card" ',
                                        'Card Holder Name'   => $post['name'],
                                    ),
                                    
                                    'tables' => array(

                                       'attr'  => 'id="items-table"', // <table>  attributes
                                       'head'  => array('Date', 'Amount S$'),
                                       'body'  => $body 
                                         /*array(
                                           array('Parvathi','2','10.00'),
                                           array('Lakshmi','6','20.00'),
                                           array('Lakshmi','6','20.00'),
                                       ),*/

                                    ),
                                ),
                            );
                             
                            //echo '<pre>'; print_r( $args ); die;
                            
                        /*
                            $args = array(
                                'type'      => '5', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai, '6' => Common
                                'is_scan'   => true,
                                'is_mini'   => true,    
                                'gst'       => $gst, 

                                'data'      => array( 

                                    // Type = 5
                                    'name'      => $print_args['name'],
                                    'items'     => $print_args['items'],
                                    'extra'     => $print_args['extra'],
                                    'is_tamil'  => $is_tamil,
                                    'rec_msg'   => $rec_msg,

                                ),

                            );
                            */
                        
                        
                            $results = print_rec($args);
                            
                            
                            
                        endif;
                        
                    break;    
                    
                    case 'change':
                        // Password Change
                        $this->db->update( TBL_BILL_MEMBER_CARD, array('password' => $post['passcode']), array('id' => $post['id']) );
                        
                    break;
                
                    case 'scanned' :
                        
                        $this->db->select('*, star AS star_id');
                        $q = $this->db->get_where( TBL_BILL_MEMBER_CARD, array('card_no' => $post['cardNo']) );
                        $result = $q->row_array();
                        
                        if( empty( $result ) ) :
                            $err_no = 1; // Card No Not exists
                        elseif( $result['status'] != 1 ) :
                            $err_no = 2; // Inactive Card No
                            
                        endif;
                        
                        //echo "<pre>"; print_r( $result ); die;

                    break;    
                        
                    case 'pass' :
                        // Validate Password
                        $this->db->select('*, star AS star_id');
                        $q = $this->db->get_where( TBL_BILL_MEMBER_CARD, array('id' => $post['id'], 'password' => $post['passcode']) );
                        $result = $q->row_array();
                        if( empty( $result ) ) :
                            $err_no = 3; // Invalid password
                        else :
                            // Set as User logged In
                            
                            
                            $user = array(
                                'role'      => 1,
                                'id'   => $result['id'],
                                'name'      => $result['name'],
                                'log_type'  => 'scan',
                                'is_kiosk'  => TRUE,
                            );
                        
                            set_user_data((Object) $user);
                            
                        endif;
                    break;    
                endswitch;
                
                $results = array(
                    'errNo' => $err_no,
                    'result' => $result
                );
                
           
            break;    
            
           
            case 'submit' :
                $date_now = date("Y-m-d H:i:s");
                $session_data = $this->session->userdata( TBL_PREFIX . 'user_logged_in' );
                $pay_amt = $paid_amt = 0;
                $dgt_nos = 5;
                
                $is_tender = $post['isTender'] == 'true' ? TRUE : FALSE;
                $is_tamil  = $post['isTamil']  == 'true' ? TRUE : FALSE;
                $is_scan   = $post['isScan'] == 'true' ? TRUE : FALSE; 
                $this->session->set_userdata( $session_data['user_id'] . '_tamil', $is_tamil);
                
                //echo "<pre>"; print_r( $post ); die;
                
                /*Data: Array
(
    [act] => submit
    [items] => Array
        (
            [0] => Array
                (
                    [catId] => 1
                    [itemId] => 1
                    [grouping] => 1
                    [qty] => 1
                    [price] => 1.00
                )

            [1] => Array
                (
                    [catId] => 1
                    [itemId] => 2
                    [grouping] => 1
                    [qty] => 2
                    [price] => 1.00
                )

            [2] => Array
                (
                    [catId] => 4
                    [itemId] => 14
                    [grouping] => 0
                    [qty] => 9
                    [price] => 10.00
                )

        )

    [payments] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [val] => 93.00
                )

        )

    [input_1] => Kannan
    [input_2] => 12
    [input_3] => Pico
    [input_4] => 15
)*/
                
                /* $post =  array
(
    'act' => 'submit',
    'items' => array
        (
            '0' => array
                (
                    'catId' => '2',
                    'itemId' => '1',
                    'grouping' => '0',
                    'gods'  => '1,3',
                    'qty' => '10',
                    'price' => '10.00',
                    'bari_rec_no'   => '6CT332',
                ),

            '1' => array
                (
                    'catId' => '2',
                    'itemId' => '2',
                    'grouping' => '1',
                    'gods'  => '1',
                    'qty' => '5',
                    'price' => '5.00',
                    'bari_rec_no'   => '2CT312',
                ),

            '2' => array
                (
                    'catId' => '2',
                    'itemId' => '10',
                    'grouping' => '1',
                    'qty' => '1',
                    'price' => '1.00',
                    'bari_rec_no'   => '3CU152',
                ),

            '3' => array
                (
                    'catId' => '3',
                    'itemId' => '14',
                    'grouping' => '0',
                    'gods'  => '1,3,5',
                    'qty' => '4',
                    'price' => '10.00',
                    'bari_rec_no'   => '9ET631',
                ),
               
        ),

    'payments' => array
        (
            '0' => array
                (
                    'id' => '1',
                    'val' => '22',
                ),

            '1' => array
                (
                    'id' => '2',
                    'val' => '34',
                ),

        ),

    'input_1' => 'Jen',
    'input_2' => '2',
    'input_3' => 'Kepler',
    'input_4' => '5',
    'input_5' => 'Mic',
    'input_6' => '8',
);
            */
                
                /*
                * Get last Receipt ID
                */
                $this->db->select('COUNT(id) AS last_count');
                $q = $this->db->get_where( TBL_BAR, array());
                $rec_id = $q->row_array()['last_count'];
                $parent_rec_no = fill_digits( ++$rec_id, 4 );
                
                $general_setting = get_general_setting();
                $gst = $general_setting->gst;
                
                $print_args = array();
                
                
                
                /*
                 * Items
                 */
                $cat_rec = $cats = $name_group = array();
                // Category in General Settings
                
                foreach( $post['items'] as $k => $itm ) :
                    $rec_nos = array();
                
                
                    /*
                     * Parent table
                     */
                     if( empty( $name_group[$itm['nameGroup']] ) ) :
                        $names = !empty( $itm['names'] ) ? json_decode( $itm['names'], TRUE ) : array($post['input_1'], $post['input_3']);
                     
                        $args = array(
                            'bar_rec_no'    => $parent_rec_no++,
                            'bar_name_1'    => htmlspecialchars( substr( $names[0], 3 )),
                            'star_id_1'     => $post['input_2'],
                            'bar_name_2'    => htmlspecialchars( substr( $names[1], 3 )),
                            'star_id_2'     => $post['input_4'],
                            'contact_no'    => $post['contact_no'],
                            /*'bar_name_3'    => $post['input_5'],
                            'star_id_3'     => $post['input_6'],*/
                            'gst'           => $gst,
                            'is_tender'     => $is_tender ? 1 : 2,
                            'created_on'    => $date_now,
                            'created_by'    => $session_data['user_id'],
                        );

                        $this->db->insert( TBL_BAR , $args );
                        $db_id = $this->db->insert_id();
                        
                        $name_group[$itm['nameGroup']] = $db_id;
                    endif;    
                
                    
                    if( empty( $cats[$itm['catId']] ) ) :
                        $this->db->select('id, category_name, tamil_name, grouping, cat_prefix, image, is_separate');
                        $q = $this->db->get_where(TBL_CATEGORY, array('id' => $itm['catId']));
                        $cat = $q->row_array();
                        $cats[$itm['catId']] = $cat;
                    else :
                        $cat = $cats[$itm['catId']];
                    endif;  
                    
                    /*$cat_name = trim( str_replace('ARCHANAI', '', strtoupper( $cat['category_name'] ) ) );
                    $rec_no = ( $cat_name[0].$cat_name[strlen($cat_name)-1] );*/
                    $rec_no = '';
                    $itmm_id = 0;
                    $whre = array();
                    
                    if( $general_setting->is_category == 1 ) :
                        // With Category
                        $rec_no .= $cat['cat_prefix'];
                        $whre['bari_cat_id'] = $cat['id'];
                        
                        $whre['is_category'] = 1;
                    else :
                        // Without Category (For Whole Application)
                        $whre['is_category'] = 0;
                    endif;
                    
                    if( $cat['grouping'] != '1' ) :
                        // Single
                        $whre['bari_item_id'] = $itm['itemId'];
                        $itmm_id = $itm['itemId'];
                    endif;
                    
                    // Added for Server Down Import operation
                    $itm['is_cat_group'] = $cat['grouping'];

                    if( empty( $cat_rec[$cat['id']][$itmm_id] ) ) :
                        // Get Count
                        $this->db->limit(1);
                        //$this->db->where('`bari_rec_no` IS NOT NULL', '', FALSE);
                        $this->db->order_by('id', 'DESC');
                        $this->db->select('bari_rec_cnt AS count');
                        $q = $this->db->get_where(TBL_BARI, $whre);
                        $last_rec_cnt = $q->row_array()['count'];
                        
                        $cat_rec[$cat['id']][$itmm_id] = !empty( $last_rec_cnt ) ? $last_rec_cnt : 0;
                    endif;
                    
                    for( $i = 0; $i < $itm['qty']; $i++ ) :
                        /*
                         * Insert by Quantity Wise
                         */
                        ++$cat_rec[$cat['id']][$itmm_id];
                        
                        $args = array(
                            'bar_id'        => $db_id,
                            'bari_cat_id'   => (($general_setting->is_category == 1) ? $itm['catId'] : 0),
                            'bari_item_id'  => $itm['itemId'],
                            'bari_qty'      => 1, //$itm['qty'],
                            'bari_price'    => $itm['price'],
                            'bari_sub_total'=> $itm['price'], //$itm['qty'] * $itm['price'],
                            'bari_god_ids'  => $itm['gods'],
                            'bari_is_inventory'=> $itm['isInventory'] == '1' ? '1' : '0',
                            'is_category'   => (($general_setting->is_category == 1) ? 0 : 1),

                            'bari_rec_cnt'  => $cat_rec[$cat['id']][$itmm_id],
                            'bari_rec_no'   => ($rec_no.( $cat_rec[$cat['id']][$itmm_id] < pow(10, $dgt_nos) ? fill_digits( $cat_rec[$cat['id']][$itmm_id], $dgt_nos ) : $cat_rec[$cat['id']][$itmm_id] )),
                            
                            'created_on'    => $date_now,
                            'created_by'    => $session_data['user_id'],
                        );
                        
                        $name_group[$itm['nameGroup']][$db_id] = $args['bari_sub_total'];
                        
                        $this->db->insert( TBL_BARI , $args );
                        $item_ins_id = $this->db->insert_id();
                        
                        $pay_amt += $args['bari_price'];
                        $rec_nos[] = $args['bari_rec_no'];
                        
                    endfor;
                
                    /*
                     * Reduce Inventory
                     */
                     if( $itm['isInventory'] == '1' && !empty( $itm['invItemId'] ) ) :
                         
                        $inv_item_id  = $itm['invItemId'];
                     
                        $this->db->order_by('id desc');
                        $q = $this->db->get_where(TBL_INV_LOG, array('inv_item_id' => $inv_item_id, 'status' => 1));
                        $log = $q->row_array();
                        
                        $args = array(
                            'inv_cat_id'    => $log['inv_cat_id'],
                            'inv_item_id'   => $inv_item_id,
                            'uom'           => $log['uom'],
                            'cost_price'    => $poi['unit_price'],
                            'sell_price'    => $inv_item['selling_price'],
                            
                            'inv_qty'           => $itm['qty'],
                            'prev_avail_qty'    => $log['prev_avail_qty'],
                            'now_avail_qty'     => $log['now_avail_qty'],
                            'bal_issued_qty'    => $log['bal_issued_qty'] - $itm['qty'],

                            'created_on'    => $date_now,
                            'created_by'    => $session_data['user_id'],
                        );   

                        $this->db->update( TBL_INV_LOG, array('status' => 0), array( 'id' => $log['id'] ) );
                        $this->db->insert( TBL_INV_LOG, $args );
                        
                        
                        // Update "Counter Qty" in Inventory Issued table
                        $this->db->order_by('id ASC');
                        $q = $this->db->get_where( TBL_INV_ISSUED, array( 'usage_type' => 1, 'inv_item_id' => $args['inv_item_id'], 'total_avail_qty >' => 0, 'status' => 1 ) );
                        $iu_items = $q->result_array();
                        
                        $tmp_qty = $itm['qty'];
                        foreach( $iu_items as $uk => $iu_item ) :
                            
                            if( $tmp_qty > 0 ) :
                                $set = array(); 
                                if( $iu_item['total_avail_qty'] <= $tmp_qty ) :
                                    // Fully Used
                                    $set['total_avail_qty'] = 0;
                                    $set['total_sold_qty'] = $iu_item['total_issued_qty'];
                                    
                                else :
                                    $set['total_avail_qty'] = $iu_item['total_avail_qty']-$tmp_qty;
                                    $set['total_sold_qty'] = $iu_item['total_sold_qty'] + $tmp_qty;
                                endif;
                                
                                $tmp_qty = $tmp_qty - $iu_item['total_avail_qty'];
                                
                                $this->db->update( TBL_INV_ISSUED, $set, array('id' => $iu_item['id']) );
                            else :
                                break;
                            endif;
                        endforeach;
                        
                        
                        /*$this->db->set('`total_sold_qty`', '`total_sold_qty`+'.$itm['qty'], FALSE);
                        $this->db->set('`total_avail_qty`', '`total_avail_qty`-'.$itm['qty'], FALSE);
                        $this->db->update( TBL_INV_ISSUED, array('updated_on' => $date_now, 'updated_by' => $session_data['user_id']), array('usage_type' => 1, 'inv_item_id' => $args['inv_item_id']) );
                         */
                        
                        
                        // Update "avail. Counter Qty" in Item table
                        $this->db->set('`avail_counter_qty`', '`avail_counter_qty`-'.$itm['qty'], FALSE);
                        $this->db->update( TBL_ITEM, array(), array('inv_item_id' => $args['inv_item_id']) );
                      
                     endif;
                     
                    $post['items'][$k]['bari_rec_no'] = $rec_nos;
                endforeach;
            
                
                /*
                * Payments
                */
                if( $is_tender || $is_scan ) :
                    
                    if( $is_scan ) :
                        $pay_type_id = $post['payId'];
                    
                        /*if( empty( $pay_type_id ) ) :
                            $q = $this->db->get_where(TBL_PAY_TYPE, array('slug' => 'membership-card', 'status' => 1));
                            $pay_type = $q->row_array();
                            $pay_type_id = $pay_type['id'];
                        endif;*/
                        
                        // Deduct the card Balance
                        /*$this->db->set('`amount`', '`amount` - '.$pay_amt, FALSE);
                        $this->db->update( TBL_BILL_MEMBER_CARD, array(), array('id' => $post['cardDetails']['mem_reg_id']) );*/
                    endif;
                    
                   // Direct Cash
                   
                   $post['payments'] = array(
                        array(
                           'id'         => $is_scan && !empty($pay_type_id) ? $pay_type_id : 1,
                           'val'        => $pay_amt,
                           'member'     => $is_scan ? $post['cardDetails'] : '',
                           'pay_details'=> $is_scan ? $post['cardDetails'] : '',
                        ),   
                   );
                   
                endif;
               
                foreach( $post['payments'] as $k => $pay ) :
                    $this->db->select('slug');
                    $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $pay['id']) );
                    $prow = $q->row_array();

                    $pay_details = $pay['pay_details'];
                    if( $prow['slug'] == 'cheque' && !empty($pay['val']) ) :
                        // Cheque
                        $e = explode('-', $pay['details']['date']);
                        $pay_details = array(
                            'name'   => $pay['details']['name'],
                            'no'   => $pay['details']['no'],
                            'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                        );
                    endif;

                    $pay_details = json_encode( $pay_details );

                    $members = array();
                    if( $prow['slug'] == 'membership-card' && !empty($pay['val']) ) :
                        // Membership Card
                        $members = array(
                            'name'   => $pay['member']['name'],
                            'no'   => $pay['member']['card_no'],
                            'amount' => $pay['member']['amount'],
                        );

                         // Pay amount From Membership Card

                         if($pay['member']['amount'] > 0) :
                             $paidAmount = $pay['member']['amount'] - $pay['val'];
                             $update_amount = array(
                                 'amount' => $paidAmount
                             );
                             $this->update_card_amount($update_amount,$pay['member']['mem_id']);

                             /*** To Insert Refund Amount - Start ***/
                             /* $insert = array(
                                 'menu_id' => 2,
                                 'auto_id' => $db_id,
                                 'pay_type_id' => $pay['id'],
                                 'amount' => $pay['val'],
                                 'created_on' => $date_now,
                                 'created_by' => $session_data['user_id']
                             );
                             $this->insert_refund_amount($insert);   */          

                         endif;
                    endif;
                   
                    $members = json_encode( $members );

                    $paid_amt += $pay['val'];
                    $args = array(
                        'pay_ref_type'  => 2, // For Billing Archanai
                        'pay_ref_id'    => $db_id, // Main ID
                        'pay_type_id'   => $pay['id'],
                        'pay_amount'    => $pay['val'],
                        'pay_details'   => $pay_details,
                        'member_card_details'   => $members,
                        'pay_desc'      => $is_tender ? 'Tender' : ( $is_scan ? 'By Card Scanning' : '' ), 
                        'created_on'    => $date_now,
                        'created_by'    => $session_data['user_id'],
                    );
                   
                    if( $is_scan ) :
                        $args['mem_card_id'] = $post['cardDetails']['mem_id'];
                    endif;

                    // Insert
                    $this->db->insert( TBL_PAY, $args );
                   
               endforeach; 

                $gst_amount = ($gst / 100) * ($pay_amt);               
               
                // Update Amount
                $args = array(
                    'bar_amount'     => $pay_amt,
                    'bar_paid_amount'=> $paid_amt,
                    //'gst'            => $gst,
                    //'gst_value'      => $gst_amount,
                );

                $this->db->update( TBL_BAR, $args, array('id' => $db_id) );
               
               
               /*
                * Print
                */
                $print_args = $itms = $stars = array();
                $with_god = $with_name = $with_footer = $with_group = FALSE;
                
                foreach($post['items'] as $k => $item ) :
                    $qty = $item['qty'];
                    $rec_nos = $item['bari_rec_no'];
                    $names   = $item['names'];   
                    
                    
                    $gods = array();
                    if( !empty($item['gods']) ) :
                        $this->db->select('name, tamil_name, price, icon');
                        $this->db->where_in('id', explode(',', $item['gods'])); // Comma separated God ID's
                        $q = $this->db->get_where(TBL_GOD_NAME, array());
                        $gods = $q->result_array();
                    endif;

                    if( !empty($cats[$item['catId']]) ) :
                        $cat = $cats[$item['catId']];
                    else :
                        $q = $this->db->get_where(TBL_CATEGORY, array('id' => $item['catId']));
                        $cat = $q->row_array();
                        
                        $cats[$item['catId']] = $cat;
                    endif;
                    
                    if( !empty($itms[$item['itemId']]) ) :
                        $item = $itms[$item['itemId']];
                    else :
                        $q = $this->db->get_where(TBL_ITEM, array('id' => $item['itemId']));
                        $item = $q->row_array();
                        
                        $itms[$item['itemId']] = $item;
                    endif;
                    
                    $cat['image'] = !empty( $cat['image'] ) ? DIR_CATEGORY_IMAGE . $cat['image'] : '';
                    $item['image'] = !empty( $item['image'] ) ? DIR_ITEM_IMAGE . $item['image'] : '';

                    $item['cat'] = $cat;
                    //$item['category_id'] = $cat['id'];
                    $item['cat']['name'] = $cat['category_name'];
                    
                    if( !empty($names) ) : //if( $is_scan ) :
                        $names = json_decode( $names, TRUE ); //explode(',', $item['names']);
                        foreach( $names as $n => $name ) :
                            $star = $stars[$name[1]];
                            if( empty( $star ) ) :
                                $q = $this->db->get_where( TBL_STAR, array('id' => $name[1]) );
                                $star = $q->row_array();
                                $stars[$name[1]] = $star; 

                            endif;
                            $item['with_names'][] = array($name[0], $star['tamil_name']);
                        endforeach;
                    endif;
                    
                    $agods = array('');
                    $is_separ_god = ( !empty($gods) && $cat['grouping'] != '1' ) ? TRUE : FALSE;
                    if( $is_separ_god ) :
                        // With Gods, but Not Grouping
                        $qty = 1;
                        $agods = $gods;
                        $rec_nos_arr = $rec_nos;
                    endif;
                    
                    foreach($agods as $x => $agod) :
                        if( $is_separ_god ) :
                            $gods[$x]['image'] = !empty( $agod['icon'] ) ? DIR_GOD_ICON . $agod['icon'] : '';
                            $item['gods'] = array($gods[$x]);
                            //$item['gods'] = array($gods[$x], '');
                            $rec_nos = array($rec_nos_arr[$x]);
                        else :
                            $item['gods'] = $gods;
                        endif;
                        
                        $item['qty'] = $qty;

                        $item['sub_total'] = $qty * $post['items'][$k]['price'];
                        
                        //**if( $item['god_name'] == '1' || $cat['grouping'] != '1' ) :
                            // Separate Receipt ( With God || No Group )
                        
                        if( $cat['grouping'] != '1' || $cat['is_separate'] == '1' || $is_scan ) :
                            // Separate Receipt ( No Group only )
                            
                            $upto = 1;
                            if( $cat['is_separate'] == '1' ) :
                                $upto = $qty;
                                $qty = 1;
                                $item['sub_total'] = $item['price'];
                                $item['qty'] = $qty;
                            endif;
                        
                            $item['cat_prefix'] = $cat['cat_prefix'];
                            for( $n = 0; $n < $upto; $n++ ) :
                                $item['total_qty'] = $qty;

                                $item['rec_no'] = $cat['is_separate'] == '1' ? array($rec_nos[$n]) : $rec_nos;
                                $item['total_price'] = $item['sub_total'];
                                $print_args['items'][] = array($item);
                                //$print_args['items'][$cat['id']][0]['rec_no'] = $rec_nos;
                            endfor;

                        else :
                            // Group 
                            
                            $item['rec_no'] = $rec_nos;
                            $print_args['items']['group-'.$cat['id']][] = $item;
                            //$print_args['items'][$cat['id']][0]['rec_no'] = $rec_nos;
                            $print_args['items']['group-'.$cat['id']][0]['total_qty'] += $qty;

                            if( $item['receipt'] == '1' ) :
                                // With Name is found
                                $print_args['items']['group-'.$cat['id']][0]['receipt'] = '1';
                            endif;

                            if( $item['is_enable_footer'] == '1' ) :
                                // With Footer is found
                                $print_args['items']['group-'.$cat['id']][0]['is_enable_footer'] = '1';
                            endif;

                            $print_args['items']['group-'.$cat['id']][0]['total_price'] += $item['sub_total'];

                        endif;
                    endforeach;     // $agods
            
                    
                endforeach;

                /*$print_args['extra'] = array(
                    'with_god'      => $with_god,
                    'with_name'     => $with_name,
                    'with_footer'   => $with_footer,
                );*/

                
                //if( !$is_scan ) :
                    
                    for( $i = 1; $i <=4; $i+=2 ) :    
                        $q = $this->db->get_where(TBL_STAR, array('id' => $post['input_'.($i+1)]));
                        $star = $q->row_array();
                        $print_args['name'][] = array($post['input_'.$i], $star['tamil_name']);
                    endfor;
                //endif;


                $args = array(
                    'type'      => '5', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai, '6' => Common
                    //'rec_no'    => '000004-000006',
                    //'title'     => $main_service['service_name']. ' - '.$service['name'],
                    //'amount'    => array('340.00','340.00'),
                    //'copy'      => FALSE,
                    'is_category' => $general_setting->is_category,
                    'is_scan'     => $is_scan,  
                    'gst'         => $gst, 

                    'data'      => array( 
                        
                        // Type = 5
                        'name'      => $print_args['name'],
                        'items'     => $print_args['items'],
                        'extra'     => $print_args['extra'],
                        'is_tamil'  => $is_tamil,
                    ),

                );

                $results = print_rec($args);
                
            break;
            
            case 'cat-items' :
                $cat_id = $post['catId'];
                
                $results = $this->get_items($cat_id);
                
            break;
        
        endswitch;
        
        return $results;
    }
    
    function get_items( $cat_id = '' ) {
        
        $whr = array(
            'itm.status' => 1
        );
        
        if( !empty( $cat_id ) ) :
            $whr['itm.category_id'] = $cat_id;
        endif;
        
        $this->db->select('cat.id, cat.category_name, cat.grouping, itm.*, cat.id AS cat_id, itm.id AS item_id, itm.is_inventory, itm.inv_item_id, itm.avail_counter_qty AS actual_counter_qty, CASE WHEN `itm`.`avail_counter_qty` < 0 THEN 0 ELSE `itm`.`avail_counter_qty` END AS avail_counter_qty, (SELECT price FROM `'. TBL_PRICE .'` WHERE FIND_IN_SET( itm.id, `item_id`) AND `category_id` = cat.id AND `status` = "1" AND CURDATE() BETWEEN start_date AND end_date) AS date_price', FALSE);
        $this->db->join( TBL_CATEGORY . ' AS cat', 'cat.id = itm.category_id' );
        $this->db->order_by('itm.order_sequence');
        $q = $this->db->get_where( TBL_ITEM . ' AS itm', $whr );
        $db_results = $q->result_array();

        $results = array();
        foreach( $db_results as $k => $result ) :
            $img_url = DIR_ITEM_IMAGE . $result['image'];

            if( empty($result['image']) || !file_exists( $img_url ) ) :
                // Placeholder Image
                $img_url = '';//assets/billing/images/placeholder.png';
            endif;

            $result['image'] = $img_url;
            $results[$k] = $result;
        endforeach;
        
        return $results;
    }
    
    public function update_card_amount($data,$id) {
        $this->db->where('id',$id);
        $this->db->update(TBL_BILL_MEMBER_CARD,$data);
        return $this->db->affected_rows();
    }
    
    public function insert_refund_amount($data){
        $this->db->insert(TBL_REFUND,$data);
        return $this->db->insert_id();
    }
    
    public function get_items_by_not_cat() {
        $this->db->select('cat.id, cat.category_name, cat.grouping, itm.*, cat.id AS cat_id, itm.id AS item_id, itm.is_inventory, itm.inv_item_id, itm.avail_counter_qty, (SELECT price FROM `'. TBL_PRICE .'` WHERE FIND_IN_SET( itm.id, `item_id`) AND `category_id` = cat.id AND `status` = "1" AND CURDATE() BETWEEN start_date AND end_date) AS date_price', FALSE);
        $this->db->join( TBL_CATEGORY . ' AS cat', 'cat.id = itm.category_id','left');
        $this->db->order_by('itm.order_sequence');
        $q = $this->db->get_where( TBL_ITEM . ' AS itm', array('itm.status' => 1) );
        $db_results = $q->result_array();
        
        $results = array();
        foreach( $db_results as $k => $result ) :
            $img_url = DIR_ITEM_IMAGE . $result['image'];
        
            if( empty($result['image']) || !file_exists( $img_url ) ) :
                // Placeholder Image
                $img_url = '';//assets/billing/images/placeholder.png';
            endif;
            
            $result['image'] = $img_url;
            $results[$k] = $result;
        endforeach;
        
        return $results;
    }
    

}
