<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Billing_donation extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('billing/donation_model', '', TRUE);
        $this->load->model('login_details_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index($id = 4) {
        $data = array();
        $data['results'] = $this->donation_model->list_all();
        #echo '<pre>';print_r($data['results']);die;
        #$data['results'] = $this->donation_model->get_pledge_data();
        if (!empty($this->session->flashdata('success'))) 
            $data['success'] = $this->session->flashdata('success');
        else 
            $data['error'] = $this->session->flashdata('error');
        
        $actions = $this->actions();
        $data['add_btn']    = 'Create New Donation Details';
        $data['view_link']  = $actions['view'] . '/';
        $data['add_link']   = $actions['add'] . '/' . $id ;
        $data['edit_link']  = $actions['edit'] . '/';
        $data['delete_link']= $actions['delete'] . '/';
        $data['print'] = base_url() . 'billing_donation/print_list/';
        $data['title'] = 'Donation';
        
        $data['menu_id'] = $id;
        $service_menu = get_billing_controller($actions['controller']);
        $data['title'] = $service_menu->service_name;
        $data['service_menu_id'] = array('service_menu_id' => $service_menu->id, 'menu_type' => '4');
        $this->render($data, 'billing/donation/list');
    }
    
    public function add($type_id= '') {
        $data = array();
        $actions = $this->actions();
        $data['fn_types'] = $this->donation_model->get( TBL_SERVICE, array( 'menu_name' => $type_id ), array('order_by' => 'name') );
        $data['service_type_id'] = $type_id;
        $data['payments'] = $this->donation_model->payment_mode_lists();
        
        $data['form_action'] = $actions['insert'];
        $data['title'] = 'Donation';
        $this->render($data, 'billing/donation/add');
    }
    
    private function get_donation_url_key($name, $id = '') {
        $url_key = get_url_key($name);
        if ($this->donation_model->donation_url_key_exists($url_key, $id)) {
            $this->uri_key_index ++;
            return $this->get_donation_url_key($name . '_' . $this->uri_key_index, $id);
        }
        
        return $url_key;
    }
    
    public function insert() { #echo '<pre>';print_r($_POST);die;
        $services = $this->donation_model->service_type_exists($this->input->post('fn_type'));
        
        $insert = array(
            'type_id' => $this->input->post('type_id'),
            'service_id' => $this->input->post('fn_type'),
            'name' => $this->input->post('name'),
            'tamil_name' => htmlspecialchars( $this->input->post('tamil_name') ),
            'contact_no' => $this->input->post('contact_no'),
            'email' => $this->input->post('ct_email'),
            'address' => $this->input->post('ct_address'),
            'desc' => $this->input->post('cs_desc'),
            'amount_type' => ((!empty($this->input->post('amount_type'))) ? $this->input->post('amount_type') : 3),
            'amount' => $this->input->post('cs_amount'),
            #'status' => $this->input->post('status'),
            'url_key' => $this->get_donation_url_key($this->input->post('name')),
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        
        $insert_id = $this->donation_model->insert($insert);
        
        if ($insert_id > 0) {
            $this->session->set_flashdata('success', 'Billing for Donation is added successfully');
            if($services->num_rows() > 0) {
                $last_receipt_no = $services->row()->receipt_no;
                $last_no = (int)$last_receipt_no;
                $receipt_no = (($last_no + 1)  > 9999) ? ($last_no + 1)  : sprintf('0%03d', ($last_no + 1) );
            } else
                $receipt_no = '0001';
            
            $update = array(
                'receipt_no' => $receipt_no
            );
            $this->donation_model->update($update, $insert_id);
            
            $rows =  $this->donation_model->get_pledge_amount_details($this->input->post('fn_type'),$this->input->post('name'),$this->input->post('contact_no'));
            
            $donation_pledge = $this->donation_model->get_pledge_amount_details_by_data($this->input->post('fn_type'),$this->input->post('name'),$this->input->post('contact_no'));
            
            if($rows > 0) {
                $update = array(
                    'service_id' => $this->input->post('fn_type'),
                    'd_id' => $insert_id,
                    'name' => $this->input->post('name'),
                    'contact_no' => $this->input->post('contact_no'), 
                    'amount_type' => $this->input->post('amount_type'),
                    'end_date' => date('Y-m-d'),
                    #'status' => $this->input->post('status'),
                    'url_key' => $this->get_donation_url_key($this->input->post('name')),
                    'updated_by' => $this->user_data['user_id'],
                    'updated_on' => date('Y-m-d H:i:s')
                );
                
                if((!empty($this->input->post('hidden_pledge_type'))) && ($this->input->post('hidden_pledge_type')== 1)) {
                    $update['pledge_type'] = $this->input->post('hidden_pledge_type');
                    $old_amount = $donation_pledge->amount;
                    $now_pay_amt = $this->input->post('cs_amount');
                    $new_amount = $old_amount + $now_pay_amt;
                    
                    if($this->input->post('amount_type') == 1) {
                        $update['pledge_amount'] = $this->input->post('pledging_amount');
                        $update['amount'] = $new_amount;
                        $pledge_amount = $this->input->post('pledging_amount');
                    } else if($this->input->post('amount_type') == 2){
                        $update['pledge_amount'] = $this->input->post('pledging_item');
                        $update['amount'] = $new_amount;
                        $pledge_amount = $this->input->post('pledging_item');
                    }
                    
                    if((float)$new_amount == (float)$donation_pledge->pledge_amount) {
                        $update['pledge_status'] = 0;
                    } else {
                        $update['pledge_status'] = 1;
                    }
                } else {
                    $update['pledge_type'] = 0;
                    $update['pledge_amount'] = 0;
                    $update['amount'] = $this->input->post('cs_amount');
                    $update['pledge_status'] = 1;
                }
                $lastId = $donation_pledge->id;
                $this->donation_model->update_donation_pledge($update,$donation_pledge->id);
                
                $update = array(
                    'pledge_amount' => $pledge_amount
                );
                
                $this->donation_model->updtae_pledge_amt_transaction($update,$donation_pledge->id);
                
                if($this->input->post('amount_type') == 1) {
                    $paid_amt = number_format(($this->input->post('pledging_amount') - $this->input->post('balance_amount') + $this->input->post('cs_amount')),2,'.','');
                } else if($this->input->post('amount_type') == 2) {
                    $paid_amt = number_format(($this->input->post('pledging_item') - $this->input->post('balance_amount') + $this->input->post('cs_amount')),2,'.','');
                    $paid_now = number_format(($this->input->post('balance_amount') - $this->input->post('cs_amount')),2,'.','');
                }
                
            } else {
                $insert = array(
                    'receipt_no' => $receipt_no,
                    'd_id' => $insert_id,
                    'service_id' => $this->input->post('fn_type'),
                    'name' => $this->input->post('name'),
                    'contact_no' => $this->input->post('contact_no'),
                    'end_date' => date('Y-m-d'),
                    'amount' => $this->input->post('cs_amount'),
                    'pledge_status' => 1,
                    #'status' => $this->input->post('status'),
                    'url_key' => $this->get_donation_url_key($this->input->post('name')),
                    'created_by' => $this->user_data['user_id'],
                    'created_on' => date('Y-m-d H:i:s')
                );
                
                if(!empty($this->input->post('pledge_type'))) {
                    $insert['pledge_type'] = $this->input->post('pledge_type');
                    if($this->input->post('amount_type') == 1) {
                        $insert['amount_type'] = $this->input->post('amount_type');
                        $insert['pledge_amount'] = $this->input->post('pledging_amount');
                        $pledgeAmount = $this->input->post('pledging_amount');
                    } else if($this->input->post('amount_type') == 2){
                        $insert['amount_type'] = $this->input->post('amount_type');
                        $insert['pledge_amount'] = $this->input->post('pledging_item');
                        $pledgeAmount = $this->input->post('pledging_item');
                    } else if(empty($this->input->post('amount_type'))){
                        $insert['amount_type'] = 3;
                        $insert['pledge_amount'] = 0;
                        $pledgeAmount = 0;
                        $insert['pledge_status'] = 0;
                        $insert['pledge_type'] = 0;
                    }
                     
                    if($this->input->post('cs_amount') == $pledgeAmount) {
                        $insert['pledge_status'] = 0;
                    } else {
                        $insert['pledge_status'] = 1;
                    }
                } else {
                    $insert['pledge_type'] = 0;
                    $insert['pledge_amount'] = 0;
                    $insert['amount_type'] = 3;
                    $insert['pledge_status'] = 1;
                }
                
                $lastId = $this->donation_model->insert_donation_pledge($insert);
                
                if($this->input->post('amount_type') == 1) {
                    $paid_amt = $this->input->post('cs_amount');
                } elseif($this->input->post('amount_type') == 2) {
                    $paid_amt = $this->input->post('cs_amount');
                    $paid_now = number_format(($this->input->post('pledging_item')-$this->input->post('cs_amount')),2,'.','');
                }
            }
            
            $update = array (
                'pledge_id' => $lastId
            );
            $this->donation_model->update($update,$insert_id);
                
            $insert_trans = array(
                'receipt_no' => $receipt_no,
                'd_id' => $insert_id,
                'service_id' => $this->input->post('fn_type'),
                'name' => $this->input->post('name'),
                'contact_no' => $this->input->post('contact_no'),
                'pledge_date' => date('Y-m-d'),
                'amount' => $this->input->post('cs_amount'),
                'pledge_id' => $lastId,
                #'status' => $this->input->post('status'),
                'url_key' => $this->get_donation_url_key($this->input->post('name')),
                'created_by' => $this->user_data['user_id'],
                'created_on' => date('Y-m-d H:i:s')
            );
            
            if($rows > 0) {
                if(!empty($this->input->post('hidden_pledge_type'))) {
                    if($this->input->post('amount_type') == 1) {
                        $insert_trans['pledge_type'] = $this->input->post('hidden_pledge_type');
                        $insert_trans['amount_type'] = $this->input->post('amount_type');
                        $insert_trans['pledge_amount'] = $this->input->post('pledging_amount');
                    } else if($this->input->post('amount_type') == 2){
                        $insert_trans['pledge_type'] = $this->input->post('hidden_pledge_type');
                        $insert_trans['amount_type'] = $this->input->post('amount_type');
                        $insert_trans['pledge_amount'] = $this->input->post('pledging_item');
                    } else if(empty($this->input->post('amount_type'))){
                        $insert_trans['pledge_amount'] = 0;
                        $insert_trans['amount_type'] = 3;
                    }
                } else {
                    $insert_trans['pledge_type'] = 0;
                    $insert_trans['pledge_amount'] = 0;
                    $insert_trans['amount_type'] = 3;
                }
            }
            else {
                if(!empty($this->input->post('pledge_type'))) {
                    if($this->input->post('amount_type') == 1) {
                        $insert_trans['pledge_type'] = $this->input->post('pledge_type');
                        $insert_trans['amount_type'] = $this->input->post('amount_type');
                        $insert_trans['pledge_amount'] = $this->input->post('pledging_amount');
                    } else if($this->input->post('amount_type') == 2){
                        $insert_trans['pledge_type'] = $this->input->post('pledge_type');
                        $insert_trans['amount_type'] = $this->input->post('amount_type');
                        $insert_trans['pledge_amount'] = $this->input->post('pledging_item');
                    } else if(empty($this->input->post('amount_type'))){
                        $insert_trans['pledge_amount'] = 0;
                        $insert_trans['amount_type'] = 3;
                    }
                } else {
                    $insert_trans['pledge_type'] = 0;
                    $insert_trans['pledge_amount'] = 0;
                    $insert_trans['amount_type'] = 3;
                }
            }
            
            $this->donation_model->insert_pledge_transaction($insert_trans);
           
            $pay_type = $this->input->post('pay_type');
            
            foreach( $pay_type as $key => $value ) {
                if($value != '') {
                    $this->db->select('slug');
                    $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $key) );
                    $prow = $q->row_array();
                   
                    $pay_details = array();
                    if( $prow['slug'] == 'cheque' && !empty($value) ) :
                        // Cheque
                        $e = explode('-', $this->input->post('chq_date'));
                        $pay_details = array(
                           'name'   => $this->input->post('chq_bnk_name'),
                           'no'   => $this->input->post('chq_no'),
                           'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                        );
                    endif;
                    $pay_details = json_encode( $pay_details );
                    $insert = array(
                        'pay_ref_type'  => 4,
                        'pay_ref_id'    => $insert_id,
                        'pay_type_id'   => $key,
                        'pay_amount'    => $value,
                        'pay_details'   => $pay_details,
                        'status'        => 1,
                        'created_by'    => $this->user_data['user_id'],
                        'created_on'    => date('Y-m-d H:i:s')
                    );
                    $this->donation_model->insert_payment($insert);
                }
            }
            
            /*** To Print Receipt - Start ***/
            $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('fn_type'));
            $service_menu = $this->login_details_model->get_service_menu_by_id($this->input->post('type_id'));
            $prefix = get_general_setting()->prefix;
            
            
            $args = array(
                'type'      => '1', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
                'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,
                'title'     => $service_menu->service_name . ' - ' .$gst_details->name,
                /* (($this->input->post('amount_type') != 2) ? 'amount' : 'item' )   => (
                    ($this->input->post('hidden_pledge_type') == 1) ? (($this->input->post('amount_type') == 1 ) ? array($this->input->post('pledging_amount'),$paid_amt,$this->input->post('paid_amount')) : array($this->input->post('pledging_item'),$paid_amt,$paid_now)) : array($this->input->post('paid_amount'))
                ), */
                'gst'       => (($this->input->post('amount_type') != 2 ) ? $gst_details->gst : ''),
                'printType' => FALSE,
                
                'data'      => array(
                    // Type = 1 && 3 
                    'name'      => array($this->input->post('name').','.htmlspecialchars( $this->input->post('tamil_name') )),
                    'contact_no'=> $this->input->post('contact_no'),
                    'email'     => $this->input->post('ct_email'),
                    'address'   => $this->input->post('ct_address'),
                    'desc'      => $this->input->post('cs_desc'),
                ),
                
            );
            
            if($this->input->post('amount_type') == 1) {
                $total_amt 	= number_format($this->input->post('pledging_amount'),2,'.','');
                $Paid 		= number_format($paid_amt,2,'.','');
                $payNow 	= $this->input->post('paid_amount');
            } else if($this->input->post('amount_type') == 2){
                $total_amt = $this->input->post('pledging_item');
                $Paid = $paid_amt;
                $payNow = $paid_now;
            }
            
            $a = ($this->input->post('hidden_pledge_type') == 1) ? array($total_amt,$Paid,$payNow) : array($this->input->post('paid_amount'));
            if( $this->input->post('amount_type') == 2 ) :
                $args['data']['section'] = array(
                    array(
                        'Total Items<div class="sub-lbl"> மொத்த பொருட்கள்</div>'   => $a[0] . ' gms',
                        'Given Items<div class="sub-lbl"> கொடுக்கப்பட்ட  பொருட்கள்</div>'    => $a[1] . ' gms',
                    ),
                    'Pending Items<div class="sub-lbl"> நிலுவையிலுள்ள  பொருட்கள்</div>'  => $a[2] . ' gms' 
                );
            else :
                $args['amount'] = $a;
                
            endif;
                
            #echo '<pre>'; print_r($args);die;
            print_rec($args);            
            /*** End ***/
        }
        else
            $this->session->set_flashdata('error', 'Billing for Donation is not added!');
        
        redirect('billing_donation', 'refresh');
    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $actions = $this->actions();
        $data['donation'] = $this->donation_model->get_by_id($id);
        $data['transaction'] = $this->donation_model->get_pledge_transaction_details_by_id($data['donation']->service_id,$data['donation']->name,$data['donation']->contact_no,$data['donation']->receipt_no);
        $data['balance'] = $this->donation_model->get_balance_amt_by_id($data['transaction']->pledge_id,$data['transaction']->id);
        
        $data['payments'] = $this->donation_model->get_paid_type_by_id($data['donation']->type_id,$id);
        $data['paid_amount'] = $this->donation_model->total_paid_amount($data['donation']->type_id,$data['donation']->id);
        
        $data['fn_types'] = $this->donation_model->get( TBL_SERVICE, array( 'menu_name' => $data['donation']->type_id ), array('order_by' => 'name') );
        $data['payments'] = $this->donation_model->payment_mode_lists();
        $data['form_action'] = $actions['update'] . '/' . $id ;
        $data['title'] = 'Donation';
        $this->render($data, 'billing/donation/edit');
    }
    
    public function update($id) {
        if (empty($id)) {
            show_400_error();
        }
       
        $Donate = $this->donation_model->get_by_id($id);
        if($this->input->post('hidden_pledge_type') == 0) { // Ongoing
            $donation = array(
                'type_id' => $this->input->post('type_id'), 
                'service_id' => $this->input->post('fn_type'),
                'name' => $this->input->post('name'),
                'tamil_name' => htmlspecialchars( $this->input->post('tamil_name') ),
                'contact_no' => $this->input->post('contact_no'),
                'email' => $this->input->post('ct_email'),
                'address' => $this->input->post('ct_address'),
                'desc' => $this->input->post('cs_desc'),
                'amount_type' => $this->input->post('hidden_pledge_amount_type'),
                'amount' => $this->input->post('cs_amount'),
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            $affected_rows = $this->donation_model->update($donation,$this->input->post('hidden_id'));
            
            $donation_pledge = array(
                'd_id' => $this->input->post('hidden_id'),
                'service_id' => $this->input->post('fn_type'),
                'name' => $this->input->post('name'),
                'contact_no' => $this->input->post('contact_no'),
                'pledge_type' => $this->input->post('hidden_pledge_type'),
                'amount_type' => $this->input->post('hidden_pledge_amount_type'),
                'amount' => $this->input->post('cs_amount'),
                'end_date' => date('Y-m-d H:i:s'),
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            
            $this->donation_model->update_pledge($donation_pledge,$this->input->post('hidden_id'),$this->input->post('rec_no'));
            
            $donation_trans = array(
                'd_id' => $this->input->post('hidden_id'),
                'service_id' => $this->input->post('fn_type'),
                'name' => $this->input->post('name'),
                'contact_no' => $this->input->post('contact_no'),
                'pledge_date' => date('Y-m-d H:i:s'),
                'pledge_type' => $this->input->post('hidden_pledge_type'),
                'amount_type' => $this->input->post('hidden_pledge_amount_type'),
                'amount' => $this->input->post('cs_amount'),
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            
            $this->donation_model->update_transaction($donation_trans,$this->input->post('hidden_id'),$this->input->post('rec_no'));
        } else {
            if($this->input->post('AmountType') == 1) { // Amount
            
                $donation_data = $this->donation_model->get_by_id($this->input->post('hidden_id'));
                //echo '<pre>';print_r($donation_data);exit;
                # To Update Donation Table 
                
                $update = array (
                    'service_id' => $this->input->post('fn_type'),
                    'name' => $this->input->post('name'),
                    'tamil_name' => htmlspecialchars( $this->input->post('tamil_name') ),
                    'contact_no' => $this->input->post('contact_no'),
                    'email' => $this->input->post('ct_email'),
                    'address' => $this->input->post('ct_address'),
                    'desc' => $this->input->post('cs_desc'),
                    'amount_type' => $this->input->post('AmountType'),
                    'amount' => $this->input->post('cs_amount'),
                    'url_key' => $this->get_donation_url_key($this->input->post('name')),
                    'updated_by' => $this->user_data['user_id'],
                    'updated_on' => date('Y-m-d H:i:s')
                );
                
                $affected_rows = $this->donation_model->update($update,$this->input->post('hidden_id'));
                
                
                # To Update Donation Pledge Table
                
                $update = array(
                    'service_id' => $this->input->post('fn_type'),
                    'name' => $this->input->post('name'),
                    'contact_no' => $this->input->post('contact_no'),
                    'pledge_type' => $this->input->post('hidden_pledge_type'),
                    'amount_type' => $this->input->post('AmountType'),
                    'pledge_amount' => $this->input->post('pledging_amount'),
                    'end_date' => date('Y-m-d'),
                    #'status' => $this->input->post('status'),
                    'url_key' => $this->get_donation_url_key($this->input->post('name')),
                    'updated_by' => $this->user_data['user_id'],
                    'updated_on' => date('Y-m-d H:i:s')
                );
                
                if($this->input->post('old_amount') == $this->input->post('cs_amount') ) {
                    $update['amount'] = $donation_data->dp_amount;
                } elseif($this->input->post('old_amount') < $this->input->post('cs_amount')) {
                    $update['amount'] = ($donation_data->dp_amount) + ($this->input->post('cs_amount') - $this->input->post('old_amount'));
                    
                } elseif($this->input->post('old_amount') > $this->input->post('cs_amount')) {
                    $update['amount'] = ($donation_data->dp_amount) - ($this->input->post('old_amount') - $this->input->post('cs_amount'));
                    
                    /*** To Insert Refund Amount - Start ***/
                    $insert = array(
                        'menu_id' => $this->input->post('type_id'),
                        'service_id' => $this->input->post('fn_type'),
                        'auto_id' => $this->input->post('hidden_id'),
                        'pay_type_id' => 1,
                        'amount' => ($this->input->post('old_amount') - $this->input->post('cs_amount')),
                        'created_on' => date('Y-m-d H:i:s'),
                        'created_by' => $this->user_data['user_id']
                    );
                    $this->login_details_model->insert_refund_amount($insert);                    
                    /*** End ***/
                }
                
                $this->donation_model->update_donation_pledge($update,$donation_data->pledge_id);
                
                # To Update Donation Pledge Transaction Table
                
                $update = array(
                    'd_id' => $this->input->post('hidden_id'),
                    'service_id' => $this->input->post('fn_type'),
                    'name' => $this->input->post('name'),
                    'contact_no' => $this->input->post('contact_no'),
                    'pledge_date' => date('Y-m-d'),
                    'amount' => $this->input->post('cs_amount'),
                    'pledge_id' => $donation_data->pledge_id,
                    #'status' => $this->input->post('status'),
                    'url_key' => $this->get_donation_url_key($this->input->post('name')),
                    'created_by' => $this->user_data['user_id'],
                    'created_on' => date('Y-m-d H:i:s')
                );
                
                $this->donation_model->update_transaction($update,$this->input->post('hidden_id'),$donation_data->receipt_no);
                
                $update = array(
                    'pledge_amount' => $this->input->post('pledging_amount')
                );
                
                $this->donation_model->updtae_pledge_amt_transaction($update,$donation_data->pledge_id);
              
            } else if($this->input->post('AmountType') == 2) { // Item
                $donation_data = $this->donation_model->get_by_id($this->input->post('hidden_id'));
                //echo '<pre>';print_r($donation_data );exit;
                # To Update Donation Pledge Table
                
                $update = array (
                    'service_id' => $this->input->post('fn_type'),
                    'name' => $this->input->post('name'),
                    'tamil_name' => htmlspecialchars( $this->input->post('tamil_name') ),
                    'contact_no' => $this->input->post('contact_no'),
                    'email' => $this->input->post('ct_email'),
                    'address' => $this->input->post('ct_address'),
                    'desc' => $this->input->post('cs_desc'),
                    'amount_type' => $this->input->post('AmountType'),
                    'amount' => $this->input->post('cs_amount'),
                    'url_key' => $this->get_donation_url_key($this->input->post('name')),
                    'updated_by' => $this->user_data['user_id'],
                    'updated_on' => date('Y-m-d H:i:s')
                );
                
                $affected_rows = $this->donation_model->update($update,$this->input->post('hidden_id'));
                
                
                # To Update Donation Pledge Table
                
                $update = array(
                    'service_id' => $this->input->post('fn_type'),
                    'name' => $this->input->post('name'),
                    'contact_no' => $this->input->post('contact_no'),
                    'pledge_type' => $this->input->post('hidden_pledge_type'),
                    'amount_type' => $this->input->post('AmountType'),
                    'pledge_amount' => $this->input->post('pledging_item'),
                    'end_date' => date('Y-m-d'),
                    #'status' => $this->input->post('status'),
                    'url_key' => $this->get_donation_url_key($this->input->post('name')),
                    'updated_by' => $this->user_data['user_id'],
                    'updated_on' => date('Y-m-d H:i:s')
                );
                
                if($this->input->post('old_amount') == $this->input->post('cs_amount') ) {
                    $update['amount'] = $donation_data->dp_amount;
                } elseif($this->input->post('old_amount') < $this->input->post('cs_amount')) {
                    $update['amount'] = ($donation_data->dp_amount) + ($this->input->post('cs_amount') - $this->input->post('old_amount'));
                } elseif($this->input->post('old_amount') > $this->input->post('cs_amount')) {
                    $update['amount'] = ($donation_data->dp_amount) - ($this->input->post('old_amount') - $this->input->post('cs_amount'));                   
                }
                
                $this->donation_model->update_donation_pledge($update,$donation_data->pledge_id);
                
                # To Update Donation Pledge Transaction Table
                
                $update = array(
                    'd_id' => $this->input->post('hidden_id'),
                    'service_id' => $this->input->post('fn_type'),
                    'name' => $this->input->post('name'),
                    'contact_no' => $this->input->post('contact_no'),
                    'pledge_date' => date('Y-m-d'),
                    'amount' => $this->input->post('cs_amount'),
                    'pledge_id' => $donation_data->pledge_id,
                    #'status' => $this->input->post('status'),
                    'url_key' => $this->get_donation_url_key($this->input->post('name')),
                    'created_by' => $this->user_data['user_id'],
                    'created_on' => date('Y-m-d H:i:s')
                );
                
                $this->donation_model->update_transaction($update,$this->input->post('hidden_id'),$donation_data->receipt_no);
                
                $update = array(
                    'pledge_amount' => $this->input->post('pledging_item')
                );
                
                $this->donation_model->updtae_pledge_amt_transaction($update,$donation_data->pledge_id);
            }
        }
        
        if ($affected_rows > 0) {
            $this->session->set_flashdata('success', 'Billing for Donation is updated successfully');
            $Donation = $this->donation_model->donation_pledge_data_by_id($donation_data->pledge_id);
            if($Donation->pledge_amount == $Donation->amount) {
                $pledge_status = 0;
            } else {
                $pledge_status = 1;
            }
            $update = array (
                'pledge_status' => $pledge_status
            );
            
            $this->donation_model->update_donation_pledge($update,$donation_data->pledge_id);
            if($this->input->post('AmountType') != 2) {
                $paid_hidden_id = $this->input->post('paid_hidden_id');
                if(!empty($paid_hidden_id)) :
                    $paidType = $this->donation_model->delete_payment_by_paid_id($paid_hidden_id);
                endif;
                $pay_type = $this->input->post('pay_type');
                
                foreach( $pay_type as $key => $value ) {
                    if($value != '') {
                        $this->db->select('slug');
                        $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $key) );
                        $prow = $q->row_array();
                       
                        $pay_details = array();
                        if( $prow['slug'] == 'cheque' && !empty($value) ) :
                            // Cheque
                            $e = explode('-', $this->input->post('chq_date'));
                            $pay_details = array(
                               'name'   => $this->input->post('chq_bnk_name'),
                               'no'   => $this->input->post('chq_no'),
                               'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                            );
                        endif;
                        
                        $pay_details = json_encode( $pay_details );
                        $insert = array(
                            'pay_ref_type'  => 4,
                            'pay_ref_id'    => $this->input->post('hidden_id'),
                            'pay_type_id'   => $key,
                            'pay_amount'    => $value,
                            'pay_details'   => $pay_details,
                            'status'        => 1,
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => $Donate->created_on
                        );
                        $this->donation_model->insert_payment($insert);
                    }
                }
            }

            if($this->input->post('hidden_pledge_type') == 1 && $this->input->post('old_amount') < $this->input->post('cs_amount')) {
                /*** To Print Receipt - Start ***/
                $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('fn_type'));
                $service_menu = $this->login_details_model->get_service_menu_by_id($this->input->post('type_id'));
                $prefix = get_general_setting()->prefix;
                
                /* if(!empty($this->input->post('balance_amount'))) {
                    $paid_amt = ($this->input->post('pledging_amount') - $this->input->post('balance_amount')) + ($this->input->post('old_amount')) + ($this->input->post('cs_amount'));
                } else { */
                    $paid_amt = $this->input->post('cs_amount');
                //}
                $args = array(
                    'type'      => '1', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
                    'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $this->input->post('rec_no'),
                    'title'     => $service_menu->service_name . ' - ' .$gst_details->name,
                    /* (($this->input->post('AmountType') != 2) ? 'amount' : 'item' )   => (
                        ($this->input->post('hidden_pledge_type') == 1) ? (($this->input->post('AmountType') == 1 ) ? array($this->input->post('pledging_amount'),number_format($paid_amt,2,'.',''),$this->input->post('paid_amount')) : array($this->input->post('pledging_item'),number_format($paid_amt,2,'.',''),number_format(($this->input->post('cs_amount') - $this->input->post('old_amount')),2,'.',''))) : array($this->input->post('paid_amount'))
                    ) ,*/
                    'gst'       => (($this->input->post('AmountType') != 2 ) ? $gst_details->gst : ''),
                    'printType' => FALSE,
                    
                    'data'      => array(
                        // Type = 1 && 3 
                        'name'      => array($this->input->post('name').','.htmlspecialchars( $this->input->post('tamil_name') )),
                        'contact_no'=> $this->input->post('contact_no'),
                        'email'     => $this->input->post('ct_email'),
                        'address'   => $this->input->post('ct_address'),
                        'desc'      => $this->input->post('cs_desc'),
                    ),
                    
                );
                
                if($this->input->post('AmountType') == 1) {
                    $total_amt = $this->input->post('pledging_amount');
                    $Paid = number_format($paid_amt,2,'.','');
                    $payNow = $this->input->post('paid_amount');
                } else if($this->input->post('AmountType') == 2){
                    $total_amt = $this->input->post('pledging_item');
                    $Paid = number_format($paid_amt,2,'.','');
                    $payNow = number_format(($this->input->post('pledging_item') - $this->input->post('cs_amount')),2,'.','');
                }
                
                
                $a = ($this->input->post('hidden_pledge_type') == 1) ? array($total_amt,$Paid,$payNow) : array($this->input->post('paid_amount'));
                if( $this->input->post('AmountType') == 2 ) :
                    $args['data']['section'] = array(
                        array(
                            'Total Items<div class="sub-lbl"> மொத்த பொருட்கள்</div>'   => $a[0] . ' gms',
                            'Given Items<div class="sub-lbl"> கொடுக்கப்பட்ட  பொருட்கள்</div>'    => $a[1] . ' gms',
                        ),
                        'Pending Items<div class="sub-lbl"> நிலுவையிலுள்ள  பொருட்கள்</div>'  => $a[2] . ' gms' 
                    );
                
                else :
                    $args['amount'] = $a;
                    
                endif;
                #echo '<pre>'; print_r($args);die;
                print_rec($args);            
                /*** End ***/
            }
        } else 
            $this->session->set_flashdata('error', 'Billing for Donation is not updated!');
        
        redirect('billing_donation', 'refresh');
    }
    
    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['donation'] = $this->donation_model->get_by_id($id);
        $data['transaction_data'] = $this->donation_model->get_pledge_transaction_details($data['donation']->service_id,$data['donation']->name,$data['donation']->contact_no,$data['donation']->pledge_id);
        $data['payments'] = $this->donation_model->get_paid_type_by_id($data['donation']->type_id,$id);
        $data['transaction'] = $this->donation_model->get_pledge_transaction_details_by_id($data['donation']->service_id,$data['donation']->name,$data['donation']->contact_no,$data['donation']->receipt_no);
        $data['balance'] = $this->donation_model->get_balance_amt_by_id($data['transaction']->pledge_id,$data['transaction']->id);
        $data['paid_amount'] = $this->donation_model->total_paid_amount($data['donation']->type_id,$data['donation']->id);
        $data['title'] = 'Donation';
        $this->render($data, 'billing/donation/view');
    }
    
    public function delete($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $donation = $this->donation_model->get_by_id($id);
        
        $donation_last = $this->donation_model->get_pledge_last_data($donation->service_id,$donation->name,$donation->contact_no);
        #echo '<pre>';print_r($donation_last);die;
        #if($donation->pledge_type == 0) {
            $update = array ( 
                'amount' => 0,
                'status' => 2,
                'del_reason' => $this->input->post('hidden_del_reason'),
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            
            $affected_rows = $this->donation_model->update($update,$id);
            
            $update = array ( 
                'status' => 2,
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            $this->donation_model->update_transaction($update,$id,$donation->receipt_no);
        
        #}

        if ($affected_rows > 0) {
            $this->session->set_flashdata('success', 'Billing for Donation is deleted successfully');
            if($donation->pledge_type != 2) {
                $update = array ( 
                    'pay_amount' => 0,
                    'updated_by' => $this->user_data['user_id'],
                    'updated_on' => date('Y-m-d H:i:s')
                );
                
               $this->donation_model->update_paid_type($update,$donation->type_id,$id);
               $this->donation_model->update_refund(array('status' => 2),$donation->type_id,$id);
            }
            
            $old_donation = $this->donation_model->donation_pledge_data_by_id($donation->pledge_id);
           
            if($old_donation->amount > 0) {
                $paid_amount = $old_donation->amount - $donation->amount;
                $pledge_status = 1;
            } else {
                $paid_amount = 0;
                $pledge_status = 1;
            }
          
            $status = ($paid_amount > 0) ? 1 : 2;
            
            $update = array (
                'd_id' => $donation_last->id,
                'amount' => $paid_amount,
                'pledge_status' => $pledge_status,
                'status' => $status
            );
            $this->donation_model->update_donation_pledge($update,$old_donation->id);
        }
        
        else 
            $this->session->set_flashdata('error', 'Billing for Donation is not deleted!');
        
        redirect( 'billing_donation', 'refresh');
    }
    
    public function get_amount_by_service_id() {
        $data =  $this->donation_model->get_amount_by_service_id($_POST['service_type']);
        echo json_encode($data);
        exit(0);
    }
    
    public function get_data_by_service_type(){
        $data['get_data'] =  $this->donation_model->get_data_by_service_type($_POST['service_type']);
        $data['get_contact'] =  $this->donation_model->get_contact_by_service_type($_POST['service_type']);
        echo json_encode($data);
        exit(0);
    }
    
    public function ajax() {
        $data =  $this->donation_model->ajax();
        echo json_encode($data);
        exit(0);  
    }
    
    public function get_pledge_amount_details() {
        $rows =  $this->donation_model->get_pledge_amount_details($_POST['service_type'],$_POST['name'],$_POST['contact_no']);
        $data = array();
        if($rows > 0) {
            $data['pledge_data'] = $this->donation_model->get_pledge_amount_details_by_data($_POST['service_type'],$_POST['name'],$_POST['contact_no']);
            $data['transaction_data'] = $this->donation_model->get_pledge_transaction_details($_POST['service_type'],$_POST['name'],$_POST['contact_no'],$data['pledge_data']->id);
        }
        echo json_encode($data);
        exit(0);
    }
    
    public function print_transaction_details($service_type,$name,$contact_no){
        $rows =  $this->donation_model->get_pledge_amount_details($service_type,$name,$contact_no);
        if($rows > 0) {
            $pledge_data = $this->donation_model->get_pledge_amount_details_by_data($service_type,$name,$contact_no);
            $transaction_data = $this->donation_model->get_pledge_transaction_details($service_type,$name,$contact_no,$pledge_data->id);
            $body = array();
            foreach($transaction_data as $key=>$value) {
               $body[] = array(date('d M Y',strtotime($value->pledge_date)),$value->receipt_no,$value->amount);
            }
            
            $args = array(
                'type'      => '6', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai, '6' => Common
                'rec_no'    => $pledge_data->receipt_no,
                'title'     => 'Donation Transaction Details',//$main_service['service_name']. ' - '.$service['name'],
                'amount'    => array(''),
                'copy'      => FALSE,
                'printType' => FALSE,
                
                'data'      => array(
                    // Type = 6
                   'fields'  => array(
                        'Name'   => $pledge_data->name,
                        'Pledge Amount/Item' => $pledge_data->pledge_amount,
                        'Amount/Item'   => $pledge_data->amount,
                    ),
                    
                    'tables' => array(
                        'head'  => array('Date', 'Ref No','Amount'),
                        'body'  => $body,
                    ),
                ),
            );
            
            print_rec($args); 
        }
        
        redirect( 'billing_donation/add/4', 'refresh');
    }
    
    public function print_list($id,$menu_id) {
        $donation = $this->donation_model->get_by_id($id);
		$paymentDetails = $this->donation_model->get_payment_date($id);
        #echo '<pre>';print_r($donation);die;
        /*** To Print Receipt - Start ***/
        $gst_details = $this->login_details_model->get_amount_by_service_id($donation->service_id);
        $service_menu = $this->login_details_model->get_service_menu_by_id($donation->type_id);
        $prefix = get_general_setting()->prefix;
        
        $args = array(
            'type'      => '1', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
            'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $donation->receipt_no,
            'title'     => $service_menu->service_name . ' - ' .$gst_details->name,
            #'amount'    => (($donation->amount_type != 2 ) ? array($donation->amount) : array('0.00')),
            
            'gst'       => (($donation->amount_type != 2 ) ? $gst_details->gst : ''),
            'status'    => $donation->status,
            'printType' => FALSE,
	        'payment_date' => date('d/m/Y h:i A',strtotime($paymentDetails[0]['created_on'])),
            
            'data'      => array(
                // Type = 1 && 3 
                'name'      => array($donation->name.','.$donation->tamil_name),
                'contact_no'=> $donation->contact_no,
                'email'     => $donation->email,
                'address'   => $donation->address,
                'desc'      => $donation->desc,
            ),
            
        );
        
        if($donation->amount_type == 1) {
            $paidNow = $donation->amount;
        } else if($donation->amount_type == 2) {
            $paidNow = number_format(($donation->pledge_amount - $donation->amount),2,'.','');
        }
        
        $a = ($donation->pledge_type == 1) ? array($donation->pledge_amount,$donation->amount,$paidNow) : array($donation->amount);
        if( $donation->amount_type == 2 ) :
            $args['data']['section'] = array(
                array(
                    'Total Items<div class="sub-lbl"> மொத்த பொருட்கள்</div>'   => $a[0] . ' gms',
                    'Given Items<div class="sub-lbl"> கொடுக்கப்பட்ட  பொருட்கள்</div>'    => $a[1] . ' gms',
                ),
                'Pending Items<div class="sub-lbl"> நிலுவையிலுள்ள  பொருட்கள்</div>'  => $a[2] . ' gms' 
            );
        else :
            $args['amount'] = $a;
            
        endif;
        
        
       //echo "<pre>"; print_r( $args ); die;
        
        if(print_rec($args))
            $this->session->set_flashdata('success', 'Receipt has been printed successfully');
        
        else 
            $this->session->set_flashdata('error', 'Receipt has not been printed!');
            
        /*** End ***/
        
        redirect( 'billing_donation/index/' . $menu_id, 'refresh');
    }
  	
	function donation_bill_amount() {
		$display_pole_set 	= get_display_pole_data();
		$amount 			=  $_POST['amount'];
		//$this->session->set_flashdata('bill_paid_amount', $amount);
		//DISPLAY POLE TEXT CONTENT
		if($display_pole_set['pole_setting']['status'] == 1){
			exec("mode ".$display_pole_set['port_val']['value'].": BAUD=9600 PARITY=n DATA=8 STOP=1 to=off dtr=off rts=off");
			$fp =fopen($display_pole_set['port_val']['value'], "w+");
			fwrite($fp,"\x0c");
			fwrite($fp, "DONATION\n\rTOTAL : $".$_POST['amount']); //write string to serial
		}
	} 
} 
?>