<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Billing_outdoor_services extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('billing/outdoor_services_model', '', TRUE);
        $this->load->model('login_details_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index($id = 13) {
        $data = array();
        $data['results'] = $this->outdoor_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 Outdoor Services';
        $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_outdoor_services/print_list/';
        $data['title'] = 'Outdoor 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/outdoor_services/list');
    }
    
    public function add($type_id= '') {
        $data = array();
        $actions = $this->actions();
        $data['fn_types'] = $this->outdoor_services_model->get( TBL_SERVICE, array( 'menu_name' => $type_id ) );
        $data['service_type_id'] = $type_id;
        $data['payments'] = $this->outdoor_services_model->payment_mode_lists();
        $data['priest'] = $this->outdoor_services_model->get_designation_list($designation="Priest");
        $data['nathaswaram'] = $this->outdoor_services_model->get_designation_list($designation="Nathaswaram");
        $data['melam'] = $this->outdoor_services_model->get_designation_list($designation="Melam");
        
        $data['form_action'] = $actions['insert'];
        $data['title'] = 'Outdoor Services';
        $this->render($data, 'billing/outdoor_services/add');
    }
    
    private function get_outdoor_url_key($name, $id = '') {
        $url_key = get_url_key($name);
        if ($this->outdoor_services_model->outdoor_url_key_exists($url_key, $id)) {
            $this->uri_key_index ++;
            return $this->get_outdoor_url_key($name . '_' . $this->uri_key_index, $id);
        }
        
        return $url_key;
    }
    
    public function insert() { //echo '<pre>';print_r($_POST);die;
        
        $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('fn_type'));
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($this->input->post('cs_amount'));
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        $e = explode("-", $this->input->post('fn_date'));
        $od_from_date = $e[2] . '-' . $e[1] . '-' . $e[0] . ' ' . $this->input->post('fn_from_time');
        $od_to_date = $e[2] . '-' . $e[1] . '-' . $e[0] . ' ' . $this->input->post('fn_to_time');

        $insert = array(
            'type_id' => $this->input->post('type_id'),
            'service_id' => $this->input->post('fn_type'),
            'date' => date('Y-m-d',strtotime($this->input->post('fn_date'))),
            'period' => $this->input->post('fn_period'),
            'from_time' => date('H:i',strtotime($this->input->post('fn_from_time'))),
            'to_time' => date('H:i',strtotime($this->input->post('fn_to_time'))),
            'od_from_date' => $od_from_date,
            'od_to_date' => $od_to_date,
            'devotee_name' => $this->input->post('name'),
            'tamil_name' => htmlspecialchars( $this->input->post('tamil_name') ),
            'contact_no1' => $this->input->post('contact_no1'),
            'contact_no2' => $this->input->post('contact_no2'),
            'email' => $this->input->post('ct_email'),
            'address' => $this->input->post('ct_address'),
            'postal_code' => $this->input->post('postal_code'),
            'priest_id' => $this->input->post('priest_name'),
            'nathaswaram_id' => $this->input->post('nathaswaram_name'),
            'melam_id' => $this->input->post('melam_name'),
            'desc' => $this->input->post('cs_desc'),
            'amount' => $this->input->post('cs_amount'),
            'gst' => $gst,
            'gst_value' => $gst_amount,
            'book_status' => (!empty($this->input->post('bookbtn'))) ? 2 : 1,
            'booked_date' => date('Y-m-d H:i:s'),
            'url_key' => $this->get_outdoor_url_key($this->input->post('name')),
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        
        $bk_status = $insert['book_status'];
        /*
        * Get last Receipt ID
        */
        $wh = array(
            'service_id'    => $insert['service_id'] ,
            'book_status'   => $bk_status
        );

        $receipt_no = generate_rec_no(TBL_BILL_OUTDOOR_SERVICES, $wh);
        $insert['receipt_no'] = $receipt_no;   
        
        //$services = $this->outdoor_services_model->service_type_exists($this->input->post('fn_type'), $bk_status);
        
        if (!empty($this->input->post('bookbtn'))) {
            $insert['updated_on'] = date('Y-m-d H:i:s');
        }

        $insert_id = $this->outdoor_services_model->insert($insert);
        
        if ($insert_id > 0) {
            $this->session->set_flashdata('success', 'Billing for Outdoor Service 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->outdoor_services_model->update($update, $insert_id);*/
           
            if($this->input->post('bookbtn') != 2) {
                $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'  => 13,
                            '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->outdoor_services_model->insert_payment($insert);
                    }
                }
                
                /*** To Print Receipt - Start ***/
                $service_menu = $this->login_details_model->get_service_menu_by_id($this->input->post('type_id'));
                $prefix = get_general_setting()->prefix;
                
                // Get Last Inserted Data By ID
                $outdoor = $this->outdoor_services_model->get_by_id($insert_id);
                
                $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('cs_amount')),
                    'gst'       => $gst_details->gst,
                    'printType' => FALSE,
                    
                    'data'      => array(
                        // Type = 1 && 3 
                        'name'      => array($this->input->post('name') .','.  $this->input->post('tamil_name')),
                        'contact_no'=> ($this->input->post('contact_no1') . ((!empty($this->input->post('contact_no2'))) ?  ', ' . $this->input->post('contact_no2') : '')),
                        'email'     => $this->input->post('ct_email'),
                        'address'   => $this->input->post('ct_address') . ((!empty($this->input->post('postal_code'))) ? ' / Postal Code: ' . $this->input->post('postal_code') : ''),
                        'desc'      => $this->input->post('cs_desc'),
                        
                        'section'  => array(
                            array(
                                'Function Date<div class="sub-lbl"> விழா தேதி</div>' => date('d/m/Y',strtotime($this->input->post('fn_date'))),
                                'Nathaswaram Name<div class="sub-lbl"> நாதஸ்வரம்</div>'   => $outdoor->nathaswaram_name,
                                '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'))),
                                'Priest Name<div class="linear-lbl"> ஐயர்  பெயர்</div>'   => $outdoor->priest_name,
                                'Period<div class="linear-lbl"> காலம்</div>'        => (($this->input->post('fn_period') == 2) ? 'Evening / மாலை' : 'Morning / காலை'),
                                'Melam Name<div class="sub-lbl"> மேளம்</div>'    => $outdoor->melam_name,
                            ),
                            
                            
                        ),
                    ),
                    
                );
                
                print_rec($args);            
                /*** End ***/
            }else{
				 redirect('billing_outdoor_services', 'refresh');	
			}
        }
        else
            $this->session->set_flashdata('error', 'Billing for Outdoor Service is not added!');   

        if(empty($this->input->post('book-now')))
            redirect('billing_outdoor_services', 'refresh');

        else
            redirect('billing_outdoor_services/add/' . $this->input->post('type_id'), 'refresh');
    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $actions = $this->actions();
        $data['form_action'] = $actions['update'] . '/' . $id;
        
        $data['outdoor'] = $this->outdoor_services_model->get_by_id($id);
        $data['paid_amount'] = $this->outdoor_services_model->total_paid_amount($data['outdoor']->type_id,$data['outdoor']->id);
        $data['fn_types'] = $this->outdoor_services_model->get( TBL_SERVICE, array( 'menu_name' => $data['outdoor']->type_id ) );
        $data['payments'] = $this->outdoor_services_model->payment_mode_lists();
        $data['priest'] = $this->outdoor_services_model->get_designation_list($designation="Priest");
        $data['nathaswaram'] = $this->outdoor_services_model->get_designation_list($designation="Nathaswaram");
        $data['melam'] = $this->outdoor_services_model->get_designation_list($designation="Melam");
        
        $data['title'] = 'Outdoor Services';
        $this->render($data, 'billing/outdoor_services/edit');
    }
    
    public  function update($id){ #echo '<pre>';print_r($_POST);die;
        if (empty($id)) {
            show_400_error();
        }
        
        $outdoor = $this->outdoor_services_model->get_by_id($id);
        $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('fn_type'));
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst;
            $gst_amount = ($gst / 100) * ($this->input->post('cs_amount'));
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        $e = explode("-", $this->input->post('fn_date'));
        $od_from_date = $e[2] . '-' . $e[1] . '-' . $e[0] . ' ' . $this->input->post('fn_from_time');
        $od_to_date = $e[2] . '-' . $e[1] . '-' . $e[0] . ' ' . $this->input->post('fn_to_time');

        $update = array(
            'type_id' => $this->input->post('type_id'),
            'service_id' => $this->input->post('fn_type'),
            'date' => date('Y-m-d',strtotime($this->input->post('fn_date'))),
            'period' => $this->input->post('fn_period'),
            'from_time' => date('h:i',strtotime($this->input->post('fn_from_time'))),
            'to_time' => date('h:i',strtotime($this->input->post('fn_to_time'))),
            'od_from_date' => $od_from_date,
            'od_to_date' => $od_to_date,
            'devotee_name' => $this->input->post('name'),
            'tamil_name' => htmlspecialchars( $this->input->post('tamil_name') ),
            'contact_no1' => $this->input->post('contact_no1'),
            'contact_no2' => $this->input->post('contact_no2'),
            'email' => $this->input->post('ct_email'),
            'address' => $this->input->post('ct_address'),
            'postal_code' => $this->input->post('postal_code'),
            'priest_id' => $this->input->post('priest_name'),
            'nathaswaram_id' => $this->input->post('nathaswaram_name'),
            'melam_id' => $this->input->post('melam_name'),
            'desc' => $this->input->post('cs_desc'),
            'amount' => $this->input->post('cs_amount'),
            'gst' => $gst,
            'gst_value' => $gst_amount,
            'book_status' => (!empty($this->input->post('book-now'))) ? 2 : 1,
            'url_key' => $this->get_outdoor_url_key($this->input->post('name')),
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
        
        $receipt_no = $outdoor->receipt_no;
        $bk_status = $update['book_status'];
        
        if( empty( $receipt_no ) || ($bk_status == "1" && $this->input->post('book_status') == "2" ) ) :
            /*
            * Get last Receipt ID
            */
            $wh = array(
                'service_id'    => $update['service_id'],
                'book_status'   => $bk_status
            );
            
            $receipt_no = generate_rec_no(TBL_BILL_OUTDOOR_SERVICES, $wh);
            $update['receipt_no'] = $receipt_no;   
            
            $created_date = date('Y-m-d H:i:s');
            
        else :
            //$update['created_on'] =  date('Y-m-d H:i:s');
            $created_date = $outdoor->created_on;
        endif;
        
        $affected_rows = $this->outdoor_services_model->update($update,$id);
        
        $editted_outdoor = $this->outdoor_services_model->get_by_id($id);
        
        if($affected_rows > 0) {
            if((empty($this->input->post('book-now')))) {
                $this->session->set_flashdata('success', 'Billing for Outdoor Service is updated successfully');
                
                #$paidtype = $this->outdoor_services_model->delete_paid_type($this->input->post('type_id'),$id);
                
                    
                $paid_hidden_id = $this->input->post('paid_hidden_id');
                if(!empty($paid_hidden_id)) :
                    $paidtype = $this->outdoor_services_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 > 0 && $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'  => 13,
                            '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'    => $created_date,
                        );
                        $this->outdoor_services_model->insert_payment($insert);
                    }
                }
                
                if($outdoor->book_status == 2) {    
                    /*** To Print Receipt - Start ***/
                    $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,
                        'amount'    => array($this->input->post('cs_amount')),
                        'gst'       => $gst_details->gst,
                        'printType' => FALSE,
                        
                        'data'      => array(
                            // Type = 1 && 3 
                            'name'      => array($this->input->post('name') .','.  $this->input->post('tamil_name')),
                            'contact_no'=> ($this->input->post('contact_no1') . ((!empty($this->input->post('contact_no2'))) ?  ', ' . $this->input->post('contact_no2') : '')),
                            'email'     => $this->input->post('ct_email'),
                            'address'   => $this->input->post('ct_address') . ((!empty($this->input->post('postal_code'))) ? ' / Postal Code: ' . $this->input->post('postal_code') : ''),
                            'desc'      => $this->input->post('cs_desc'),
                            
                            'section'  => array(
                                array(
                                    'Function Date<div class="sub-lbl"> விழா தேதி</div>' => date('d/m/Y',strtotime($this->input->post('fn_date'))),
                                    'Nathaswaram Name<div class="linear-lbl"> நாதஸ்வரம்</div>'   => $editted_outdoor->nathaswaram_name,
                                    
                                    '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'))),
                                    'Priest Name<div class="linear-lbl"> ஐயர்  பெயர்</div>'   => $editted_outdoor->priest_name,
                                    'Period<div class="linear-lbl"> காலம்</div>'        => (($this->input->post('fn_period') == 2) ? 'Evening  / மாலை' : 'Morning / காலை'),
                                    'Melam Name<div class="sub-lbl"> மேளம்</div>'    => $editted_outdoor->melam_name,
                                ),
                                
                            ),
                        ),
                        
                    );
                    
                    print_rec($args);           
                    /*** End ***/
                }
            } else {
                $this->session->set_flashdata('success', 'Billing for Outdoor Service is booked successfully');
            }
            
        } else 
            $this->session->set_flashdata('error', 'Billing for Outdoor Service is not updated!');
        
        if(empty($this->input->post('book-now')))
            redirect('billing_outdoor_services', 'refresh');

        else
            redirect('billing_outdoor_services/add/' . $this->input->post('type_id'), 'refresh');
    }
    
    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['outdoor'] = $this->outdoor_services_model->get_by_id($id);
        $data['paid_amount'] = $this->outdoor_services_model->total_paid_amount($data['outdoor']->type_id,$data['outdoor']->id);
        $data['payments'] = $this->outdoor_services_model->get_paid_type_by_id($data['outdoor']->type_id,$id);
        $data['title'] = 'Outdoor Services';
        $this->render($data, 'billing/outdoor_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->outdoor_services_model->update($update,$id) > 0) {
            $this->session->set_flashdata('success', 'Billing for Outdoor Service is deleted successfully');
            $outdoor = $this->outdoor_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->outdoor_services_model->update_paid_type($update,$outdoor->type_id,$id);
        }
        
        else 
            $this->session->set_flashdata('error', 'Billing for Outdoor Service is not deleted!');
        
        redirect( 'billing_outdoor_services/index/' . $menu_id, 'refresh');
    }
    
    public function get_amount_by_service_id() {
        $data =  $this->outdoor_services_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->outdoor_services_model->get_data_by_service_type($_POST['service_type']);
        echo json_encode($data);
        exit(0);
    }
    
    public function ajax() {
        $data =  $this->outdoor_services_model->ajax();		
        echo json_encode($data);
        exit(0);  
    }

    public function get_ajax() {
        $data =  $this->outdoor_services_model->get_ajax();
        echo json_encode($data);
        exit(0);  
    }
    
    public function print_list($id,$menu_id) {
        $outdoor = $this->outdoor_services_model->get_by_id($id);
	$paymentDetails = $this->outdoor_services_model->get_payment_date($id);
        
        /*** To Print Receipt - Start ***/
        $service_menu = $this->login_details_model->get_service_menu_by_id($outdoor->type_id);
        $gst_details = $this->login_details_model->get_amount_by_service_id($outdoor->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 : '') . $outdoor->receipt_no,
            'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
            'amount'    => array($outdoor->amount),
            'gst'       => $gst_details->gst,
            'status'    => $outdoor->status,
            'printType' => FALSE,
	    'payment_date' => date('d/m/Y',strtotime($paymentDetails[0]['created_on'])),
            
            'data'      => array(
                // Type = 1 && 3 
                'name'      => array($outdoor->devotee_name .','.  $outdoor->tamil_name),
                'contact_no'=> ($outdoor->contact_no1 . ((!empty($outdoor->contact_no2)) ? ', ' . $outdoor->contact_no2 : '')) ,
                'email'     => $outdoor->email,
                'address'   => $outdoor->address . ((!empty($outdoor->postal_code)) ? ' / Postal Code: ' . $outdoor->postal_code : ''),
                'desc'      => $outdoor->desc,
                
                'section'  => array(
                    array(
                        'Function Date<div class="sub-lbl"> விழா தேதி</div>' => date('d/m/Y',strtotime($outdoor->date)),
                        'Nathaswaram Name<div class="sub-lbl"> நாதஸ்வரம்</div>'   => $outdoor->nathaswaram_name,
                        'Time<div class="linear-lbl"> நேரம்</div>'          => date('H:i',strtotime($outdoor->from_time)) . ' - ' . date('H:i',strtotime($outdoor->to_time)),
                        'Priest Name<div class="linear-lbl"> ஐயர்  பெயர்</div>'   => $outdoor->priest_name,
                        'Period<div class="linear-lbl"> காலம்</div>'        => (($outdoor->period == 2) ? 'Evening  / மாலை' : 'Morning / காலை'),
                        'Melam Name<div class="sub-lbl"> மேளம்</div>'    => $outdoor->melam_name,
                    ),
                ),
            ),
            
        );
        #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_outdoor_services/index/' . $menu_id, 'refresh');
    }
    
} 
?>