<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Billing_other_services extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('billing/other_services_model', '', TRUE);
        $this->load->model('login_details_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index($id = 14) {
        $data = array();
        $data['results'] = $this->other_services_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 Service';
        $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_other_services/print_list/';
        $data['title'] = 'Other Services';
        
        $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/other_services/list');
    }
    
    public function add($type_id= '') {
        $data = array();
        $actions = $this->actions();
        $data['payments'] = $this->other_services_model->payment_mode_lists();
        $data['stars'] = $this->other_services_model->star_lists();
        $data['service_type'] = $this->other_services_model->get_service_type($type_id);
        $data['service_type_id'] = $type_id;
        
        $data['form_action'] = $actions['insert'];
        $data['title'] = 'Other Services';
        $this->render($data, 'billing/other_services/add');
    }
    
    private function get_other_service_url_key($name, $id = '') {
        $url_key = get_url_key($name);
        if ($this->other_services_model->other_service_url_key_exists($url_key, $id)) {
            $this->uri_key_index ++;
            return $this->get_other_service_url_key($name . '_' . $this->uri_key_index, $id);
        }
        
        return $url_key;
    }
    
    public function insert() {
        $services = $this->other_services_model->service_type_exists($this->input->post('service_type'));
        $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('service_type'));
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($this->input->post('amount'));
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        
        $insert = array(
            'devotee_name' => $this->input->post('devotee_name'),
            'tamil_name' => htmlspecialchars( $this->input->post('tamil_devotee_name') ),
            'star_id'=> $this->input->post('star'),
            'contact_no' => $this->input->post('contact_no'),
            'email' => $this->input->post('email'),
            'type_id' => $this->input->post('service_type_id'),
            'service_id'=> $this->input->post('service_type'),
            'address' => $this->input->post('address'),
            'period' => $this->input->post('period'),
            'date' => ((!empty($this->input->post('fn_date'))) ? date('Y-m-d',strtotime($this->input->post('fn_date'))) : NULL),
            'from_time' => date('H:i:s',strtotime($this->input->post('fn_from_time'))),
            'to_time'=> date('H:i:s',strtotime($this->input->post('fn_to_time'))),
            'url_key' => $this->get_other_service_url_key($this->input->post('devotee_name')),
            'desc' => $this->input->post('desc'),
            'amount' => $this->input->post('amount'),
            'gst' => $gst,
            'gst_value' => $gst_amount,
            'payment_mode' => $this->input->post('payment_mode'),
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        
        $insert_id = $this->other_services_model->insert($insert);
        
        if ($insert_id > 0) {
            $this->session->set_flashdata('success', 'Billing for Other Services 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->other_services_model->update($update, $insert_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'  => 14,
                        'pay_ref_id'    => $insert_id,
                        'pay_type_id'   => $key,
                        'pay_amount'    => trim($value),
                        'pay_details'   => $pay_details,
                        'status'        => 1,
                        'created_by'    => $this->user_data['user_id'],
                        'created_on'    => date('Y-m-d H:i:s')
                    );
                    $this->other_services_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;
            $other_service = $this->other_services_model->get_by_id($insert_id);
            $cdate = ''; $cdate = date('d-m-Y h:i:sa', strtotime($insert['created_on']));
            $args = array(
                'type'      => '1', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
                'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,
                'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
                'amount'    => array($this->input->post('amount')),
                'gst'       => $gst_details->gst,
                'printType' => FALSE,
                'fn_type' => 'other',
                'created_on' => $cdate,
                
                'data'      => array(
                    // Type = 1 && 3 
                    'name'      => array($this->input->post('devotee_name') .','. $other_service->star .','.  $this->input->post('tamil_devotee_name') .','. $other_service->star_tamil_name),
                    'contact_no'=> $this->input->post('contact_no'),
                    'email'     => $this->input->post('email'),
                    'address'   => $this->input->post('address'),
                    'desc'      => $this->input->post('desc'),
                    
                    'section'  => array(
                        array(
                            'Date<div class="linear-lbl"> தேதி</div>'      => ((!empty($this->input->post('fn_date'))) ? date('d/m/Y',strtotime($this->input->post('fn_date'))) : ' - '),
                            'Time<div class="linear-lbl"> நேரம்</div>'      => date('H:i',strtotime($this->input->post('fn_from_time'))) . ' - ' . date('H:i',strtotime($this->input->post('fn_to_time'))),
                            'Period<div class="linear-lbl"> காலம்</div>'    => ($this->input->post('period') == 1) ? 'Morning / காலை' : 'Evening / மாலை',
                        ),
                    ),
                ),
                
            );
            
            print_rec($args);            
            /*** End ***/
        }
        else
            $this->session->set_flashdata('error', 'Billing for Other Services is not added!');   
       
        redirect('billing_other_services', 'refresh');
    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['payments'] = $this->other_services_model->payment_mode_lists();
        $data['stars'] = $this->other_services_model->star_lists();
        $data['other_service'] = $this->other_services_model->get_by_id($id);
        $data['paid_amount'] = $this->other_services_model->total_paid_amount($data['other_service']->type_id,$data['other_service']->id);
        $data['service_type'] = $this->other_services_model->get_service_type($data['other_service']->type_id);
        
        $actions = $this->actions();
        $data['title'] = 'Other Services';
        $data['form_action'] = $actions['update'] . '/' . $id;
        $this->render($data, 'billing/other_services/edit');
    }
    
    public function update($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $other_service = $this->other_services_model->get_by_id($id);
        $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('service_type'));
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($this->input->post('amount'));
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
       
        $update = array(
            'devotee_name' => $this->input->post('devotee_name'),
            'tamil_name' => htmlspecialchars( $this->input->post('tamil_devotee_name') ),
            'star_id'=> $this->input->post('star'),
            'contact_no' => $this->input->post('contact_no'),
            'email' => $this->input->post('email'),
            'type_id' => $this->input->post('service_type_id'),
            'service_id'=> $this->input->post('service_type'),
            'address' => $this->input->post('address'),
            'period' => $this->input->post('period'),
            'date' => ((!empty($this->input->post('fn_date'))) ? date('Y-m-d',strtotime($this->input->post('fn_date'))) : NULL),
            'from_time' => date('H:i:s',strtotime($this->input->post('fn_from_time'))),
            'to_time'=> date('H:i:s',strtotime($this->input->post('fn_to_time'))),
            'url_key' => $this->get_other_service_url_key($this->input->post('devotee_name')),
            'desc' => $this->input->post('desc'),
            'amount' => $this->input->post('amount'),
            'gst' => $gst,
            'gst_value' => $gst_amount,
            'payment_mode' => $this->input->post('payment_mode'),
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
        
        if ($this->other_services_model->update($update, $id) > 0) {
            $this->session->set_flashdata('success', 'Billing for Other Services is updated successfully');
            
            $paid_hidden_id = $this->input->post('paid_hidden_id');
            if(!empty($paid_hidden_id)) {
                $paidtype = $this->other_services_model->delete_payment_by_paid_id($paid_hidden_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'  => 14,
                        'pay_ref_id'    => $id,
                        'pay_type_id'   => $key,
                        'pay_amount'    => trim($value),
                        'pay_details'   => $pay_details,
                        'status'        => 1,
                        'created_by'    => $this->user_data['user_id'],
                        'created_on'    => $other_service->created_on
                    );
                    $this->other_services_model->insert_payment($insert);
                }
            }         
        }
        else
            $this->session->set_flashdata('error', 'Billing for Other Services is not updated!');    
        
        redirect('billing_other_services','refresh');
    }
    
    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['other_service'] = $this->other_services_model->get_by_id($id);
        $data['paid_amount'] = $this->other_services_model->total_paid_amount($data['other_service']->type_id,$data['other_service']->id);
        $data['payments'] = $this->other_services_model->get_paid_type_by_id($data['other_service']->type_id,$id);
        $data['title'] = 'Other Services';
        $this->render($data, 'billing/other_services/view');
    }
    
    public function delete($id = '', $menu_id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $update = array ( 
            'amount' => 0,
            'del_reason' => $this->input->post('hidden_del_reason'),
            'status' => 2,
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
       
        if ($this->other_services_model->update($update,$id) > 0) {
            $this->session->set_flashdata('success', 'Billing for Other Services is deleted successfully');
            $other_service = $this->other_services_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->other_services_model->update_paid_type($update,$other_service->type_id,$id);
        }       
        else 
            $this->session->set_flashdata('error', 'Billing for Other Services is not deleted!');
        
        redirect( 'billing_other_services/index/' . $menu_id, 'refresh');
    }
    
    public function get_amount_by_service_id() {
        $data =  $this->other_services_model->get_amount_by_service_id($_POST['service_type']);
        echo json_encode($data);
        exit(0);
    }
    
    public function print_list($id,$menu_id) {
        $other_service = $this->other_services_model->get_by_id($id);
		$paymentDetails = $this->other_services_model->get_payment_date($id);
       
        /*** To Print Receipt - Start ***/
        $service_menu = $this->login_details_model->get_service_menu_by_id($other_service->type_id);
        $gst_details = $this->login_details_model->get_amount_by_service_id($other_service->service_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 : '') . $other_service->receipt_no,
            'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
            'amount'    => array($other_service->amount),
            'gst'       => $gst_details->gst,
            'status'    => $other_service->status,
            'printType' => FALSE,
	    	'payment_date' => date('d/m/Y h:i A',strtotime($paymentDetails[0]['created_on'])),
            
            'data'      => array(
                // Type = 1 && 3 
                'name'      => array($other_service->devotee_name .','. $other_service->star  .','.  $other_service->tamil_name .','. $other_service->star_tamil_name ),
                'contact_no'=> $other_service->contact_no,
                'email'     => $other_service->email,
                'address'   => $other_service->address,
                'desc'      => $other_service->desc,
                
                'section'  => array(
                    array(
                        'Date<div class="linear-lbl"> தேதி</div>'      => (($other_service->date != '') ? date('d/m/Y',strtotime($other_service->date))  : ' - '),
                        'Time<div class="linear-lbl"> நேரம்</div>'      => date('H:i',strtotime($other_service->from_time)) . ' - ' . date('H:i',strtotime($other_service->to_time)),
                        'Period<div class="linear-lbl"> காலம்</div>'    => ($other_service->period == 1) ? 'Morning / காலை' : 'Evening / மாலை',
                    ),
                ),
            ),
            
        );
        
        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_other_services/index/' . $menu_id, 'refresh');
    }
	
	function other_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, "OTHER SERVICES\n\rTOTAL : $".$_POST['amount']); //write string to serial
		}
	}
}
?>