<?php

/* 
 * Author       : Jai K
 * Purpose      : Model for Billing Kattalai Archanai
 * Created On   : 2016-09-02 12:02
 */

class Kattalai_Archanai_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_BK)->row();
    }
    
    function get_all( $id= '', $where = array() ) {
        if( !empty( $id ) ) :
            $where['self.id'] = $id;
        endif;
        
        #$where['self.status'] = 1;
        $where['self.bk_book_status'] = 1;
        
        
        $this->db->select( 'self.*, self.status AS status, serv.name AS service_name, serv.amount as ser_amount, serv.prefix, 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_STAR . ' AS star1', 'star1.id = self.bk_star_1', 'left' );
        $this->db->join( TBL_STAR . ' AS star2', 'star2.id = self.bk_star_2', 'left' );
        
        $this->db->order_by('self.bk_rec_no','desc');
        
        $q = $this->db->get_where( TBL_BK . ' AS self', $where );
        return $q->result_array();
    }
    
    function get_all_booked_details( $id= '', $where = array() ) {
        if( !empty( $id ) ) :
            $where['self.id'] = $id;
        endif;
        
        #$where['self.status'] = 1;
        
        $this->db->select( 'self.*, self.status AS status, serv.name AS service_name, serv.amount as ser_amount, serv.prefix, 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_STAR . ' AS star1', 'star1.id = self.bk_star_1', 'left' );
        $this->db->join( TBL_STAR . ' AS star2', 'star2.id = self.bk_star_2', 'left' );
        
        $this->db->order_by('self.id','desc');
        
        $q = $this->db->get_where( TBL_BK . ' AS self', $where );
        return $q->result_array();
    }
    
    function get_items_id($id){
        $this->db->where('bk_id',$id);
        $this->db->where('status !=',2);
        return $this->db->get(TBL_BKI)->result();
    }
    
    function get_items( $bk_id ) {
        $where['self.bk_id'] = $bk_id;
        $where['self.status'] = 1;
        
        
        $qry = ', GROUP_CONCAT(god.name) AS god_names';//', (select god.name FROM '.TBL_GOD_NAME . ' AS god WHERE god.id IN(self.bki_god_ids) AND god.status = "1") AS god_name';
        
        $this->db->where('FIND_IN_SET(god.id, self.bki_god_ids)', '', FALSE);
        $this->db->group_by('self.id');
        $this->db->select( 'self.*, self.id AS id, self.status AS status'. $qry);
        $q = $this->db->get_where( TBL_BKI . ' AS self, '.TBL_GOD_NAME.' AS god', $where );
        return $q->result_array();
    }
    
    function get_payments( $bk_id ) {
        $where['self.pay_ref_type'] = 8; // Billing Kattalai Archanai
        $where['self.pay_ref_id'] = $bk_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);die;
        $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] : '';
        $print_args = array();
        $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['total_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();
        
        $args = array(
            'service_id'    => $post['fn_type'],
            'bk_star_1'     => !empty( $post['star_1'] ) ? $post['star_1'] : '0',
            'bk_star_2'     => !empty( $post['star_2'] ) ? $post['star_2'] : '0',
            'bk_star_3'     => !empty( $post['star_3'] ) ? $post['star_3'] : '0',
            'bk_name_1'     => $post['name_1'],
            'bk_name_2'     => $post['name_2'],
            'bk_name_3'     => $post['name_3'],
            'bk_tamil_name_1'=> htmlspecialchars( $post['tamil_name_1'] ),
            'bk_tamil_name_2'=> htmlspecialchars( $post['tamil_name_2'] ),
            'bk_tamil_name_3'=> htmlspecialchars( $post['tamil_name_3'] ),
            'contact_no'    => $post['contact_no'],
            'bk_desc'       => $post['desc'],
            'gst'           => $gst,
            'gst_value'     => $gst_amount,          
            'bk_book_status'=> !empty( $post['book_now'] ) ? 2 : 1,            
            'bk_amount'     => $post['total_amount'],
        );
        
        if( empty( $post['book_now'] ) ) :
            // Returned | Extra items Added
            $args['bk_paid_amount'] = $post['total_amount'];
        endif;

        $bk_status = $args['bk_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'],
                'bk_book_status'=> $bk_status
            );
            
            $receipt_no = generate_rec_no(TBL_BK, $wh);
            $args['bk_rec_no'] = $receipt_no;   
        endif;

        if( $is_add ) :
            // Insert 
            $args['bk_booked_date'] = $date_now;
            $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;
            
            /*$receipt_no = '0001';
            $services = $this->service_type_exists($post['fn_type']);
            if($services->num_rows() > 0) {
                $last_receipt_no = $services->row()->bk_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_BK, $args );
            $db_id = $this->db->insert_id();
			
			$period 			= $this->input->post('pr_period');
			$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');
			$pr_day_type		= $this->input->post('pr_day_type');
			$pr_expand_dates	= $this->input->post('pr_expand_dates');
			$pr_no_of_days		= $this->input->post('pr_no_of_days');
			$pr_weekly_day		= $this->input->post('pr_weekly_day');
            if(!empty($period)) :
                foreach( $deity as $k => $deity_id ) {
					$exp_dates 			= explode(',', $post['pr_expand_dates'][$k]);
					$e 					= explode('-', $exp_dates[0]);
					$exp_begin_strtime 	= strtotime( $e[2].'-'.$e[1].'-'.$e[0] );				
					$e 					= explode('-', $exp_dates[count($exp_dates)-1]);
					$exp_end_strtime 	= strtotime( $e[2].'-'.$e[1].'-'.$e[0] );
					
                    $sub_total 	= $qty[$k] * $price[$k] * $pr_no_of_days[0];
					
                    $insert = array(
                        'kattalai_id'   => $db_id,
						'bkp_day_type'  => $pr_day_type[0],
						'bkp_no_days'   => $pr_no_of_days[0],
						'bkp_week_day'  => $pr_day_type[0] == '2' ? $pr_weekly_day[0] : '', // Only for Weekly
						'deity_id'      => $deity_id,
						'prasadam'      => $prasadam[$k],
						'quantity'      => $qty[$k],
						'price'         => $price[$k],
						'sub_total'     => $sub_total,
						'dates'			=> $pr_expand_dates[0],
						'period'		=> $period,
						'status'        => 1,
						'created_by'    => $this->user_data['user_id'],
						'created_on'    => date('Y-m-d H:i:s')
                    );
                    $this->db->insert( TBL_BKP, $insert );
					
					$print_args['data']['date'][] 	= array(date("d/m/Y", $exp_begin_strtime), date("d/m/Y", $exp_end_strtime));
					$print_args['data']['day'][] 	= $pr_day_type[$k] == '2' ? $this->get_week_name( $pr_weekly_day[$k] ) : '';
					$print_args['data']['days'][] 	= $pr_no_of_days[$k];
                }
				//echo '<pre>';print_r($print_args);die;
            endif;
        elseif( !empty( $db_id ) ):
            // Update
			
			//echo '<pre>';print_r($post);die;
            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_BK, $args, array( 'id' => $db_id ) );
			
			$period 			= $this->input->post('pr_period');
			$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');
			$pr_day_type		= $this->input->post('pr_day_type');
			$pr_expand_dates	= $this->input->post('pr_expand_dates');
			$pr_no_of_days		= $this->input->post('pr_no_of_days');
			$pr_weekly_day		= $this->input->post('pr_weekly_day');
            
            if(!empty($period)) {
				//echo '<pre>';print_r($post);die;
                foreach( $deity as $k => $deity_id ) {
					$exp_dates 			= explode(',', $post['pr_expand_dates'][$k]);
					$e 					= explode('-', $exp_dates[0]);
					$exp_begin_strtime 	= strtotime( $e[2].'-'.$e[1].'-'.$e[0] );
					$e 					= explode('-', $exp_dates[count($exp_dates)-1]);
					$exp_end_strtime 	= strtotime( $e[2].'-'.$e[1].'-'.$e[0] );
										
                    $sub_total 			= $qty[$k] * $price[$k] * $pr_no_of_days[0];
					
                    if(empty($pr_id[$k])) {
                        $insert = array(
                            'kattalai_id'   => $db_id,
							'bkp_day_type'  => $pr_day_type[0],
							'bkp_no_days'   => $pr_no_of_days[0],
							'bkp_week_day'  => $pr_day_type[0] == '2' ? $pr_weekly_day[0] : '', // Only for Weekly
                            'deity_id'      => $deity_id,
                            'prasadam'      => $prasadam[$k],
                            'quantity'      => $qty[$k],
                            'price'         => $price[$k],
                            'sub_total'     => $sub_total,
							'dates'			=> $pr_expand_dates[0],
							'period'		=> $period,
                            'status'        => 1,
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => date('Y-m-d H:i:s')
                        );
                        $this->db->insert( TBL_BKP, $insert );
                    } else {
                        $update = array(
                            'kattalai_id'   => $db_id,
							'bkp_day_type'  => $pr_day_type[0],
							'bkp_no_days'   => $pr_no_of_days[0],
							'bkp_week_day'  => $pr_day_type[0] == '2' ? $pr_weekly_day[0] : '', // Only for Weekly
                            'deity_id'      => $deity_id,
                            'prasadam'      => $prasadam[$k],
                            'quantity'      => $qty[$k],
                            'price'         => $price[$k],
                            'sub_total'     => $sub_total,
							'dates'			=> $pr_expand_dates[0],
							'period'		=> $period,
                            'status'        => 1,
                            '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]);
						$this->db->update( TBL_BKP, $update, array( 'id' => $pr_id[$k] ) );
						/*echo $this->db->last_query();
						exit;*/
                    }
					
					$print_args['data']['date'][] 	= array(date("d/m/Y", $exp_begin_strtime), date("d/m/Y", $exp_end_strtime));
					$print_args['data']['day'][] 	= $pr_day_type[$k] == '2' ? $this->get_week_name( $pr_weekly_day[$k] ) : '';
					$print_args['data']['days'][] 	= $pr_no_of_days[$k];
                }
            }

        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_BKI, array('status' => 2 ), array( 'id' => $rm_id ) );
            endforeach;
            
        endif;
        
     // 08-09-2016,09-09-2016,10-09-2016,11-09-2016,12-09-2016,13-09-2016,14-09-2016,15-09-2016
        $f_e = explode(',', $post['expand_dates'][0]);
        $e = explode('-', $f_e[0]);
        $bk_begin_strtime = strtotime( $e[2].'-'.$e[1].'-'.$e[0] );
            
        $bk_end_strtime = $bk_begin_strtime;
		
		if(empty($period)){
			foreach( $post['day_type'] as $k => $day_type ) :
				$exp_dates = explode(',', $post['expand_dates'][$k]);
				
				$sub_total = $post['days_amt'][$k];
				
				$e = explode('-', $post['start_date'][$k]);
				$start_date = $e[2].'-'.$e[1].'-'.$e[0];
				
				$e = explode('-', $post['end_date'][$k]);
				$end_date = $e[2].'-'.$e[1].'-'.$e[0];
				
				$e = explode('-', $exp_dates[0]);
				$exp_begin_strtime = strtotime( $e[2].'-'.$e[1].'-'.$e[0] );
			
				if( $exp_begin_strtime < $bk_begin_strtime ) :
					$bk_begin_strtime = $exp_begin_strtime;
				endif;
				
				$e = explode('-', $exp_dates[count($exp_dates)-1]);
				$exp_end_strtime = strtotime( $e[2].'-'.$e[1].'-'.$e[0] );
			
				if( $exp_end_strtime > $bk_end_strtime ) :
					$bk_end_strtime = $exp_end_strtime;
				endif;
	
				
				/*if( strtotime($start_date) < $bk_begin_strtime ) :
					$bk_begin_strtime = strtotime($start_date);
				endif;
				
				if( strtotime($end_date) > $bk_end_strtime ) :
					$bk_end_strtime = strtotime($end_date);
				endif;*/
				
				$this->db->select('name, tamil_name');
				$this->db->where_in('id', explode(',', $post['deity'][$k]));
				$q = $this->db->get_where(TBL_GOD_NAME, array());
				$gods = $q->result_array();
	
				$args = array(
					'bki_day_type'  => $day_type,
					'bki_god_ids'   => $post['deity'][$k],
					'bki_week_day'  => $day_type == '2' ? $post['weekly_day'][$k] : '', // Only for Weekly 
					'bki_from_date' => $start_date,
					'bki_to_date'   => $end_date,
					'bki_dates'     => $post['expand_dates'][$k],
					'bki_no_days'   => $post['no_of_days'][$k],
					'bki_amount'    => $sub_total,
				);
				
				$args['bki_week_day'] = !empty( $args['bki_week_day'] ) ? $args['bki_week_day'] : '0';
				
				if( empty( $post['bki_id'][$k] ) ) :
					// Insert
					$args['bk_id']      = $db_id;
					$args['created_on'] = $date_now;
					$args['created_by'] = $session_data['user_id'];
	
					$this->db->insert( TBL_BKI, $args );
					
				else :
					// Update
					
					$args['updated_on'] = $date_now;
					$args['updated_by'] = $session_data['user_id'];
	
					$this->db->update( TBL_BKI, $args, array( 'id' => $post['bki_id'][$k], 'bk_id' => $db_id ) );
					
				endif;
			   
	
				//$print_args['amount'][] = $sub_total;
				$print_args['data']['items'][] = (!empty($gods)) ? $gods : array();
				$print_args['data']['date'][] = array(date("d/m/Y", strtotime($start_date)), date("d/m/Y", strtotime($end_date)));
				$print_args['data']['day'][] = $day_type == '2' ? $this->get_week_name( $args['bki_week_day'] ) : '';
				$print_args['data']['days'][] = $args['bki_no_days'];
			endforeach;
		}
       
        if(empty($print_args['data']['date'])) {
            $print_args['data']['date'][] = array(date("d/m/Y", strtotime($post['sdate'])), date("d/m/Y", strtotime($post['edate'])));
        }
        
		if(empty($period)){
			$args = array(
				'bk_begin_date' => ((!empty($bk_begin_strtime)) ? date("Y-m-d", $bk_begin_strtime) : date("Y-m-d",strtotime($post['sdate']))),
				'bk_end_date'   => ((!empty($bk_end_strtime)) ? date("Y-m-d", $bk_end_strtime) : date("Y-m-d",strtotime($post['edate']))),
			);
		}else{
			$e 			= explode('/', $print_args['data']['date'][0][0]);
			$start_date = $e[2].'-'.$e[1].'-'.$e[0];
			
			$e 			= explode('/', $print_args['data']['date'][0][1]);
			$end_date 	= $e[2].'-'.$e[1].'-'.$e[0];
			
			$args = array(
				'bk_begin_date' =>  $start_date,
				'bk_end_date'   =>  $end_date,
			);
		}
		
		//echo $period."<pre>"; print_r($args); print_r($print_args['data']['date'][0]); exit;
        $this->db->update( TBL_BK, $args, array( 'id' => $db_id ) );
        
        
        $kattalai_archanai = $this->get_by_id($db_id);        
        
        /*x
         * Payments
         */
         
        if(!empty( $post['paid_amount'] ) && 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;
        
            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 );                
                
                $paid_amt += $pay_amt;
                $args = array(
                    'pay_ref_type'  => 8, // For Billing kattalai Archanai
                    'pay_ref_id'    => $db_id, // Main ID
                    'pay_type_id'   => $pay_type_id,
                    'pay_amount'    => $pay_amt,
                    'pay_details'   => $pay_details,
                    'created_on'    => $kattalai_archanai->created_on,
                    'created_by'    => $session_data['user_id'],
                );
                
                // Insert
                $this->db->insert( TBL_PAY, $args );

            endforeach;  
        /*endif;
        
        if(empty(( $post['book_now'] )) && ($is_add || (!empty($db_id) && ($post['hidden_amount'] < $post['total_amount'] || $post['book_status'] == 2)))) :*/
            /*
             * Print
             */
            $q = $this->db->get_where(TBL_STAR, array( 'id' => $post['star_1'] ));
            $star_1 =  $q->row_array();
            
            $q = $this->db->get_where(TBL_STAR, array( 'id' => $post['star_2'] ));
            $star_2 =  $q->row_array();

            $q = $this->db->get_where(TBL_STAR, array( 'id' => $post['star_3'] ));
            $star_3 =  $q->row_array();
            
            $print_args['amount'][] = $post['total_amount'];
			
			$prasadam = $this->kattalai_archanai_model->get_prasadam_by_id($db_id);
			
			$tables = $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->bkp_no_days . ' x ' .$details->quantity . ' x ' . $details->price .'</div>',
					'<div style="text-align: right;">'.number_format($details->bkp_no_days*$details->quantity*$details->price, 2 ).'</div>',
				);
			endforeach;
			
			if($prasadam){
				$tables = array(
								'head'  => array('God Name<div class="sub-lbl">கடவுள் பெயர்<div>', 'Prasadam Name<div class="sub-lbl">பிரசாதம்<div>','No.Days x Qty x Unit Price($)<div class="sub-lbl">நாட்கள் x எண்ணிக்கை x ஒன்றின் விலை<div>', 'Amount($)<div class="sub-lbl">தொகை<div>'),
								'body'  => $print_body,
							);
			}
            $cdate = ''; $cdate = date('d-m-Y h:i:sa', strtotime($kattalai_archanai->created_on));
            $args = array(
                'type'      => '2', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai
                'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,
                'title'     => $main_service['service_name']. ' - '.$service['name'],
                'amount'    => $print_args['amount'],
                'gst'       => $gst_details->gst,
                'copy'      => TRUE,
                'printType' => TRUE,
                'payment_date' => $cdate,
				'fn_type' 	=> $post['fn_type'],   //126
                
                'data'      => array(
                    
                    // Type = 2
                    'name'      => array(
                        
                        $post['name_1'].','.$star_1['name'].','.htmlspecialchars( $post['tamil_name_1'] ).','.$star_1['tamil_name'], 
                        $post['name_2'].','.$star_2['name'].','.htmlspecialchars( $post['tamil_name_2'] ).','.$star_2['tamil_name'],
                        $post['name_3'].','.$star_3['name'].','.htmlspecialchars( $post['tamil_name_3'] ).','.$star_3['tamil_name'],
                    ),
                    
                    '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'],
                    'days'      => $print_args['data']['days'],
					
					'tables'	=> $tables,
                    
                ),
				
				
                
            );
            
			//echo "<pre>"; print_r($args); exit;
			
            //error_log(print_r($args,1));
            print_rec($args);            
        endif;
        
        
        /*** To Insert Refund Amount - Start ***/
        /* if(empty(( $post['book_now'] )) && ((!empty($db_id) && $post['hidden_amount'] > $post['total_amount']))) {
        #if((!empty($post['hidden_amount'])) && ($post['hidden_amount'] > $post['total_amount'])) {
            $insert = array(
                'menu_id' => 8,
                'service_id' => $post['fn_type'],
                'auto_id' => $post['hidden_id'],
                'pay_type_id' => 1,
                'amount' => ($post['hidden_amount'] - $post['total_amount']),
                'created_on' => date('Y-m-d H:i:s'),
                'created_by' => $this->user_data['user_id']
            );
            $this->insert_refund_amount($insert);
            
        } */
        
    }
    
    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' => 8, 'pay_ref_id' => $id ) );
        $this->db->update( TBL_REFUND, array( 'status' => 2), array( 'menu_id' => 8, 'auto_id' => $id ));
        
        $update = array(
            'bki_amount' => 0,
            'status' => 2
        );
        $this->db->update( TBL_BKI, $update, array( 'bk_id' => $id ) );
		
		$update = array(
            'sub_total' => 0,
            'status' => 2
        );
        $this->db->update( TBL_BKP, $update, array( 'kattalai_id' => $id ) );
        
        $update = array(
            'bk_amount' => 0,
            'bk_paid_amount' => 0,
            'del_reason' => $hidden_del_reason,
            'status' => 2
        );
        $this->db->update( TBL_BK, $update, array( 'id' => $id ) );
        
    }
    
    function ajax() {
        $post = $this->input->post();
        #error_log(print_r($post,1));
        switch( $post['act'] ) :
            case 'booked' :
                
                /*
                 * Get all booked details
                 */
                $where['self.bk_book_status'] = 2;
                $where['self.status'] = 1;
                
                if( !empty( $post['fromDate'] ) ) :
                    $e = explode("-", $post['fromDate']);
                    $where['DATE(self.bk_booked_date) >= '] = $e[2] . '-' . $e[1] . '-' . $e[0]; 
                endif;
                
                if( !empty( $post['toDate'] ) ) :
                    $e = explode("-", $post['toDate']);
                    $where['DATE(self.bk_booked_date) <= '] = $e[2] . '-' . $e[1] . '-' . $e[0]; 
                endif;
                
                $results = $this->get_all_booked_details( '', $where );
                
            break;    
            
        endswitch;
        
        return $results;
    }
    
    public function get_amount_by_service_id($id) {
        $this->db->where('id',$id);
        return $this->db->get(TBL_SERVICE)->row();
    }
    
    function get_week_name($day_no) {
        $week = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday'); 
        return $week[$day_no];
    }
    
    public function get_refund_details_by_ids($menu_id,$service_id,$auto_id) {
        $this->db->select('SUM(amount) as refund_amount');
        $this->db->where('menu_id',$menu_id);
        $this->db->where('service_id',$service_id);
        $this->db->where('auto_id',$auto_id);
        $this->db->where('status !=',2);
        return $this->db->get(TBL_REFUND)->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 service_type_exists($type) {
        $this->db->where('service_id',$type);
        $this->db->where('status !=',2);
        $this->db->order_by('bk_rec_no','desc');
        return $this->db->get(TBL_BK);
    }
    
    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( $bk_id ) {
        $where['self.pay_ref_type'] = 8; // Billing Kattalai Archanai
        $where['self.pay_ref_id'] = $bk_id;
        $where['self.status'] = 1;        
        $q = $this->db->get_where( TBL_PAY . ' AS self', $where );
        return $q->result_array();
    }
	
	public function get_prasadam_price($id) {
        $this->db->where('id',$id);
        return $this->db->get(TBL_PRASADAM)->row();        
    }
	
	public function get_prasadam_by_id($id){
        $this->db->select('kp.*, g.name as god_name, p.name as prasadam_name',FALSE);
        $this->db->join(TBL_PRASADAM . ' p','p.id = kp.prasadam','left');
        $this->db->join(TBL_GOD_NAME . ' as g','g.id = kp.deity_id','left');
        $this->db->where('kp.kattalai_id',$id);
        $this->db->where('kp.status !=',2);
        return  $this->db->get(TBL_BKP . ' as kp')->result();
    }
	
	public function get_prasadam_json($id){
        $this->db->select('kp.*, g.name as god_name, p.name as prasadam_name',FALSE);
        $this->db->join(TBL_PRASADAM . ' p','p.id = kp.prasadam','left');
        $this->db->join(TBL_GOD_NAME . ' as g','g.id = kp.deity_id','left');
        $this->db->where('kp.kattalai_id',$id);
        $this->db->where('kp.status !=',2);
        return  $this->db->get(TBL_BKP . ' as kp')->result_array();
    }

}