<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Billing_ubayam extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('billing/ubayam_model', '', TRUE);
        $this->load->model('login_details_model', '', TRUE);
        $this->load->model('billing/archanai_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index($id = 17) {
        $data = array();
        $data['results'] = $this->ubayam_model->list_all();
        if (!empty($this->session->flashdata('success'))) 
            $data['success'] = $this->session->flashdata('success');
        else 
            $data['error'] = $this->session->flashdata('error');
        
        $actions = $this->actions();
        $data['add_btn']    = 'Create New Ubayam Details';
        $data['view_link']  = $actions['view'] . '/';
        $data['add_link']   = $actions['add'] . '/' . $id ;
        $data['edit_link']  = $actions['edit'] . '/';
        $data['delete_link']= $actions['delete'] . '/';
        $data['print'] = base_url() . 'billing_ubayam/print_list/';
        $data['title'] = 'Ubayam';
        
        $data['menu_id'] = $id;
        $service_menu = get_billing_controller($actions['controller']);
        $data['title'] = $service_menu->service_name;
        $data['service_menu_id'] = array('service_menu_id' => $service_menu->id, 'menu_type' => '4');
        $this->render($data, 'billing/ubayam/list');
    }
    
    public function add($type_id= '') {
        $data = array();
        $actions = $this->actions();
        $data['devotees'] = $this->ubayam_model->get( TBL_DEVOTEE, '', array('order_by' => 'name') );
        $data['deity'] = $this->ubayam_model->get( TBL_GOD_NAME, '', array('order_by' => 'name') );
        $data['fn_types'] = $this->ubayam_model->get( TBL_SERVICE, array( 'menu_name' => $type_id ), array('order_by' => 'name') );
        $data['stars'] = $this->ubayam_model->get( TBL_STAR, '', array('order_by' => 'name') );
        $data['service_type_id'] = $type_id;
        $data['ptypes'] = $this->ubayam_model->get( TBL_PAY_TYPE );
        $data['prasadams'] = $this->ubayam_model->get( TBL_PRASADAM, '', array('order_by' => 'name') );
        $data['categories'] = $this->archanai_model->get( TBL_CATEGORY, '', array('order_by' => 'category_order') );
        $data['pr_types']   = $this->ubayam_model->get( TBL_SERVICE, array( 'menu_name' => 15 ), array('order_by' => 'name') );
        $data['form_action'] = $actions['insert'];
        $data['title'] = 'Ubayam';
        $this->render($data, 'billing/ubayam/add');
    }
    
    private function get_ubayam_url_key($name, $id = '') {
        $url_key = get_url_key($name);
        if ($this->ubayam_model->ubayam_url_key_exists($url_key, $id)) {
            $this->uri_key_index ++;
            return $this->get_ubayam_url_key($name . '_' . $this->uri_key_index, $id);
        }
        
        return $url_key;
    }
    
    public function insert() {
        // echo '<pre>'; print_r($_POST); exit;
        $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('fn_type'));
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($this->input->post('cs_amount'));
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        
        $insert = array(
            'type_id' => $this->input->post('type_id'),
            'service_id' => $this->input->post('fn_type'),
            'date' => date('Y-m-d',strtotime($this->input->post('fn_date'))),
            'from_time' => date('H:i',strtotime($this->input->post('fn_from_time'))),
            'to_time' => date('H:i',strtotime($this->input->post('fn_to_time'))),
            'deity_id' => $this->input->post('fn_deity'),
            'period' => $this->input->post('fn_period'),
            'devotee_name1' => $this->input->post('ct_dev_name_1'),
            'tamil_name1' => htmlspecialchars( $this->input->post('ct_dev_name_1_tamil') ),
            'devotee_name2' => $this->input->post('ct_dev_name_2'),
            'tamil_name2' => htmlspecialchars( $this->input->post('ct_dev_name_2_tamil') ),
            'star1' => $this->input->post('ct_star_1'),
            'star2' => $this->input->post('ct_star_2'),
            'contact_no' => $this->input->post('ct_contact_no'),
            'email' => $this->input->post('ct_email'),
            'address' => $this->input->post('ct_address'),
            'desc' => $this->input->post('cs_desc'),
            'amount' => $this->input->post('ub_amount'),
            'gst' => $gst,
            'gst_value' => $gst_amount,
            'book_status' => (!empty($this->input->post('book-now'))) ? 2 : 1,
            'booked_date' => date('Y-m-d H:i:s'),
            'url_key' => $this->get_ubayam_url_key($this->input->post('ct_dev_name_1')),
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        
        $bk_status = $insert['book_status'];
        /*
        * Get last Receipt ID
        */
        $wh = array(
            'service_id'    => $insert['service_id'] ,
            'book_status'   => $bk_status
        );

        $receipt_no = generate_rec_no(TBL_BILL_UBAYAM, $wh);
        $insert['receipt_no'] = $receipt_no;   
        
        //$services = $this->ubayam_model->service_type_exists($this->input->post('fn_type'), $bk_status);
        
        if(!empty($this->input->post('book-now'))) {
            $insert['updated_on'] = date('Y-m-d H:i:s');
        }
        
        $insert_id = $this->ubayam_model->insert($insert);
        
        if ($insert_id > 0) {
            $this->session->set_flashdata('success', 'Billing for Ubayam Details is added successfully');
            /*if($services->num_rows() > 0) {
                $last_receipt_no = $services->row()->receipt_no;
                $last_no = (int)$last_receipt_no;
                $receipt_no = (($last_no + 1)  > 9999) ? ($last_no + 1)  : sprintf('0%03d', ($last_no + 1) );
            } else
                $receipt_no = '0001';
            
            $update = array(
                'receipt_no' => $receipt_no
            );
            $this->ubayam_model->update($update, $insert_id);*/
            
            // $deity = $this->input->post('pr_deity');
            // $qty = $this->input->post('pr_qty');
            // $price = $this->input->post('pr_price');
            // $prasadam = $this->input->post('pr_prasadam');

            //Prasadam
            if(!empty($_POST['pr_type'])) {
                $prasadam_res = $this->prasadam_insert($_POST);
                sleep(5);
            }
            //Other Archanai
            // $otherarchanai_res = $this->archanai_insert($_POST);
            // sleep(3);

            // if(!empty($deity)) {
            //     foreach( $deity as $k => $deity_id ) {
            //         $sub_total = $qty[$k] * $price[$k];
            //         $insert = array(
            //             'ubayam_id'   => $insert_id,
            //             'deity_id'      => $deity_id,
            //             'prasadam'      => $prasadam[$k],
            //             'quantity'      => $qty[$k],
            //             'price'         => $price[$k],
            //             'sub_total'     => $sub_total,
            //             'status'        => 1,
            //             'url_key'       => $this->get_ubayam_url_key($prasadam[$k]),
            //             'created_by'    => $this->user_data['user_id'],
            //             'created_on'    => date('Y-m-d H:i:s')
            //         );
            //         $this->ubayam_model->insert_prasadam($insert);
            //     }
            // }

            if(empty($this->input->post('book-now'))) {
                $pay_type = $this->input->post('pay_type');
                
                foreach( $pay_type as $key => $value ) {
                    if($value != '') {
                        
                        $this->db->select('slug');
                        $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $key) );
                        $prow = $q->row_array();
                   
                        $pay_details = array();
                        if( $prow['slug'] == 'cheque' && !empty($value) ) :
                            // Cheque
                            $e = explode('-', $this->input->post('chq_date'));
                            $pay_details = array(
                                'name'   => $this->input->post('chq_bnk_name'),
                                'no'   => $this->input->post('chq_no'),
                                'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                            );
                        endif;
                       
                        $pay_details = json_encode( $pay_details );
                        $ubayam_amount = $this->input->post('ub_amount');
                        $insert = array(
                            'pay_ref_type'  => 17,
                            'pay_ref_id'    => $insert_id,
                            'pay_type_id'   => $key,
                            'pay_amount'    => $ubayam_amount,//$value,
                            'pay_details'   => $pay_details,
                            'status'        => 1,
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => date('Y-m-d H:i:s')
                        );
                        $this->ubayam_model->insert_payment($insert);
                    }
                }
                
                /*** To Print Receipt - Start ***/
                $service_menu = $this->login_details_model->get_service_menu_by_id($this->input->post('type_id'));
                $prefix = get_general_setting()->prefix;
                $ubayam = $this->ubayam_model->get_by_id($insert_id);
                $prasadam = $this->ubayam_model->get_prasadam_by_id($insert_id);
                
                $gods = $prasadams= $print_body = array();
                foreach( $prasadam as $k => $details ) :
                
                    if( !array_key_exists( $details->deity_id, $gods ) ) :
                        $q  =$this->db->get_where( TBL_GOD_NAME, array('id' => $details->deity_id) );
                        $gods[$details->deity_id] = $q->row_array();
                    endif;
                    
                    if( !array_key_exists( $details->prasadam, $prasadams ) ) :
                        $q  =$this->db->get_where( TBL_PRASADAM, array('id' => $details->prasadam) );
                        $prasadams[$details->prasadam] = $q->row_array();
                    endif;
                    
                    $print_body[] = array(
                        (!empty($details->deity_id) ? ($gods[$details->deity_id]['name'] . ((!empty($gods[$details->deity_id]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $gods[$details->deity_id]['tamil_name'] .'</span>' : '')) : '<center> - </center>'),
                        $prasadams[$details->prasadam]['name'] . ((!empty($prasadams[$details->prasadam]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $prasadams[$details->prasadam]['tamil_name'] .'</span>' : ''),
                        '<div style="text-align: right;">'.$details->quantity . ' x ' . $details->price .'</div>',
                        '<div style="text-align: right;">'.number_format( $details->quantity*$details->price, 2 ).'</div>',
                    );
                endforeach;
                $cdate = ''; $cdate = date('d-m-Y h:i:sa', strtotime($insert['created_on']));
                $args = array(
                    'type'      => '1', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
                    'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,
                    'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
                    'amount'    => array($this->input->post('ub_amount')),
                    'gst'       => $gst_details->gst,
                    'printType' => TRUE,
                    'created_on' => $cdate,
                    'fn_type' => 'ubayam',
                    
                    'data'      => array(
                        // Type = 1 && 3 
                        'name'      => array(str_replace(",", "cama", $this->input->post('ct_dev_name_1')) .','. $ubayam->star1_name .','.  $this->input->post('ct_dev_name_1_tamil') .','. $ubayam->star_tamil_name1, $this->input->post('ct_dev_name_2') .','. $ubayam->star2_name .','.  $this->input->post('ct_dev_name_2_tamil') .','. $ubayam->star_tamil_name2),
                        'contact_no'=> $this->input->post('ct_contact_no'),
                        'email'     => $this->input->post('ct_email'),
                        'address'   => $this->input->post('ct_address'),
                        'desc'      => $this->input->post('cs_desc'),
                        
                        'section'  => array(
                            array(
                                'Date<div class="sub-lbl"> தேதி</div>' => date('d/m/Y',strtotime($this->input->post('fn_date'))),
                                'Time<div class="linear-lbl"> நேரம்</div>'      => date('H:i',strtotime($this->input->post('fn_from_time'))) . ' - ' . date('H:i',strtotime($this->input->post('fn_to_time'))),
                                'Period<div class="linear-lbl"> காலம்</div>'    => ($this->input->post('fn_period') == 1) ? 'Morning / காலை' : 'Evening / மாலை',
                                'Deity<div class="linear-lbl"> தெய்வம்</div>'     => $ubayam->god_name,
                            ),
                        ),
                        
                        'tables' => array(
                            'head'  => array('God Name<div class="sub-lbl">கடவுள் பெயர்<div>', 'Prasadam Name<div class="sub-lbl">பிரசாதம்<div>','Qty x Unit Price($)<div class="sub-lbl">எண்ணிக்கை x ஒன்றின் விலை<div>', 'Amount($)<div class="sub-lbl">தொகை<div>'),
                            'body'  => $print_body,
                        ),
                    ),
                    
                );
                
                print_rec($args);            
                /*** End ***/
            }
            
        }
        else
            $this->session->set_flashdata('error', 'Billing for Ubayam Details is not added!');        

        if(empty($this->input->post('book-now')))
            redirect('billing_ubayam', 'refresh');

        else
            redirect('billing_ubayam/add/' . $this->input->post('type_id'), 'refresh');
    }

    public function archanai_insert($post) {
        $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);  

        /*
        * 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'];
        $rec_no = fill_digits( ++$rec_id, 4 );
        
        $general_setting = get_general_setting();
        $gst = $general_setting->gst;

        $print_args = array();
        /*
        * Parent table
        */

        // $names = !empty( $itm['names'] ) ? json_decode( $itm['names'], TRUE ) : array($post['input_1'], $post['input_3']);
        // $names = !empty( $post['items'][0]['names'] ) ? json_decode( $post['items'][0]['names'], TRUE ) : array(array($post['input_1'], $post['input_2']), array($post['input_3'], $post['input_4']));
        $args = array(
            'bar_rec_no'    => $rec_no,
            'bar_name_1'    => $post['ct_dev_name_1'],
            'star_id_1'     => !empty( $post['ct_star_1'] ) ? $post['ct_star_1'] : '0',
            'bar_name_2'    => $post['ct_dev_name_2'],
            'star_id_2'     => !empty( $post['ct_star_2'] ) ? $post['ct_star_2'] : '0',
            'contact_no'    => $post['ct_contact_no'],
            // 'bar_name_3'    => htmlspecialchars( substr( $post['input_5'], 3 )),
            // '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();

        /*
        * Items
        */
        $cat_rec = $cats = array();
        // Category in General Settings
        $randnos 	= rand(2222, 9999);
        $previous_itm_price = "0.00";
        
        // echo '<pre>'; print_r($_POST);
        foreach( $post['category'] as $k => $catId ) :
            $rec_nos 		= array();					
            // $names_dev 		= !empty($itm['names']) ? json_decode($itm['names'], TRUE) : array(array($post['input_1'], $post['input_2']), array($post['input_3'], $post['input_4']));
            $itemId = $post['sub_category'][$k];
            $itemQty = $post['ar_qty'][$k];
            $itemPrice = $post['ar_price'][$k];

            if ($post['daydevset'] == 1):						
                $argsday = array(
                    'name1' => $post['ct_dev_name_1'],
                    'name2' => $post['ct_dev_name_2'],
                    'star1' => !empty( $post['ct_star_1'] ) ? $post['ct_star_1'] : '0',
                    'star2' => !empty( $post['ct_star_2'] ) ? $post['ct_star_2'] : '0',
                    'cat_id' => (($general_setting->is_category == 1) ? $catId : 0),
                    'item_id' => $itemId,
                    'ref_name' => $post['daydevname'], //$itm['qty'],
                    'ref_id' => $randnos,
                    'item_qty' => $itemQty, //$itm['qty'] * $itm['price'],
                    'total_amount' => $itemPrice,
                    'ref_name_day' => $post['daydevval'],
                    'status' => 1,
                    'created_on' => $date_now,
                    'created_by' => $session_data['user_id'],
                    'sanctum_id' => ''
                );

                $this->db->insert("thiru_day_devotees", $argsday);		
            endif; 

            if( empty( $cats[$catId] ) ) :
                $this->db->select('id, category_name, tamil_name, grouping, cat_prefix, image, is_separate');
                $q = $this->db->get_where(TBL_CATEGORY, array('id' => $catId));
                $cat = $q->row_array();
                $cats[$catId] = $cat;
            else :
                $cat = $cats[$catId];
            endif;  

            $rec_no = '';
            $itmm_id = 0;
            $whre = array();
            //echo "<br> Pre Price: ".$previous_itm_price;
            $whre['bari_price']  = number_format($itemPrice, 2, '.', '');
            $whre['is_category'] = ($general_setting->is_category == 1) ? 0 : 1;
            
            if( $whre['is_category'] == 0 ) :
                // With Category for Whole Application
                //$rec_no .= $cat['cat_prefix'];
                $whre['bari_cat_id'] = $cat['id'];
            endif;
            
            if( $cat['grouping'] != '1' ) :
                // Single
                $whre['bari_item_id'] = $itemId;
                $itmm_id = $itemId;
            endif;

            // Added for Server Down Import operation
            $itm['is_cat_group'] = $cat['grouping'];

            if(empty($cat_rec[$catId][$itemId]) || ($previous_itm_price != $whre['bari_price'])) :
                $previous_itm_price = $whre['bari_price'];
                // 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);
                $this->db->last_query(); 
                $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 < $itemQty; $i++ ) :
					
                $this->db->select('prefix');
                $q 				= $this->db->get_where(TBL_ITEM, array('id' => $itemId));
                $item_prefix	= $q->row()->prefix;
                
                /*
                 * Insert by Quantity Wise
                 */
                ++$cat_rec[$cat['id']][$itmm_id];
                
                $args = array(
                    'bar_id'        => $db_id,
                    'bari_cat_id'   => (($general_setting->is_category == 1) ? $catId : 0),
                    'bari_item_id'  => $itemId,
                    'bari_qty'      => 1, //$itm['qty'],
                    'bari_price'    => $itemPrice,
                    'bari_sub_total'=> $itemPrice, //$itm['qty'] * $itm['price'],
                    'bari_god_ids'  => '',//$itm['gods'],
                    'bari_is_inventory'=> 1,//$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'   => ($item_prefix.( $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;

        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['category'] as $k => $catId ) :
            $qty 			= $post['ar_qty'][$k];
            $rec_nos 		= $args['bari_rec_no'];
            $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[$catId]) ) :
                $cat = $cats[$catId];
            else :
                $q = $this->db->get_where(TBL_CATEGORY, array('id' => $catId));
                $cat = $q->row_array();
                
                $cats[$catId] = $cat;
            endif;
            
            if( !empty($itms[$post['sub_category'][$k]]) ) :
                $item = $itms[$post['sub_category'][$k]];
            else :
                $q = $this->db->get_where(TBL_ITEM, array('id' => $post['sub_category'][$k]));
                $item = $q->row_array();
                
                $itms[$post['sub_category'][$k]] = $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['ar_price'][$k];
                
                //**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['with_names'][0][0]][] = $item;
                    $print_args['items']['group-'.$cat['id']. '-' . $item['with_names'][0][0]][0]['total_qty'] += $qty;

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

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

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

                endif;
            endforeach;     // $agods
    
            
        endforeach;

        // for( $i = 1; $i <=6; $i+=2 ) :    
        //     $q = $this->db->get_where(TBL_STAR, array('id' => $post['ct_star_1']));
        //     $star = $q->row_array();
        //     $print_args['name'][] = array('ENG'.$post['ct_dev_name_1'], $star['tamil_name']);
        // endfor;
        $q = $this->db->get_where(TBL_STAR, array('id' => $post['ct_star_1']));
        $star = $q->row_array();
        $print_args['name'][] = array('ENG'.$post['ct_dev_name_1'], $star['tamil_name']);

        $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);
        // echo '<pre>';print_r($args); exit;

    }

    public function prasadam_insert($post) {
        $date_now = date("Y-m-d H:i:s");
        $prasadam_type = $post['pr_type'];
        $session_data = $this->session->userdata( TBL_PREFIX . 'user_logged_in' );

        //Prasadam
        $q = $this->db->get_where( TBL_SERVICE, array('id' => $prasadam_type) );
        $gst_details = $q->row();
        // $gst_details = $this->get_amount_by_service_id($post['fn_type']);
    
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($post['amount']);
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        
        $q = $this->db->get_where( TBL_SERVICE, array('id' => $prasadam_type) );
        $service = $q->row_array();
        
        $q = $this->db->get_where( TBL_SERVICE_MENU, array('id' => $service['menu_name']) );
        $main_service = $q->row_array();

        //$total_amt = 0;
        // $e = explode(( strpos( $post['fn_date'], '/' ) > 0 ? '/' : '-' ), $post['fn_date']); // dd-mm-yyyy
        // $fn_date = $e[2] . '-' . $e[1] . '-' .$e[0];
        $args = array(
            'service_id'        => $prasadam_type,//$post['fn_type'],
            'star_id_1'         => !empty( $post['ct_star_1'] ) ? $post['ct_star_1'] : '0',
            'star_id_2'         => !empty( $post['ct_star_2'] ) ? $post['ct_star_2'] : '0',
            
            'bp_fn_date'        => date('Y-m-d',strtotime($post['fn_date'])),
            'bp_fn_time'		=> date("H:i:s", strtotime($post['fn_from_time'])),
            'bp_period'         => $post['fn_period'],
            'bp_dev_name_1'     => $post['ct_dev_name_1'],
            'bp_dev_name_2'     => $post['ct_dev_name_2'],

            'bp_tamil_name_1'   => htmlspecialchars( $post['ct_dev_name_1_tamil'] ),
            'bp_tamil_name_2'   => htmlspecialchars( $post['ct_dev_name_2_tamil'] ),
            'bp_contact_no'     => $post['ct_contact_no'],
            'bp_email'          => $post['ct_email'],
            /* 'bp_address_1'      => $post['address_1'],
            'bp_address_2'      => $post['ct_address'], */
            'bp_desc'           => $post['cs_desc'],
            'gst'               => $gst,
            'gst_value'         => $gst_amount,
            'bp_book_status'    => !empty( $post['book-now'] ) ? 2 : 1,
        );

        $bk_status = $args['bp_book_status'];
        $receipt_no = $post['rec_no'];
        if( empty( $receipt_no ) || ( !$is_add && $bk_status == "1"  && $post['book_status'] == "2" ) ) :
            
            /*
            * Get last Receipt ID
            */
            $wh = array(
                'service_id'    => $service['id'],
                'bp_book_status'=> $bk_status
            );
            
            $receipt_no = generate_rec_no(TBL_BP, $wh);
            $args['bp_rec_no'] = $receipt_no;   
        endif;

        $is_add = TRUE;
        $db_id  = $is_add ? '' : $segments[3];

        if( $is_add ) :
            // Insert 

            $args['created_on'] = $date_now;
            $args['created_by'] = $session_data['user_id'];

            if( $bk_status == "2" ) :
                // Booked Now
                $args['updated_on'] = $date_now;
                $args['updated_by'] = $session_data['user_id'];
            endif;
            
            $this->db->insert( TBL_BP, $args );
            $db_id = $this->db->insert_id();

        elseif( !empty( $db_id ) ):
            // Update
            $args['updated_on'] = $date_now;
            $args['updated_by'] = $session_data['user_id'];

            $this->db->update( TBL_BP, $args, array( 'id' => $db_id ) );

        endif;

        /*
         * Items
         */
        // Set status for removed Items
        if( !empty( $post['removed-items'] ) ) :
            
            $e = explode("-", trim($post['removed-items'], '-'));
            foreach( $e as $k => $rm_id ) :
                $this->db->update( TBL_BPI, array('status' => 2 ), array( 'id' => $rm_id ) );
            endforeach;
            
        endif;
        
        $gods = $prasadams= $print_body = array();
        $deity = $this->input->post('pr_deity');
        $qty = $this->input->post('pr_qty');
        $price = $this->input->post('pr_price');
        $prasadam = $this->input->post('pr_prasadam');

        foreach( $post['pr_deity'] as $k => $god_id ) :
            $sub_total = $post['pr_qty'][$k] * $post['pr_price'][$k];
            //$total_amt += $sub_total;
            
            $args = array(
                'god_id'        => $post['pr_deity'][$k],
                'prasadam_id'   => $post['pr_prasadam'][$k],
                'bpi_qty'       => $post['pr_qty'][$k],
                'bpi_price'     => $post['pr_price'][$k],
                'bpi_sub_total' => $sub_total,
            );
            
            if( !array_key_exists( $args['god_id'], $gods ) ) :
                $q  =$this->db->get_where( TBL_GOD_NAME, array('id' => $args['god_id']) );
                $gods[$args['god_id']] = $q->row_array();
            endif;
            
            if( !array_key_exists( $args['prasadam_id'], $prasadams ) ) :
                $q  =$this->db->get_where( TBL_PRASADAM, array('id' => $args['prasadam_id']) );
                $prasadams[$args['prasadam_id']] = $q->row_array();
            endif;
            
            $print_body[] = array(
                (!empty($args['god_id']) ? ($gods[$args['god_id']]['name'] . ((!empty($gods[$args['god_id']]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $gods[$args['god_id']]['tamil_name'] .'</span>' : '')) : '<center> - </center>'),
                $prasadams[$args['prasadam_id']]['name'] . ((!empty($prasadams[$args['prasadam_id']]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $prasadams[$args['prasadam_id']]['tamil_name'] .'</span>' : ''),
                '<div style="text-align: right;">'.$args['bpi_qty'] . ' x '. $args['bpi_price'] . '</div>',
                '<div style="text-align: right;">'.number_format( $args['bpi_qty']*$args['bpi_price'], 2 ).'</div>',
            );
            
            if( empty( $post['pr_id'][$k] ) ) :
                // Insert
                $args['bp_id']      = $db_id;
                $args['created_on'] = $date_now;
                $args['created_by'] = $session_data['user_id'];

                $this->db->insert( TBL_BPI, $args );
                
            else :
                // Update
                
                $args['updated_on'] = $date_now;
                $args['updated_by'] = $session_data['user_id'];

                $this->db->update( TBL_BPI, $args, array( 'id' => $post['pr_id'][$k], 'bp_id' => $db_id ) );
                
            endif;

        endforeach;
        
        $args = array(
            'bp_amount'     => $post['pr_amount'],
            'bp_paid_amount'=> $post['pr_amount'],//$post['paid_amount'],
            'bp_rec_no'     => $receipt_no,
            'bp_pay_status' => 3,//$post['amount'] >= $total_amt ? '3' : ( $paid_amt > 0 ? '2' : '1' ), // Always FULL payment
        );
        
        $this->db->update( TBL_BP, $args, array( 'id' => $db_id ) );
        
        // $Prasadam = $this->get_by_id($db_id);
        $q  =$this->db->get_where( TBL_BP, array('id' => $db_id) );
        $Prasadam = $q->row();
        /*
         * Payments
         */
        
        // Drop all previous payments
        #$this->db->delete( TBL_PAY, array( 'pay_ref_type'  => 15, 'pay_ref_id'    => $db_id ) );
        
        if(empty(( $post['book-now'] )) && ($is_add || (!empty($db_id)))) {
            $paid_hidden_id  = $this->input->post('paid_hidden_id'); 
            if(!empty($paid_hidden_id)) :
                $paidType = $this->ubayam_model->delete_payment_by_paid_id($paid_hidden_id);
            endif;
  
            foreach( $post['pay_type'] as $pay_type_id => $pay_amt ) :
                if( empty( $pay_amt ) ) :
                    // Skip empty amounts ..
                    continue;
                endif;

                $this->db->select('slug');
                $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $pay_type_id) );
                $prow = $q->row_array();
               
                $pay_details = array();
                if( $prow['slug'] == 'cheque' && !empty($pay_amt) ) :
                   // Cheque
                   $e = explode('-', $post['chq_date']);
                   $pay_details = array(
                       'name'   => $post['chq_bnk_name'],
                       'no'   => $post['chq_no'],
                       'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                   );
                endif;
               
                $pay_details = json_encode( $pay_details );                
                
                $args = array(
                    'pay_ref_type'  => 15, // For Billing Prasadam
                    'pay_ref_id'    => $db_id, // Main ID
                    'pay_type_id'   => $pay_type_id,
                    'pay_amount'    => $post['pr_amount'],//$pay_amt,
                    'pay_details'   => $pay_details,
                    'created_on'    => $date_now,   //(( empty( $receipt_no ) || ( !$is_add && $bk_status == "1"  && $post['book_status'] == "2" ) ) ? date('Y-m-d H:i:s') : $Prasadam->created_on),
                    'created_by'    => $session_data['user_id'],
                );
                
                // Insert
                $this->db->insert( TBL_PAY, $args );

            endforeach;
        }
        //Print
        if(empty(( $post['book-now'] )) && ($is_add || (!empty($db_id) && ($post['hidden_amount'] < $post['amount'] || $post['book_status'] == 2)))) {    
            /*** To Print Receipt - Start ***/
            $prefix = get_general_setting()->prefix;
			
			$this->db->where('id', $post['star_1']);
			$str1 = $this->db->get(TBL_STAR)->row();
			// $star1 = $str1->name.' / '.$str1->tamil_name;
			$star1 = $str1->tamil_name;

			$this->db->where('id', $post['star_2']);
			$str2 = $this->db->get(TBL_STAR)->row();
			//$star2 = $str2->name.' / '.$str2->tamil_name;
			$star2 = $str2->tamil_name;
            $cdate = ''; $cdate = date('d-m-Y h:i:sa', strtotime($Prasadam->created_on));
            $args = array(
                'type'      => '6', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
                'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,
                'title'     => 'Prasadam - ' . $gst_details->name,
                'amount'    => array($post['pr_amount']),
                'gst'       => $gst_details->gst,
                'copy'      => TRUE,
                'printType' => TRUE,
                'fn_type' => 'prasadam',
                'created_on' => $cdate,
                /* 'data'      => array(
                    // Type = 1 && 3 
                    'name'      => array($post['dev_name_1'], $post['tamil_name_1']),array($post['dev_name_1'], $post['tamil_name_1'], $post['dev_name_2'], $post['tamil_name_2']),
                    'contact_no'=> $post['contact_no'],
                    'email'     => $post['email'],
                    'address'   => $post['address_1'],
                    'desc'      => $post['desc'],
                ), */
                
                'data'      => array( 
                    
                    // Type = 6
                    'fields'  => array(
						'Name1/Star1<div class="sub-lbl">பெயர்1/நட்சத்திரம்1<div>' => $post['ct_dev_name_1'] . ' / ' . $star1, // . tamil( $prasadam->bp_tamil_name_1, 'border: none; font-weight: bold; font-size: 24px;' ),
						'Name2/Star2<div class="sub-lbl">பெயர்2/நட்சத்திரம்2<div>' => ($post['ct_dev_name_2']) ? $post['ct_dev_name_2'] .  ' / ' . $star2 : "",
                        /* 'Tamil Name<div class="sub-lbl">தமிழ் பெயர்<div>'    => tamil( $post['tamil_name_1'], 'border: none; font-weight: bold; font-size: 24px;' ), */
                        'Date<div class="sub-lbl">தேதி<div>' => str_replace('-', '/', $post['fn_date'] ),
                        'Period<div class="sub-lbl">காலம்<div>'        => $post['fn_period'] == '1' ? 'Morning  / காலை' : 'Evening / மாலை',
                        'Time<div class="sub-lbl">நேரம்<div>' => $post['fn_from_time'],						
                        'Email ID<div class="sub-lbl">மின்னஞ்சல்<div>'      => $post['ct_email'],
						'Contact No<div class="sub-lbl">தொடர்பு எண்<div>'    => $post['ct_contact_no'],
                    ),
                    
                    'tables' => array(
                        
                        'head'  => array('God Name<div class="sub-lbl">கடவுள் பெயர்<div>', 'Prasadam Name<div class="sub-lbl">பிரசாதம்<div>','Qty x Unit Price($)<div class="sub-lbl">எண்ணிக்கை x ஒன்றின் விலை<div>', 'Amount($)<div class="sub-lbl">தொகை<div>'),
                        'body'  => $print_body,
        
                    ),
                    
                ),
                
            );
            // echo '<pre>'; print_r($args); print_r($post); exit;
            print_rec($args);            
            /*** End ***/  
                     
        }


    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $actions = $this->actions();
        $data['form_action'] = $actions['update'] . '/' . $id;
        
        $data['ubayam'] = $this->ubayam_model->get_by_id($id);
        $data['paid_amount'] = $this->ubayam_model->total_paid_amount($data['ubayam']->type_id,$data['ubayam']->id);
        $data['devotees'] = $this->ubayam_model->get( TBL_DEVOTEE, '', array('order_by' => 'name') );
        $data['deity'] = $this->ubayam_model->get( TBL_GOD_NAME, '', array('order_by' => 'name') );
        $data['fn_types'] = $this->ubayam_model->get( TBL_SERVICE, array( 'menu_name' => $data['ubayam']->type_id ), array('order_by' => 'name') );
        $data['stars'] = $this->ubayam_model->get( TBL_STAR, '', array('order_by' => 'name') );
        $data['ptypes'] = $this->ubayam_model->get( TBL_PAY_TYPE );
        $data['prasadams'] = $this->ubayam_model->get( TBL_PRASADAM, '', array('order_by' => 'name') );
        $data['items'] = $this->ubayam_model->get_prasadam_json($id);
        $data['title'] = 'Ubayam';
        $this->render($data, 'billing/ubayam/edit');
    }
    
    public  function update($id){
        if (empty($id)) {
            show_400_error();
        }
       
        $ubayam = $this->ubayam_model->get_by_id($id);
        $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('fn_type'));
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($this->input->post('cs_amount'));
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        
        $update = array(
            'type_id' => $this->input->post('type_id'),
            'service_id' => $this->input->post('fn_type'),
            'date' => date('Y-m-d',strtotime($this->input->post('fn_date'))),
            'from_time' => date('H:i',strtotime($this->input->post('fn_from_time'))),
            'to_time' => date('H:i',strtotime($this->input->post('fn_to_time'))),
            'deity_id' => $this->input->post('fn_deity'),
            'period' => $this->input->post('fn_period'),
            'devotee_name1' => $this->input->post('ct_dev_name_1'),
            'tamil_name1' => htmlspecialchars( $this->input->post('ct_dev_name_1_tamil') ),
            'devotee_name2' => $this->input->post('ct_dev_name_2'),
            'tamil_name2' => htmlspecialchars( $this->input->post('ct_dev_name_2_tamil') ),
            'star1' => $this->input->post('ct_star_1'),
            'star2' => $this->input->post('ct_star_2'),
            'contact_no' => $this->input->post('ct_contact_no'),
            'email' => $this->input->post('ct_email'),
            'address' => $this->input->post('ct_address'),
            'desc' => $this->input->post('cs_desc'),
            'amount' => $this->input->post('cs_amount'),
            'gst' => $gst,
            'gst_value' => $gst_amount,
            'book_status' => (!empty($this->input->post('book-now'))) ? 2 : 1,
            'url_key' => $this->get_ubayam_url_key($this->input->post('ct_dev_name_1')),
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
        
        $receipt_no = $ubayam->receipt_no;
        $bk_status = $update['book_status'];
        
        if( empty( $receipt_no ) || ($bk_status == "1" && $this->input->post('book_status') == "2" ) ) :
            /*
            * Get last Receipt ID
            */
            $wh = array(
                'service_id'    => $update['service_id'],
                'book_status'   => $bk_status
            );
            
            $receipt_no = generate_rec_no(TBL_BILL_UBAYAM, $wh);
            $update['receipt_no'] = $receipt_no;   
            $created_date = date('Y-m-d H:i:s');
            
            
        else :
            $created_date = $ubayam->created_on;
        endif;
        
        $affected_rows = $this->ubayam_model->update($update,$id);
        
        if($affected_rows > 0) {
            $deity = $this->input->post('pr_deity');
            $qty = $this->input->post('pr_qty');
            $price = $this->input->post('pr_price');
            $prasadam = $this->input->post('pr_prasadam');
            $pr_id = $this->input->post('pr_id');
            
            if(!empty($deity)) {
                foreach( $deity as $k => $deity_id ) {
                    $sub_total = $qty[$k] * $price[$k];
                    if(empty($pr_id[$k])) {
                        $insert = array(
                            'ubayam_id'   => $id,
                            'deity_id'      => $deity_id,
                            'prasadam'      => $prasadam[$k],
                            'quantity'      => $qty[$k],
                            'price'         => $price[$k],
                            'sub_total'     => $sub_total,
                            'status'        => 1,
                            'url_key'       => $this->get_ubayam_url_key($prasadam[$k]),
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => date('Y-m-d H:i:s')
                        );
                        $this->ubayam_model->insert_prasadam($insert);
                    } else {
                        $update = array(
                            'ubayam_id'   => $id,
                            'deity_id'      => $deity_id,
                            'prasadam'      => $prasadam[$k],
                            'quantity'      => $qty[$k],
                            'price'         => $price[$k],
                            'sub_total'     => $sub_total,
                            'status'        => 1,
                            'url_key'       => $this->get_ubayam_url_key($prasadam[$k]),
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => date('Y-m-d H:i:s')
                        );
                        $this->ubayam_model->update_prasadam_by_id($update,$pr_id[$k]);
                    }
                }
            }
            
            if(empty($this->input->post('book-now'))) {
                #$paidtype = $this->ubayam_model->delete_paid_type($this->input->post('type_id'),$id);
                $this->session->set_flashdata('success', 'Billing for Ubayam Details is updated successfully');
                
                $paid_hidden_id = $this->input->post('paid_hidden_id');
                if(!empty($paid_hidden_id)) :
                    $paidtype = $this->ubayam_model->delete_payment_by_paid_id($paid_hidden_id);
                endif;
                
                $pay_type = $this->input->post('pay_type');
                foreach( $pay_type as $key => $value ) {
                    if($value > 0 && $value != '') {
                        
                        $this->db->select('slug');
                        $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $key) );
                        $prow = $q->row_array();
                       
                        $pay_details = array();
                        if( $prow['slug'] == 'cheque' && !empty($value) ) :
                            // Cheque
                            $e = explode('-', $this->input->post('chq_date'));
                            $pay_details = array(
                                'name'   => $this->input->post('chq_bnk_name'),
                                'no'   => $this->input->post('chq_no'),
                                'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                            );
                        endif;
                       
                        $pay_details = json_encode( $pay_details );
                   
                        $insert = array(
                            'pay_ref_type'  => 17,
                            'pay_ref_id'    => $id,
                            'pay_type_id'   => $key,
                            'pay_amount'    => trim($value),
                            'pay_details'   => $pay_details,
                            'status'        => 1,
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => $created_date
                        );
                        $this->ubayam_model->insert_payment($insert);
                    }
                }
                
                if(($this->input->post('hidden_amount') < $this->input->post('cs_amount')) || $ubayam->book_status == 2) {                
                    /*** To Print Receipt - Start ***/
                    $service_menu = $this->login_details_model->get_service_menu_by_id($this->input->post('type_id'));
                    $prefix = get_general_setting()->prefix;
                    
                    $prasadam = $this->ubayam_model->get_prasadam_by_id($id);
                
                    $gods = $prasadams= $print_body = array();
                    foreach( $prasadam as $k => $details ) :
                    
                        if( !array_key_exists( $details->deity_id, $gods ) ) :
                            $q  =$this->db->get_where( TBL_GOD_NAME, array('id' => $details->deity_id) );
                            $gods[$details->deity_id] = $q->row_array();
                        endif;
                        
                        if( !array_key_exists( $details->prasadam, $prasadams ) ) :
                            $q  =$this->db->get_where( TBL_PRASADAM, array('id' => $details->prasadam) );
                            $prasadams[$details->prasadam] = $q->row_array();
                        endif;
                        
                        $print_body[] = array(
                            (!empty($details->deity_id) ? ($gods[$details->deity_id]['name'] . ((!empty($gods[$details->deity_id]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $gods[$details->deity_id]['tamil_name'] .'</span>' : '')) : '<center> - </center>'),
                            $prasadams[$details->prasadam]['name'] . ((!empty($prasadams[$details->prasadam]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $prasadams[$details->prasadam]['tamil_name'] .'</span>' : ''),
                            '<div style="text-align: right;">'.$details->quantity . ' x ' . $details->price .'</div>',
                            '<div style="text-align: right;">'.number_format( $details->quantity*$details->price, 2 ).'</div>',
                        );
                    endforeach;
                    $cdate = ''; $cdate = date('d-m-Y h:i:sa', strtotime($ubayam->created_on));
                    $args = array(
                        'type'      => '1', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
                        'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,
                        'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
                        'amount'    => array($this->input->post('paid_amount')),
                        'gst'       => $gst_details->gst,
                        'printType' => TRUE,
                        'created_on' => $cdate,
                        'fn_type' => 'ubayam',

                        'data'      => array(
                            // Type = 1 && 3 
                            'name'      => array(str_replace(",", "cama", $this->input->post('ct_dev_name_1')) .','. $ubayam->star1_name  .','.  $this->input->post('ct_dev_name_1_tamil') .','. $ubayam->star_tamil_name1, $this->input->post('ct_dev_name_2') .','. $ubayam->star2_name .','.  $this->input->post('ct_dev_name_2_tamil') .','. $ubayam->star_tamil_name2),
                            'contact_no'=> $this->input->post('ct_contact_no'),
                            'email'     => $this->input->post('ct_email'),
                            'address'   => $this->input->post('ct_address'),
                            'desc'      => $this->input->post('cs_desc'),
                            
                            'section'  => array(
                                array(
                                    'Date<div class="sub-lbl"> தேதி</div>' => date('d/m/Y',strtotime($this->input->post('fn_date'))),
                                    'Time<div class="linear-lbl"> நேரம்</div>'      => date('H:i',strtotime($this->input->post('fn_from_time'))) . ' - ' . date('H:i',strtotime($this->input->post('fn_to_time'))),
                                    'Period<div class="linear-lbl"> காலம்</div>'    => ($this->input->post('fn_period') == 1) ? 'Morning / காலை' : 'Evening / மாலை',
                                    'Deity<div class="linear-lbl"> தெய்வம்</div>'     => ((!empty($this->input->post('fn_deity'))) ? $this->ubayam_model->get_deity_name($this->input->post('fn_deity'))->name : ''),
                                ),
                            ),
                            
                            'tables' => array(
                                'head'  => array('God Name<div class="sub-lbl">கடவுள் பெயர்<div>', 'Prasadam Name<div class="sub-lbl">பிரசாதம்<div>','Qty x Unit Price($)<div class="sub-lbl">எண்ணிக்கை x ஒன்றின் விலை<div>', 'Amount($)<div class="sub-lbl">தொகை<div>'),
                                'body'  => $print_body,
                            ),
                        ),
                        
                    );
                    
                    print_rec($args);            
                    /*** End ***/
                }
                
                 /*** To Insert Refund Amount - Start ***/
                /* if($this->input->post('hidden_amount') > $this->input->post('cs_amount')) {
                    $insert = array(
                        'menu_id' => $this->input->post('type_id'),
                        'service_id' => $this->input->post('fn_type'),
                        'auto_id' => $id,
                        'pay_type_id' => 1,
                        'amount' => ($this->input->post('hidden_amount') - $this->input->post('cs_amount')),
                        'created_on' => date('Y-m-d H:i:s'),
                        'created_by' => $this->user_data['user_id']
                    );
                    $this->login_details_model->insert_refund_amount($insert);
                    
                } */
                /*** End ***/
            
            } else {
                $this->session->set_flashdata('success', 'Billing for Ubayam Details is booked successfully');
            }
            
            /*
             * Items
             */
            // Set status for removed Items
            if( !empty($this->input->post('removed-items')) ) :
                $e = explode("-", trim($this->input->post('removed-items'), '-'));
                foreach( $e as $k => $rm_id ) :
                    $update = array('status' => 2);
                    $this->ubayam_model->update_prasadam_by_id($update,$rm_id);
                endforeach;
            endif;
           
        } else 
            $this->session->set_flashdata('error', 'Billing for Ubayam Details is not updated!');
        
        if(empty($this->input->post('book-now')))
            redirect('billing_ubayam', 'refresh');

        else
            redirect('billing_ubayam/add/' . $this->input->post('type_id'), 'refresh');
    }
    
    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['ubayam'] = $this->ubayam_model->get_by_id($id);
        $data['paid_amount'] = $this->ubayam_model->total_paid_amount($data['ubayam']->type_id,$data['ubayam']->id);
        $data['prasadams'] = $this->ubayam_model->get_prasadam_by_id($id);
        $data['ptypes'] = $this->ubayam_model->get_paid_type_by_id($data['ubayam']->type_id,$id);
        $data['title'] = 'Ubayam';
        $this->render($data, 'billing/ubayam/view');
    }
    
    public function delete($id = '', $menu_id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $update = array ( 
            'amount' => 0,
            'del_reason' => $this->input->post('hidden_del_reason'),
            'status' => 2,
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );

        if ($this->ubayam_model->update($update,$id) > 0) {
            $this->session->set_flashdata('success', 'Billing for Ubayam is deleted successfully');
            $ubayam = $this->ubayam_model->get_by_id($id);
            
            $update = array ( 
                'pay_amount' => 0,
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            
            $this->ubayam_model->update_paid_type($update,$ubayam->type_id,$id);
            $this->ubayam_model->update_refund(array('status' => 2),$ubayam->type_id,$id);
            
            $update = array(
                'sub_total' => 0,
                'status' => 2,
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            $this->ubayam_model->update_prasadam($update,$id);
        }
        
        else 
            $this->session->set_flashdata('error', 'Billing for Ubayam is not deleted!');
        
        redirect( 'billing_ubayam/index/' . $menu_id, 'refresh');
    }
    
    public function ajax() {
        $results =  $this->ubayam_model->ajax();
        echo json_encode( $results );
    }
    
    public function get_prasadam_price() {
        $data = $this->ubayam_model->get_prasadam_price($_POST['id']);
        echo json_encode($data);
        exit(0);
    }
    
    public function print_list($id,$menu_id) {
        $ubayam = $this->ubayam_model->get_by_id($id);
        $prasadam = $this->ubayam_model->get_prasadam_by_id($id);
	    $paymentDetails = $this->ubayam_model->get_payment_date($id);
        
        /*** To Print Receipt - Start ***/
        $service_menu = $this->login_details_model->get_service_menu_by_id($ubayam->type_id);
        $gst_details = $this->login_details_model->get_amount_by_service_id($ubayam->service_id);
        $prefix = get_general_setting()->prefix;
                
        $gods = $prasadams= $print_body = array();
        foreach( $prasadam as $k => $details ) :
        
            if( !array_key_exists( $details->deity_id, $gods ) ) :
                $q  =$this->db->get_where( TBL_GOD_NAME, array('id' => $details->deity_id) );
                $gods[$details->deity_id] = $q->row_array();
            endif;
            
            if( !array_key_exists( $details->prasadam, $prasadams ) ) :
                $q  =$this->db->get_where( TBL_PRASADAM, array('id' => $details->prasadam) );
                $prasadams[$details->prasadam] = $q->row_array();
            endif;
            
            $print_body[] = array(
                (!empty($details->deity_id) ? ($gods[$details->deity_id]['name'] . ((!empty($gods[$details->deity_id]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $gods[$details->deity_id]['tamil_name'] .'</span>' : '')) : '<center> - </center>'),
                $prasadams[$details->prasadam]['name'] . ((!empty($prasadams[$details->prasadam]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $prasadams[$details->prasadam]['tamil_name'] .'</span>' : ''),
                '<div style="text-align: right;">'.$details->quantity . ' x ' . $details->price .'</div>',
                '<div style="text-align: right;">'.number_format( $details->quantity*$details->price, 2 ).'</div>',
            );
        endforeach;
        
        $args = array(
            'type'      => '1', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
            'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $ubayam->receipt_no,
            'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
            'amount'    => array($ubayam->amount),
            'gst'       => $gst_details->gst,
            'status'    => $ubayam->status,
            'printType' => TRUE,
	    	'payment_date' => date('d/m/Y h:i A',strtotime($paymentDetails[0]['created_on'])),
            
            'data'      => array(
                // Type = 1 && 3 
                'name'      => array(str_replace(",", "cama", $ubayam->devotee_name1) .','. $ubayam->star1_name  .','.  $ubayam->tamil_name1 .','. $ubayam->star_tamil_name1 , $ubayam->devotee_name2 .','. $ubayam->star2_name  .','.  $ubayam->tamil_name2 .','. $ubayam->star_tamil_name2 ),
                'contact_no'=> $ubayam->contact_no,
                'email'     => $ubayam->email,
                'address'   => $ubayam->address,
                'desc'      => $ubayam->desc,
                
                'section'  => array(
                    array(
                        'Date<div class="sub-lbl"> தேதி</div>' => date('d/m/Y',strtotime($ubayam->date)),
                        'Time<div class="linear-lbl"> நேரம்</div>'      => date('H:i',strtotime($ubayam->from_time)) . ' - ' . date('H:i',strtotime($ubayam->to_time)),
                        'Period<div class="linear-lbl"> காலம்</div>'    => ($ubayam->period == 1) ? 'Morning / காலை' : 'Evening / மாலை',
                        'Deity<div class="linear-lbl"> தெய்வம்</div>'     => $ubayam->god_name,
                    ),
                ),
                
                'tables' => array(
                    'head'  => array('God Name<div class="sub-lbl">கடவுள் பெயர்<div>', 'Prasadam Name<div class="sub-lbl">பிரசாதம்<div>','Qty x Unit Price($)<div class="sub-lbl">எண்ணிக்கை x ஒன்றின் விலை<div>', 'Amount($)<div class="sub-lbl">தொகை<div>'),
                    'body'  => $print_body,
                ),
            ),
            
        );
        
		//echo "<pre>";print_r($args);die;
        if(print_rec($args))
            $this->session->set_flashdata('success', 'Receipt has been printed successfully');
        
        else 
            $this->session->set_flashdata('error', 'Receipt has not been printed!');
            
        /*** End ***/
        
        redirect( 'billing_ubayam/index/' . $menu_id, 'refresh');
    }
	
	function ubayam_bill_amount() {
		$display_pole_set 	= get_display_pole_data();
		$amount 			=  $_POST['amount'];
		//$this->session->set_flashdata('bill_paid_amount', $amount);
		//DISPLAY POLE TEXT CONTENT
		if($display_pole_set['pole_setting']['status'] == 1){
			exec("mode ".$display_pole_set['port_val']['value'].": BAUD=9600 PARITY=n DATA=8 STOP=1 to=off dtr=off rts=off");
			$fp =fopen($display_pole_set['port_val']['value'], "w+");
			fwrite($fp,"\x0c");
			fwrite($fp, "UBAYAM\n\rTOTAL : $".$_POST['amount']); //write string to serial
		}
	}
    
} 
?>