<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Billing_membership_card extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('billing/membership_card_model', '', TRUE);
        $this->load->model('billing/member_subscription_model', '', TRUE);
        $this->load->model('login_details_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index($id = 12) {
        $data = array();
        $data['results'] = $this->membership_card_model->list_all();
        if (!empty($this->session->flashdata('success'))) 
            $data['success'] = $this->session->flashdata('success');
        else 
            $data['error'] = $this->session->flashdata('error');
        
        $actions = $this->actions();
        $data['add_btn']    = 'Create New User';
        $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_membership_card/print_list/';
        $data['title'] = 'Membership Card';
        $data['type_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/membership_card/index');
    }
    
    public function add($id = 12) {
        $data = array();
        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 Membership Card';
        $data['view_link']  = $actions['view'] . '/';
        $data['add_link']   = $actions['add'] . '/' . $id ;
        $data['edit_link']  = $actions['edit'] . '/';
        $data['delete_link']= $actions['delete'] . '/';
        $data['title'] = 'Membership Card Registration & Topup (Billing)';
        
        $data['payments'] = $this->membership_card_model->payment_mode_lists();
        $data['form_action'] = base_url() . 'billing_membership_card/topup';
        $this->render($data, 'billing/membership_card/add');
    }
    
     private function get_membership_card_url_key($name, $id = '') {
        $url_key = get_url_key($name);
        if ($this->membership_card_model->membership_card_url_key_exists($url_key, $id)) {
            $this->uri_key_index ++;
            return $this->get_membership_card_url_key($name . '_' . $this->uri_key_index, $id);
        }
        
        return $url_key;
    }
    
    public function user_add($type_id= '') {
        $data = array();
        $actions = $this->actions();
        $data['stars'] = $this->membership_card_model->star_lists();
        $data['payments'] = $this->membership_card_model->payment_mode_lists();
        $data['service_type'] = $this->membership_card_model->get_service_type($type_id);
        $data['service_type_id'] = $type_id; 
        
        $data['form_action'] = $actions['insert'];
        $data['title'] = 'Membership Card Registration';
        $this->render($data, 'billing/membership_card/list');
    }
    
    public function insert() {
        $password = $this->random_password();
        $services = $this->membership_card_model->service_type_exists();
        if($this->input->post('hidden_id') == '') { 
            $url_key = $this->get_membership_card_url_key($this->input->post('name'));
            $insert = array(
                'type_id' => $this->input->post('service_type_id'),
                'card_no' => $this->input->post('card_no'),
                'name' => $this->input->post('name'),
                'tamil_name' => htmlspecialchars( $this->input->post('tamil_name') ),
                'star' => $this->input->post('star'),
                'contact_no' => $this->input->post('contact_no'),
                'email' => $this->input->post('email'),
                'address' => $this->input->post('address'),
                'password' => $password,
                'amount' => $this->input->post('amount'),
                'url_key' => $url_key,
                'created_by' => $this->user_data['user_id'],
                'created_on' => date('Y-m-d H:i:s')
            );
            
            $insert_id = $this->membership_card_model->insert($insert);
            
            if ($insert_id > 0) {
                $this->session->set_flashdata('success', 'User details is created 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->membership_card_model->update($update, $insert_id);
            
                $mem_name = $this->input->post('mem_name');
                $mem_name_tamil = $this->input->post('mem_name_tamil');
                $mem_star = $this->input->post('mem_star');
                foreach($mem_name as $key=>$value) {
                    $insert = array(
                        'mem_reg_id' => $insert_id,
                        'name' => $value,
                        'tamil_name' => $mem_name_tamil[$key],
                        'star'=> $mem_star[$key],
                        'created_by' => $this->user_data['user_id'],
                        'created_on' => date('Y-m-d H:i:s')
                    );
                    $this->membership_card_model->insert_reg_mem($insert);
                }
                
                $insert = array(
                    'mem_id' => $insert_id,
                    'topup_amount' => $this->input->post('amount'),
                    'mem_first_data' => 1,
                    'created_by' => $this->user_data['user_id'],
                    'created_on' => date('Y-m-d H:i:s')
                );
                
                $this->membership_card_model->insert_topup($insert);
                
                $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'  => 12,
                            '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->membership_card_model->insert_payment($insert);
                    }
                }
                
                /*** To Print Receipt - Start ***/
                $service_menu = $this->login_details_model->get_service_menu_by_id($this->input->post('service_type_id'));
                $prefix = get_general_setting()->prefix;
            
                $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'    => $receipt_no,
                    'title'     => 'MEMBERSHIP CARD REGISTRATION', //$service_menu->service_name,
                    'amount'    => array(''),
                    'copy'      => FALSE,
                    'short'     => TRUE,
                    
                    'data'      => array(
                        // Type = 6
                       'fields'  => array(
                            'Card Number'        => $this->input->post('card_no'),
                            'Card Holder Name'   => $this->input->post('name'),
                            'Card Value'         => number_format($this->input->post('amount'),2,'.',''),
                            'Password'           => $password,
                        ),
                    ),
                );
                
                print_rec($args);
                /*** End ***/
                
            }
            else
                $this->session->set_flashdata('error', 'User details is not created successfully!');   
        } else {
            $mem_name = $this->input->post('mem_name');
            $mem_name_tamil = htmlspecialchars( $this->input->post('mem_name_tamil') );
            $mem_star = $this->input->post('mem_star');
            foreach($mem_name as $key=>$value) {
                $insert = array(
                    'mem_reg_id' => $this->input->post('hidden_id'),
                    'name' => $value,
                    'tamil_name' => $mem_name_tamil[$key],
                    'star'=> $mem_star[$key],
                    'created_by' => $this->user_data['user_id'],
                    'created_on' => date('Y-m-d H:i:s')
                );
                $this->membership_card_model->insert_reg_mem($insert);
            }
        }
        redirect('billing_membership_card', 'refresh');
    }
    
    public function random_password($length = 4) {
		$chars = "0123456789";
		$password = substr(str_shuffle($chars), 0, $length);
		return $password;
	}
    
    public function topup(){
        $last_entry = $this->membership_card_model->get_last_entry();
        
        if($last_entry->num_rows() > 0) {
            $last_receipt_no = $last_entry->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';
        
        $insert = array(
            'mem_id' => $this->input->post('mem_id'),
            'receipt_no' => $receipt_no,
            'topup_amount' => $this->input->post('topup_amount'),
            'mem_first_data' => 0,
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        
        $insert_id = $this->membership_card_model->insert_topup($insert);
        
        if($insert_id > 0) {
            $this->session->set_flashdata('success', 'Membership Card topup successfully');
            
            $card_details = $this->membership_card_model->get_by_id($this->input->post('mem_id'));
            $amount = $card_details->amount + $this->input->post('topup_amount');
            
            $update = array(
                'amount' => $amount,
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            
            $this->membership_card_model->update($update,$this->input->post('mem_id'));
            
            $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'  => 12,
                        'pay_ref_id'    => $this->input->post('mem_id'),
                        'pay_type_id'   => $key,
                        'mem_card_id'   => $insert_id,
                        '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->membership_card_model->insert_payment($insert);
                }
            }
            
            /*** To Print Receipt - Start ***/
        
            $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'    => $receipt_no,
                'title'     => 'Membership Card Topup',
                'amount'    => array(''),
                'copy'      => FALSE,
                'short'     => TRUE,
                
                'data'      => array(
                    // Type = 6
                   'fields'  => array(
                        'Card Number'        => $card_details->card_no,
                        'Card Holder Name'   => $card_details->name,
                        'Topup Amount'       => number_format($this->input->post('topup_amount'),2,'.',''),
                        'Total Amount'       => number_format($amount,2,'.',''),
                    ),
                ),
            );
            
            print_rec($args);
            /*** End ***/
        } 
        else
            $this->session->set_flashdata('error', 'Membership Card not topup!');
        
        redirect('billing_membership_card/add', 'refresh');
    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $actions = $this->actions();
        $data['form_action'] = $actions['update'] . '/' . $id;
        
        $data['member'] = $this->membership_card_model->get_by_id($id);
        $data['stars'] = $this->membership_card_model->star_lists();
        $data['payments'] = $this->membership_card_model->payment_mode_lists();
        $data['member_list'] = $this->membership_card_model->get_members_by_id($id);
        
        $data['title'] = 'Membership Card Registration & Topup';
        $this->render($data, 'billing/membership_card/edit');
    }
    
    public  function update($id){
        if (empty($id)) {
            show_400_error();
        }
        $url_key = $this->get_membership_card_url_key($this->input->post('name'));
        $update = array(
            'type_id' => $this->input->post('service_type_id'),
            'card_no' => $this->input->post('card_no'),
            'name' => $this->input->post('name'),
            'tamil_name' => htmlspecialchars( $this->input->post('tamil_name') ),
            'star' => $this->input->post('star'),
            'contact_no' => $this->input->post('contact_no'),
            'email' => $this->input->post('email'),
            'address' => $this->input->post('address'),
            #'password' => $this->random_password(),
            #'amount' => $this->input->post('amount'),
            'url_key' => $url_key,
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
        
        $affected_rows = $this->membership_card_model->update($update,$id);
        
        if($affected_rows > 0) {
           $this->session->set_flashdata('success', 'User details is updated successfully');
           
            // Set status for removed Items
            if( !empty( $this->input->post('removed-items') ) ) :
                
                $e = explode("-", trim($this->input->post('removed-items'), '-'));
                foreach( $e as $k => $rm_id ) :
                    $this->membership_card_model->update_mem_reg(array('status' => 2),$rm_id);
                endforeach;
                
            endif;
            
            
            foreach( $this->input->post('mem_name') as $k => $mem_name ) :
            
            
                $args = array(
                    'name'        => $mem_name,
                    'tamil_name'   => htmlspecialchars( $this->input->post('mem_name_tamil')[$k] ),
                    'star'       => $this->input->post('mem_star')[$k]
                );
                
                if( empty( $this->input->post('mem_id')[$k] ) ) :
                    // Insert
                    $args['mem_reg_id'] = $id;
                    $args['created_on'] = date('Y-m-d H:i:s');
                    $args['created_by'] = $this->user_data['user_id'];

                    $this->membership_card_model->insert_reg_mem($args);
                    
                else :
                    // Update
                    
                    $args['updated_on'] = date('Y-m-d H:i:s');
                    $args['updated_by'] = $this->user_data['user_id'];

                    $this->membership_card_model->update_mem_reg( $args, $this->input->post('mem_id')[$k]);
                    
                endif;

            endforeach;
        
            /* $paidtype = $this->member_subscription_model->delete_paid_type($this->input->post('service_type_id'),$id);
            
            $pay_type = $this->input->post('pay_type');
            foreach( $pay_type as $key => $value ) {
                if($value > 0 && $value != '') {
                    $insert = array(
                        'pay_ref_type'  => 12,
                        'pay_ref_id'    => $id,
                        'pay_type_id'   => $key,
                        'pay_amount'    => $value,
                        'status'        => 1,
                        'created_by'    => $this->user_data['user_id'],
                        'created_on'    => date('Y-m-d H:i:s')
                    );
                    $this->membership_card_model->insert_payment($insert);
                }
            } */
            
        } else 
            $this->session->set_flashdata('error', 'User details is not updated!');
        
        redirect( 'billing_membership_card', 'refresh');
    }

    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['member'] = $this->membership_card_model->get_by_id($id);
        $data['payments'] = $this->membership_card_model->payment_mode_lists();
        $data['member_list'] = $this->membership_card_model->get_members_by_id($id);
        $data['ptypes'] = $this->membership_card_model->get_paid_type_by_id($data['member']->type_id,$id);
        
        $data['title'] = 'Membership Card Registration & Topup';
        $this->render($data, 'billing/membership_card/view');
    }
    
    public function delete($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $update = array ( 
            'amount' => 0,
            'del_reason' => $this->input->post('hidden_del_reason'),
            'status' => 2,
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );

        if ($this->membership_card_model->update($update,$id) > 0) {
            $this->session->set_flashdata('success', 'User is deleted successfully');
            $member = $this->membership_card_model->get_by_id($id);
            
            $update = array ( 
                'pay_amount' => 0,
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            
            $this->membership_card_model->update_paid_type($update,$member->type_id,$id);
            
            $this->membership_card_model->update_mem_reg(array('status' => 2),$id);
            
            $update = array ( 
                'topup_amount' => 0,
                'status' => 2,
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            $this->membership_card_model->update_mem_topup($update,$id);
        }
           
        else 
            $this->session->set_flashdata('error', 'User is not deleted!');
        
        redirect( 'billing_membership_card', 'refresh');
    }
    
    public function get_t_card_details(){
        $data = $this->membership_card_model->get_t_card_details($_POST['card_no']);
        echo json_encode($data);
        exit(0);
    }
    
    public function check_valid_pwd() {
        $data = $this->membership_card_model->check_valid_pwd($this->user_data['user_id']);
        echo json_encode($data);
        exit(0);
    }
    
    public function check_contact_email_exists() {
        $data = $this->membership_card_model->check_contact_email_exists($_POST['field_name'],$_POST['id'],$_POST['val']);
        echo json_encode($data);
        exit(0);
    }
    
    public function print_list($id,$menu_id) {
        $member = $this->membership_card_model->get_by_id($id);
        
        /*** To Print Receipt - Start ***/
        $service_menu = $this->login_details_model->get_service_menu_by_id($member->type_id);
        $prefix = get_general_setting()->prefix;
    
        $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'    => $member->receipt_no,
            'title'     => 'MEMBERSHIP CARD REGISTRATION', //$service_menu->service_name,
            'amount'    => array(''),
            'status'    => $member->status,
            'copy'      => FALSE,
            'short'     => TRUE,
            
            'data'      => array(
                // Type = 6
               'fields'  => array(
                    'Card Number'        => $member->card_no,
                    'Card Holder Name'   => $member->name,
                    'Card Value'         => number_format($member->amount,2,'.',''),
                    'Password'           => $member->password,
                ),
            ),
        );
        
        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_membership_card/index/' . $menu_id, 'refresh');
    }
}
?>