<?php
/*

 * Author       : Jai K

 * Purpose      : Model for Billing Abishegam

 * Created On   : 2016-07-30 18:40

*/

class Abishegam_Model extends CI_Model
{

    function __construct()
    {

        parent::__construct();

    }

    function get($tbl_name, $where = array() , $args = array())
    {
        if (!is_array($where)) { $where = array(); }

        if(isset($where) && !empty($where)) {
            $where['status'] = 1;
        } else {
            $where = array();
            $where['status'] = 1;
        }

        if ($tbl_name == 'thiru_payment_types'):

            $where['menu_id'] = 0;

        endif;

        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_by_id($id)
    {

        $this
            ->db
            ->where('id', $id);

        return $this
            ->db
            ->get(TBL_BA)
            ->row();

    }

    function get_by_print($id)
    {

        $this
            ->db
            ->select('self.*, self.status AS status, star1.name AS star_name_1, star1.tamil_name as star_tamil_name1, star2.name AS star_name_2, star2.tamil_name AS star_tamil_name2');

        $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');

        $this
            ->db
            ->where('self.id', $id);

        return $this
            ->db
            ->get(TBL_BA . ' AS self')
            ->row();

    }

    function get_all($id = '', $where = array())
    {

        if (!empty($id)):

            $where['self.id'] = $id;

        endif;

        #$where['self.status'] = 1;
        $where['self.ba_book_status'] = 1;

        $this
            ->db
            ->select('self.*, self.status AS status, serv.name AS service_name, serv.amount as ser_amount, serv.prefix, god.name AS god_name, star1.name AS star_name_1, star1.tamil_name as star_tamil_name1, star2.name AS star_name_2, star2.tamil_name AS star_tamil_name2');

        $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');

        $this
            ->db
            ->order_by('self.ba_rec_no', 'desc');

        $q = $this
            ->db
            ->get_where(TBL_BA . ' AS self', $where);

        //echo $this->db->last_query(); die;
        return $q->result_array();

    }

    function get_all_booked_details($id = '', $where = array())
    {

        if (!empty($id)):

            $where['self.id'] = $id;

        endif;

        $this
            ->db
            ->select('self.*, self.status AS status, serv.name AS service_name, serv.amount as ser_amount, 

		serv.prefix, god.name AS god_name, star1.name AS star_name_1, star2.name AS star_name_2, star1.tamil_name as star_tamil_name1,

		 star2.tamil_name AS star_tamil_name2');

        $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');

        $this
            ->db
            ->order_by('self.id', 'desc');

        $q = $this
            ->db
            ->get_where(TBL_BA . ' AS self', $where);

        return $q->result_array();

    }

    function get_items($ba_id)
    {

        $where['self.ba_id'] = $ba_id;

        $where['self.status'] = 1;

        $this
            ->db
            ->select('self.*, self.id AS id, self.status AS status, god.name AS god_name, pras.name AS prasadam_name');

        $this
            ->db
            ->join(TBL_GOD_NAME . ' AS god', 'god.id = self.god_id', 'left');

        $this
            ->db
            ->join(TBL_PRASADAM . ' AS pras', 'pras.id = self.prasadam_id', 'left');

        $q = $this
            ->db
            ->get_where(TBL_BAI . ' AS self', $where);

        return $q->result_array();

    }

    function get_payments($ba_id)
    {

        $where['self.pay_ref_type'] = 1; // Billing Abishegam
        $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 manipulate()
    {

        $post = $this
            ->input
            ->post(); #echo '<pre>';print_r($post);exit;
        $date_now = date("Y-m-d H:i:s");

        $session_data = $this
            ->session
            ->userdata(TBL_PREFIX . 'user_logged_in');

        $segments = $this
            ->uri->segments;

        $page = $segments[2];

        $is_add = $page == 'add' || $page == 'insert' ? true : false;

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

        $service_id = $is_add ? $segments[3] : '';

        //echo "<pre>Data: "; print_r( $post ); die;
        

        $gst_details = $this->get_amount_by_service_id($post['fn_type']);

        $prefix = get_general_setting()->prefix;

        if ($gst_details->gst == 1)
        {

            $gst = get_general_setting()->gst;

            $gst_amount = ($gst / 100) * ($post['cs_amount']);

        }
        else
        {

            $gst = '0.00';

            $gst_amount = '0.00';

        }

        $q = $this
            ->db
            ->get_where(TBL_SERVICE, array(
            'id' => $post['fn_type']
        ));

        $service = $q->row_array();

        $q = $this
            ->db
            ->get_where(TBL_SERVICE_MENU, array(
            'id' => $service['menu_name']
        ));

        $main_service = $q->row_array();

        $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' => $post['fn_type'],

            'god_id' => !empty($post['fn_deity']) ? $post['fn_deity'] : '0',

            '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',

            'ba_fn_from_date' => $fn_date . ' ' . $post['fn_from_time'],

            'ba_fn_to_date' => $fn_date . ' ' . $post['fn_to_time'],

            'ba_period' => $post['fn_period'],

            'ba_name_1' => $post['ct_dev_name_1'],

            'ba_tamil_name_1' => htmlspecialchars($post['ct_dev_name_1_tamil']) ,

            'ba_name_2' => $post['ct_dev_name_2'],

            'ba_tamil_name_2' => htmlspecialchars($post['ct_dev_name_2_tamil']) ,

            'ba_contact_no' => $post['ct_contact_no'],

            'ba_email' => $post['ct_email'],

            'ba_address' => $post['ct_address'],

            'ba_desc' => $post['cs_desc'],

            'gst' => $gst,

            'gst_value' => $gst_amount,

            'ba_book_status' => !empty($post['book-now']) ? 2 : 1,

            'ba_amount' => $post['ab_amount']//$post['cs_amount'],

        );

        if (empty($post['book-now'])):

            // Returned | Extra items Added
            $args['ba_paid_amount'] = $post['cs_amount'];

        endif;

        $receipt_no = $post['rec_no'];

        if (empty($receipt_no) || (!$is_add && $args['ba_book_status'] == "1" && $post['book_status'] == "2")):

            /*
            
            * Get last Receipt ID
            
            */

            $wh = array(

                'service_id' => $service['id'],

                'ba_book_status' => $args['ba_book_status']

            );

            $receipt_no = generate_rec_no(TBL_BA, $wh);

            $args['ba_rec_no'] = $receipt_no;

        endif;

        if ($is_add):

            // Insert
            $args['ba_booked_date'] = $date_now;

            $args['created_on'] = $date_now;

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

            if ($args['ba_book_status'] == "2"):

                // Booked Now
                $args['updated_on'] = $date_now;

                $args['updated_by'] = $session_data['user_id'];

            endif;

            /*$receipt_no = '0001';
            
            $services = $this->service_type_exists($post['fn_type']);
            
            if($services->num_rows() > 0) {
            
                $last_receipt_no = $services->row()->ba_rec_no;
            
                $last_no = (int)$last_receipt_no;
            
                $receipt_no = (($last_no + 1)  > 9999) ? ($last_no + 1)  : sprintf('0%03d', ($last_no + 1) );
            
            }*/

            $this
                ->db
                ->insert(TBL_BA, $args);

            //echo $this->db->last_query(); exit;
            $db_id = $this
                ->db
                ->insert_id();

        elseif (!empty($db_id)):

            // Update
            if ($post['book_status'] == 2):

                $args['created_on'] = $date_now;

            endif;

            $args['updated_on'] = $date_now;

            $args['updated_by'] = $session_data['user_id'];

            $this
                ->db
                ->update(TBL_BA, $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_BAI, array(
                    'status' => 2
                ) , array(
                    'id' => $rm_id
                ));

            endforeach;

        endif;

        //Prasadam
        $prasadam_res = $this->prasadam_insert($post);
        sleep(5);

        // foreach ($post['pr_deity'] as $k => $god_id):

        //     $sub_total = $post['pr_qty'][$k] * $post['pr_price'][$k];

        //     $args = array(

        //         'god_id' => $post['pr_deity'][$k],

        //         'prasadam_id' => $post['pr_prasadam'][$k],

        //         'bai_qty' => $post['pr_qty'][$k],

        //         'bai_price' => $post['pr_price'][$k],

        //         'bai_sub_total' => $sub_total,

        //     );

        //     if (empty($post['pr_id'][$k])):

        //         // Insert
        //         $args['ba_id'] = $db_id;

        //         $args['created_on'] = $date_now;

        //         $args['created_by'] = $session_data['user_id'];

        //         $this
        //             ->db
        //             ->insert(TBL_BAI, $args);

        //     else:

        //         // Update
        //         $args['updated_on'] = $date_now;

        //         $args['updated_by'] = $session_data['user_id'];

        //         $this
        //             ->db
        //             ->update(TBL_BAI, $args, array(
        //             'id' => $post['pr_id'][$k],
        //             'ba_id' => $db_id
        //         ));

        //     endif;

        // endforeach;

        $abishegam = $this->get_by_id($db_id);

        /*
        
         * Payments
        
        */

        # if(empty(( $post['book-now'] )) && ($is_add || (!empty($db_id) && ($post['hidden_amount'] < $post['cs_amount'] || $post['book_status'] == 2)))) {
        if (empty(($post['book-now'])) && ($is_add || (!empty($db_id))))
        {

            $paid_hidden_id = $post['paid_hidden_id'];

            if (!empty($paid_hidden_id)):

                $paidtype = $this->delete_payment_by_paid_id($paid_hidden_id);

            endif;

            $pay_str = '';

            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' => 1, // For Billing Abishegam
                    'pay_ref_id' => $db_id, // Main ID
                    'pay_type_id' => $pay_type_id,

                    'pay_amount' => $post['ab_amount'], //$pay_amt,

                    'pay_details' => $pay_details,

                    'created_on' => $date_now,

                    'created_by' => $session_data['user_id'],

                );

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

            endforeach;

        }

        if (empty(($post['book-now'])) && ($is_add || (!empty($db_id) && ($post['hidden_amount'] < $post['cs_amount'] || $post['book_status'] == 2))))
        {

            /*
            
             * Print
            
            */

            $abishegam = $this->get_by_print($db_id);

            $items = $this->get_items($db_id);

            $gods = $prasadams = $print_body = array();

            foreach ($items as $k => $details):

                $args = array();

                if (!array_key_exists($details['god_id'], $gods)):

                    $q = $this
                        ->db
                        ->get_where(TBL_GOD_NAME, array(
                        'id' => $details['god_id']
                    ));

                    $gods[$details['god_id']] = $q->row_array();

                endif;

                if (!array_key_exists($details['prasadam_id'], $prasadams)):

                    $q = $this
                        ->db
                        ->get_where(TBL_PRASADAM, array(
                        'id' => $details['prasadam_id']
                    ));

                    $prasadams[$details['prasadam_id']] = $q->row_array();

                endif;

                $print_body[] = array(

                    (!empty($details['god_id']) ? ($gods[$details['god_id']]['name'] . ((!empty($gods[$details['god_id']]['tamil_name'])) ? ' / <span class="linear-lbl lang-tamil">' . $gods[$details['god_id']]['tamil_name'] . '</span>' : '')) : '<center> - </center>') ,

                    $prasadams[$details['prasadam_id']]['name'] . ((!empty($prasadams[$details['prasadam_id']]['tamil_name'])) ? ' / <span class="linear-lbl lang-tamil">' . $prasadams[$details['prasadam_id']]['tamil_name'] . '</span>' : '') ,

                    '<div style="text-align: right;">' . $details['bai_qty'] . ' x ' . $details['bai_price'] . '</div>',

                    '<div style="text-align: right;">' . number_format($details['bai_qty'] * $details['bai_price'], 2) . '</div>',

                );

            endforeach;

            if (empty($post['book-now']))
            {
                $cdate = ''; $cdate = date('d-m-Y h:i:sa', strtotime($abishegam->created_on));
                $args = array(

                    'type' => '1',

                    'rec_no' => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,

                    'title' => $main_service['service_name'] . ' - ' . $service['name'],

                    'amount' => array(
                        $post['ab_amount']
                    ) , // Currently Paid
                    'gst' => $gst_details->gst,

                    'copy' => true,

                    'printType' => true,
                    'fn_type' => 'abishegam',
                    'created_on' => $cdate,

                    'data' => array(

                        // Type = 1 && 3 && 4
                        'name' => array(
                            $post['ct_dev_name_1'] . ',' . $abishegam->star_name_1 . ',' . $post['ct_dev_name_1_tamil'] . ',' . $abishegam->star_tamil_name1,
                            $post['ct_dev_name_2'] . ',' . $abishegam->star_name_2 . ',' . $post['ct_dev_name_2_tamil'] . ',' . $abishegam->star_tamil_name2
                        ) ,

                        'contact_no' => $post['ct_contact_no'],

                        'email' => $post['ct_email'],

                        // Type = 1 && 3
                        'address' => $post['ct_address'],

                        'desc' => $post['cs_desc'],

                        'section' => array(

                            array(

                                'Date<div class="sub-lbl"> தேதி</div>' => date('d/m/Y', strtotime($post['fn_date'])) ,

                                'Time<div class="linear-lbl"> நேரம்</div>' => $post['fn_from_time'] . ' - ' . $post['fn_to_time'],

                                'Period<div class="linear-lbl"> காலம்</div>' => ($post['fn_period'] == 1) ? 'Morning / காலை' : 'Evening / மாலை',

                                'Deity<div class="linear-lbl"> தெய்வம்</div>' => ((!empty($post['fn_deity'])) ? $this->get_deity_name($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,

                        ) ,

                    ) ,

                );
                
                //echo "<pre>"; print_r( $args ); "</pre>"; die;
                print_rec($args);

            }

        }

        /*** To Insert Refund Amount - Start ***/

        #if((!empty($post['hidden_amount'])) && ($post['hidden_amount'] > $post['cs_amount'])) {
        /* if(empty(( $post['book-now'] )) && ((!empty($db_id) && ($post['hidden_amount'] > $post['cs_amount'])))) {
        
            $insert = array(
        
                'menu_id' => 1,
        
                'service_id' => $post['fn_type'],
        
                'auto_id' => $post['hidden_id'],
        
                'pay_type_id' => 1,
        
                'amount' => ($post['hidden_amount'] - $post['cs_amount']),
        
                'created_on' => date('Y-m-d H:i:s'),
        
                'created_by' => $this->user_data['user_id']
        
            );
        
            $this->insert_refund_amount($insert);
        
            
        
        } */

    }

    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'        => $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 ***/  
                     
        }
    }

    function print_me_2()
    {

        $print_args['data'] = array

        (

            'items' => array

            (

                '0' => array

                (

                    '0' => array

                    (

                        'name' => 'Sri Vinayagar'

                    )

                ) ,

                '1' => array

                (

                    '0' => array

                    (

                        'name' => 'Sri Vinayagar'

                    )

                ) ,

                '2' => array

                (

                    '0' => array

                    (

                        'name' => 'Sri Vinayagar'

                    )

                ) ,

            ) ,

            'date' => array

            (

                '0' => array

                (

                    '0' => '11/10/2016',

                    '1' => '11/10/2016',

                ) ,

                '1' => array

                (

                    '0' => '11/10/2016',

                    '1' => '26/10/2016',

                ) ,

                '2' => array

                (

                    '0' => '12/10/2016',

                    '1' => '22/10/2016',

                ) ,

            ) ,

            'day' => array

            (

                '0' => '',

                '1' => 'Tuesday',

                '2' => '',

            ) ,

            'days' => array

            (

                '0' => '1',

                '1' => '3',

                '2' => '7',

            ) ,

        );

        $args = array(

            'type' => '2', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai
            'rec_no' => '0323',

            'title' => 'Katalai',

            'amount' => array(
                '320.00'
            ) ,

            'copy' => true,

            'data' => array(

                // Type = 2
                'name' => array(

                    'John,Tamil Name 01,Kanni Rasi',

                    'Pilli,Tamil Name 02,Swathi',

                ) ,

                'items' => $print_args['data']['items'],

                'date' => $print_args['data']['date'], //array(date("d/m/Y", $bk_begin_strtime), date("d/m/Y", $bk_end_strtime)),
                'day' => $print_args['data']['day'],

                //'weeks'     => $print_args['data']['week'],
                //( $is_item ? 'item' : 'days')     => $itm,
                

                
            ) ,

        );

        /* if( $is_itm ) :
        
            $args['data']['itm'] = "Item";
        
        else :
        
            $args['data']['amt'] = "Amount";
        
        endif; */
        
        print_rec($args);

    }

    function print_me()
    {

        /*
        
         * Print
        
        */

        // Kattalai Archanai
        /*$args = array(
        
            
        
            'type' => '2',
        
            'copy'  => TRUE,
        
            'rec_no' => '0002',
        
            'title' => 'Kattalai Archanai - Sub Kattalai Service',
        
            'amount' => array
        
                (
        
                    '0' => 1629,
        
                    '1' => 303,
        
                    '2' => 2121,
        
                    '3' => 303,
        
                ),
        
        
        
            'data' => array
        
                (
        
                    'name' => array
        
                        (
        
                            '0' => 'John,??,Bharani',
        
                            '1' => 'Kannan,???,Astham',
        
                        ),
        
        
        
                    'items' => array
        
                        (
        
                            '0' => array('Sri Vinayagar', 'Karpagm', 'Saraswathi'),
        
                            '1' => array('Sri Vinayagar', 'Saraswathi'),
        
                            '2' => array('Sri Vinayagar', 'Saraswathi'),
        
                            '3' => array('Sri Vinayagar', 'Saraswathi'),
        
                        ),
        
        
        
                    'date' => array
        
                        (
        
                            '0' => array
        
                                (
        
                                    '0' => '22/09/2016',
        
                                    '1' => '30/09/2016',
        
                                ),
        
        
        
                            '1' => array
        
                                (
        
                                    '0' => '22/09/2016',
        
                                    '1' => '12/10/2016',
        
                                ),
        
        
        
                            '2' => array
        
                                (
        
                                    '0' => '22/09/2016',
        
                                    '1' => '12/10/2016',
        
                                ),
        
        
        
                            '3' => array
        
                                (
        
                                    '0' => '23/10/2016',
        
                                    '1' => '30/10/2016',
        
                                ),
        
        
        
                        ),
        
        
        
                    'day' => array
        
                        (
        
                            '0' => '',
        
                            '1' => 'Wednesday',
        
                            '2' => '',
        
                            '3' => '',
        
                        ),
        
        
        
                    'days' => array
        
                        (
        
                            '0' => 21,
        
                            '1' => 3,
        
                            '2' => 3,
        
                            '3' => 3,
        
                        ),
        
        
        
                ),
        
            
        
        );*/

        /* $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',
        
        );
        
        
        
        $print_args = array();
        
        $with_god = $with_name = $with_footer = $with_group = FALSE;
        
        foreach($post['items'] as $k => $item ) :
        
            $qty = $item['qty'];
        
            $rec_no = $item['bari_rec_no'];
        
            
        
            $gods = array();
        
            if( !empty($item['gods']) ) :
        
                $this->db->select('name, tamil_name, price');
        
                $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;
        
        
        
            $q = $this->db->get_where(TBL_CATEGORY, array('id' => $item['catId']));
        
            $cat = $q->row_array();
        
            $cat['image'] = DIR_CATEGORY_IMAGE . $cat['image'];
        
            
        
            $q = $this->db->get_where(TBL_ITEM, array('id' => $item['itemId']));
        
            $item = $q->row_array();
        
            $item['image'] = DIR_ITEM_IMAGE . $item['image'];
        
            
        
            $item['cat'] = $cat;
        
            $item['qty'] = $qty;
        
        $item['category_id'] = $cat['id'];
        
            $item['cat']['name'] = $cat['category_name'];
        
            $item['gods'] = $gods;
        
            $item['sub_total'] = $post['items'][$k]['qty'] * $post['items'][$k]['price'];
        
            
        
            if( $cat['grouping'] == '1' && $item['god_name'] != '1' ) :
        
                if( !$with_god && $item['god_name'] == '1' ) :
        
                    $with_god = TRUE;
        
                endif;
        
                
        
                if( !$with_name && $item['receipt'] == '1' ) :
        
                    $with_name = TRUE;
        
                endif;
        
                
        
                if( !$with_footer && $item['is_enable_footer'] == '1' ) :
        
                    $with_footer = TRUE;
        
                endif;
        
                
        
                $print_args['items'][$cat['id']][] = $item;
        
                $print_args['items'][$cat['id']][0]['rec_no'][] = $rec_no;
        
                $print_args['items'][$cat['id']][0]['total_qty'] += $qty;
        
                
        
                $print_args['items'][$cat['id']][0]['total_price'] += $item['sub_total'];
        
            else:
        
                $item['total_qty'] = $qty;
        
                $item['rec_no'] = $rec_no;
        
                $print_args['items'][] = array($item);
        
            endif;
        
            
        
        endforeach;
        
        
        
        $print_args['extra'] = array(
        
            'with_god'      => $with_god,
        
            'with_name'     => $with_name,
        
            'with_footer'   => $with_footer,
        
        );
        
        
        
        
        
        
        
        for( $i = 1; $i <=6; $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;*/

        $args = array(

            'type' => '1', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai, '6' => Common
            'rec_no' => '000004',

            'title' => 'Abishegam', //$main_service['service_name']. ' - '.$service['name'],
            'amount' => array(
                '340.00',
                '40.00',
                '130'
            ) ,

            'gst' => true,

            //'copy'      => FALSE,
            

            'data' => array(

                // Type = 1 && 3 && 4
                'name' => array(
                    'John',
                    'juewy'
                ) , //, 'Jessy'),
                'contact_no' => '932783022',

                'email' => 'hello@gmail.com',

                // Type = 1 && 3
                'address' => '#345, Pi colony, Chennai',

                'desc' => 'Nothing to show!',

                // Type = 1
                /*'section'  => array(
                
                        array(
                
                            'Function Date<div class="sub-lbl">பெயர்</div>' => '22 Mar, 2016',
                
                            'Period'        => 'Evening',
                
                            'Priest Name'   => 'Mr. Ajith',
                
                        ),
                
                       'Melam Name'        => 'Seragoon',
                
                        'Nathaswaram Name'  => 'Unknown'
                
                ),*/

                // Type = 3
                /*'date'      => '22/09/2016',
                
                'time'      => '11:10:00-12:10:00',
                
                'proof'     => array('1','1','0'),
                
                'period'    => 'Evening',
                
                'event_type'=> 'Office Metting',*/

                // Type = 2
                /*'name'      => array('John,TamilName, Ailyam,Star tamilname', 'Micheal'),
                
                'date'      => array('22/09/2016', '28/09/2016'),
                
                'day'       => array('Tuesday'),
                
                //'weeks'     => '',
                
                'days'      => array('9'),
                
                'items'     => array(array(array('Lakshmi','Parvathi'), array('Lakshmi')
                
                )),*/

                // Type = 4
                /*'date'      => '22/09/2016',
                
                'period'    => 'Evening',
                
                'items'     => array(array('Lakshmi', 'Pongal', 2, 20.00), array('Parvathi', 'Pongal', 5, 100.00)),*/

                // Type = 6
                /*'fields'  => array(
                
                    'Name'   => 'John',
                
                    'Email' => 'asla@gmail.com',
                
                    'Name4'   => 'John',
                
                    'Email4' => 'asla@gmail.com',
                
                    'Name5'   => 'John',
                
                    'Email6' => 'asla@gmail.com',
                
                ),
                
                
                
                'tables' => array(
                
                 
                
                    'attr'  => 'id="items-table"', // <table>  attributes
                
                    'head'  => array('God Name','Qty', 'Price'),
                
                    'body'  => array(
                
                 * foreach
                
                        array('Parvathi','2','10.00'),
                
                        array('Lakshmi','6','20.00'),
                
                        array('Lakshmi','6','20.00'),
                
                    ),
                
                
                
                ),*/

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

            ) ,

        );
        
        print_rec($args);

    }

    function print_short()
    {

        $post = array

        (

            'act' => 'submit',

            'isTender' => 'true',

            'items' => array

            (

                '0' => array

                (

                    'catId' => '1',

                    'itemId' => '2',

                    'grouping' => '1',

                    'qty' => '1',

                    'price' => '50.00',

                    'gods' => '1',

                ) ,

                '1' => array
                // Banana
                (

                'catId' => '1',

                'itemId' => '1',

                'grouping' => '1',

                'qty' => '2',

                'price' => '10.00',

                'gods' => '',
) ,

                '2' => array

                (

                    'catId' => '1',

                    'itemId' => '3',

                    'grouping' => '1',

                    'qty' => '5',

                    'price' => '100.00',

                    'gods' => '2,3',

                ) ,

                '3' => array

                (

                    'catId' => '4',

                    'itemId' => '5',

                    'grouping' => '0',

                    'qty' => '1',

                    'price' => '20.00',

                    'gods' => '',

                ) ,

                '4' => array

                (

                    'catId' => '4',

                    'itemId' => '4',

                    'grouping' => '0',

                    'qty' => '4',

                    'price' => '60.00',

                    'gods' => '',

                ) ,

            ) ,

            'input_1' => 'John',

            'input_2' => '2',

            'input_3' => 'Thissa',

            'input_4' => '5',

        );

        $print_args = array();

        $with_god = $with_name = $with_footer = $with_group = false;

        foreach ($post['items'] as $k => $item):

            $qty = $item['qty'];

            $rec_no = $item['bari_rec_no'];

            $gods = array();

            if (!empty($item['gods'])):

                $this
                    ->db
                    ->select('name, tamil_name, price');

                $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;

            $q = $this
                ->db
                ->get_where(TBL_CATEGORY, array(
                'id' => $item['catId']
            ));

            $cat = $q->row_array();

            $cat['image'] = DIR_CATEGORY_IMAGE . $cat['image'];

            $q = $this
                ->db
                ->get_where(TBL_ITEM, array(
                'id' => $item['itemId']
            ));

            $item = $q->row_array();

            $item['image'] = DIR_ITEM_IMAGE . $item['image'];

            $item['cat'] = $cat;

            $item['qty'] = $qty;

            $item['category_id'] = $cat['id'];

            $item['cat']['name'] = $cat['category_name'];

            $item['gods'] = $gods;

            $item['sub_total'] = $post['items'][$k]['qty'] * $post['items'][$k]['price'];

            if ($item['god_name'] == '1' || $cat['grouping'] != '1'):

                // Separate Receipt ( With God || No Group )
                $item['total_qty'] = $qty;

                $item['rec_no'] = $rec_no;

                $item['total_price'] = $item['sub_total'];

                $print_args['items'][] = array(
                    $item
                );

            else:

                // Group && ( Always No God )
                

                $print_args['items'][$cat['id']][] = $item;

                $print_args['items'][$cat['id']][0]['rec_no'][] = $rec_no;

                $print_args['items'][$cat['id']][0]['total_qty'] += $qty;

                if ($item['receipt'] == '1'):

                    // With Name is found
                    $print_args['items'][$cat['id']][0]['receipt'] = '1';

                endif;

                if ($item['is_enable_footer'] == '1'):

                    // With Footer is found
                    $print_args['items'][$cat['id']][0]['is_enable_footer'] = '1';

                endif;

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

            endif;

            /*if( $cat['grouping'] == '1' && $item['god_name'] != '1' ) :
            
                if( !$with_god && $item['god_name'] == '1' ) :
            
                    $with_god = TRUE;
            
                endif;
            
                
            
                if( !$with_name && $item['receipt'] == '1' ) :
            
                    $with_name = TRUE;
            
                endif;
            
                
            
                if( !$with_footer && $item['is_enable_footer'] == '1' ) :
            
                    $with_footer = TRUE;
            
                endif;
            
                
            
                $print_args['items'][$cat['id']][] = $item;
            
                $print_args['items'][$cat['id']][0]['rec_no'][] = $rec_no;
            
                $print_args['items'][$cat['id']][0]['total_qty'] += $qty;
            
                
            
                $print_args['items'][$cat['id']][0]['total_price'] += $item['sub_total'];
            
            else:
            
                $item['total_qty'] = $qty;
            
                $item['rec_no'] = $rec_no;
            
                $print_args['items'][] = array($item);
            
            endif;*/

        endforeach;

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

        //echo "<pre>Data: "; print_r($print_args); die;
        

        for ($i = 1;$i <= 6;$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;

        $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',

            'title' => 'Archanai', //$main_service['service_name']. ' - '.$service['name'],
            'amount' => array(
                '340.00',
                '340.00'
            ) ,

            'copy' => false,

            'data' => array(

                // Type = 5
                'name' => $print_args['name'],

                'items' => $print_args['items'],

                'extra' => $print_args['extra'],

            ) ,

        );
        
        print_rec($args);

    }

    function print_short_old()
    {

        $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',

        );

    }

    public function insert_refund_amount($data)
    {

        $this
            ->db
            ->insert(TBL_REFUND, $data);

        return $this
            ->db
            ->insert_id();

    }

    function delete($id, $hidden_del_reason)
    {

        $args = array(

            'pay_amount' => 0, // Deleted
            
        );

        $this
            ->db
            ->update(TBL_PAY, $args, array(
            'pay_ref_type' => 1,
            'pay_ref_id' => $id
        ));

        $this
            ->db
            ->update(TBL_REFUND, array(
            'status' => 2
        ) , array(
            'menu_id' => 1,
            'auto_id' => $id
        ));

        $update = array(

            'ba_amount' => 0,

            'ba_paid_amount' => 0,

            'del_reason' => $hidden_del_reason,

            'status' => 2

        );

        $this
            ->db
            ->update(TBL_BA, $update, array(
            'id' => $id
        ));

        $update = array(

            'bai_sub_total' => 0,

            'status' => 2

        );

        $this
            ->db
            ->update(TBL_BAI, $update, array(
            'ba_id' => $id
        ));

    }

    function ajax()
    {

        $post = $this
            ->input
            ->post();

        switch ($post['act']):

        case 'booked':

            /*
            
                 * Get all booked details
            
            */

            $where['self.ba_book_status'] = 2;

            $where['self.status'] = 1;

            if (!empty($post['fromDate'])):

                $e = explode("-", $post['fromDate']);

                $where['DATE(self.ba_fn_from_date) >= '] = $e[2] . '-' . $e[1] . '-' . $e[0];

            endif;

            if (!empty($post['toDate'])):

                $e = explode("-", $post['toDate']);

                $where['DATE(self.ba_fn_from_date) <= '] = $e[2] . '-' . $e[1] . '-' . $e[0];

            endif;

            if (!empty($post['period'])):

                $where['self.ba_period'] = $post['period'];

            endif;

            $results = $this->get_all_booked_details('', $where);

        break;

        endswitch;

        return $results;

    }

    public function get_prasadam_price($id)
    {

        $this
            ->db
            ->where('id', $id);

        return $this
            ->db
            ->get(TBL_PRASADAM)
            ->row();

    }

    public function get_deity_name($id)
    {

        $this
            ->db
            ->where('id', $id);

        return $this
            ->db
            ->get(TBL_GOD_NAME)
            ->row();

    }

    public function service_type_exists($type)
    {

        $this
            ->db
            ->where('service_id', $type);

        $this
            ->db
            ->where('status !=', 2);

        $this
            ->db
            ->order_by('ba_rec_no', 'desc');

        return $this
            ->db
            ->get(TBL_BA);

    }

    public function get_amount_by_service_id($id)
    {

        $this
            ->db
            ->where('id', $id);

        return $this
            ->db
            ->get(TBL_SERVICE)
            ->row();

    }

    public function total_paid_amount($menu, $type)
    {

        $this
            ->db
            ->select('SUM(pay_amount) as paidAmount');

        $this
            ->db
            ->where('pay_ref_type', $menu);

        $this
            ->db
            ->where('pay_ref_id', $type);

        $this
            ->db
            ->where('status', 1);

        return $this
            ->db
            ->get(TBL_PAY)
            ->row();

    }

    public function payment_mode_lists()
    {

        $this
            ->db
            ->where('status', 1);

        $this
            ->db
            ->where('menu_id', 0);

        return $this
            ->db
            ->get(TBL_PAY_TYPE)
            ->result();

    }

    public function get_paid_type($menu, $type, $id)
    {

        $this
            ->db
            ->select('*,SUM(pay_amount) as pay_amount');

        $this
            ->db
            ->where('pay_ref_type', $menu);

        $this
            ->db
            ->where('pay_ref_id', $type);

        $this
            ->db
            ->where('pay_type_id', $id);

        $this
            ->db
            ->where('status', 1);

        $this
            ->db
            ->group_by('pay_type_id');

        return $this
            ->db
            ->get(TBL_PAY)
            ->row();

    }

    public function get_paidID($menu, $type, $id)
    {

        $this
            ->db
            ->where('pay_ref_type', $menu);

        $this
            ->db
            ->where('pay_ref_id', $type);

        $this
            ->db
            ->where('pay_type_id', $id);

        $this
            ->db
            ->where('status', 1);

        return $this
            ->db
            ->get(TBL_PAY)
            ->result();

    }

    public function delete_payment_by_paid_id($id)
    {

        $this
            ->db
            ->where_in('id', $id);

        $this
            ->db
            ->delete(TBL_PAY);

        return $this
            ->db
            ->affected_rows();

    }

    public function get_payment_date($ba_id)
    {

        $where['self.pay_ref_type'] = 1; // Billing Abishegam
        $where['self.pay_ref_id'] = $ba_id;

        $q = $this
            ->db
            ->get_where(TBL_PAY . ' AS self', $where);

        return $q->result_array();

    }

}
?>
