<?php

/* 
 * Author       : Jai K
 * Purpose      : The controller for Kattalai Archanai
 * Created On   : 2016-09-02 12:00
 */

class Billing_Kattalai_Archanai extends REF_Controller {
    public $controller;
    
    function __construct() {
        parent::__construct();
        
        $segments = $this->uri->segments;
        $this->controller = $segments[1];
        
        
        $this->load->model('billing/kattalai_archanai_model');
        $this->load->model('login_details_model');
        $this->load->model('login_details_model');
    }
    
    function index( $id='' ) {
        
        check_permission();
        $actions = $this->actions();
        
        $data = array(
            'title'          => 'Kattalai Archanai',
            'controller'     => $this->controller,
            'actions'        => $actions,
            
            'success'        => $this->session->flashdata('success'),
            'error'          => $this->session->flashdata('error'),
        );
        
        
        $data['add_btn']    = 'Create New Billing';
        $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_kattalai_archanai/print_list/';
        
        $data['results'] = $this->kattalai_archanai_model->get_all();
        //echo "<pre>Data: "; print_r( $data['results'] ); die;
        
        $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');
        // Load Views
        $this->render( $data, 'billing/kattalai-archanai/index' );
    }
    
    function add( $id='' ) {
        $this->manipulate( $id );
    }
    
    function edit( $id ) {
        $this->manipulate( $id, array( 'page' => 'edit' ) );
    }
    
    function view( $id ) {
        $this->manipulate( $id, array( 'page' => 'view' ) );
    }
    
    function export( $page = 'pdf', $id ) {
        $this->manipulate( $id, array( 'page' => $page ) );
    }
    
    function manipulate( $id, $args = array() ) {
        $actions = $this->actions();
        $service_menu = get_billing_controller($actions['controller']);
        $post = $this->input->post();
        $session_data = $this->session->userdata(TBL_PREFIX . 'user_logged_in');
        $token = $this->session->userdata( 'rtoken-'.$session_data['user_id'] );
        
        $page = $page_file_name = !empty( $args['page'] ) ? $args['page'] : 'add';
        $page_file_name         = $page == 'pdf' ? 'view' : $page_file_name;
        
        $is_book = !empty( $post['book_now'] ) ? TRUE : FALSE;
                
        $data = array(
            'id'                => $id,
            'title'             => 'Kattalai Archanai',
            'is_'.$page         => TRUE,
            'controller'        => $this->controller,
            'actions'           => $actions,
            'form_action'       => base_url() . $this->controller .'/'.$page.'/'.$id,
            'success'           => $this->session->flashdata('success'),
            'error'             => $this->session->flashdata('error'),
            
            'week'              => array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
        );
        
        if( $page != 'add' ) :
            // ID => Page ID
            
            $data['results'] = $this->kattalai_archanai_model->get_all_booked_details( $id );
            $data['items'] = $this->kattalai_archanai_model->get_items( $id );
            
            
            $data['payments'] = $this->kattalai_archanai_model->get_payments( $id );
        endif;
        
        $service_id = $page == 'add' ? $id : $data['results'][0]['service_id'];
        if( $page != 'add' ) :
            $service = $this->kattalai_archanai_model->get( TBL_SERVICE, array( 'id' => $service_id ) );
            $data['service'] = $service[0];
            $menu_id = $service[0]['menu_name'];
        else :
            $menu_id = $service_id;
        endif;
        
        if( $page == 'add' || $page == 'edit' ) :
            // ID => Menu id
            $data['token'] = $this->auto_generation_code( rand( 999, 9999 ) );
            $this->session->set_userdata( 'rtoken-'.$session_data['user_id'], $data['token'] );
            
            $data['gods']       = $this->kattalai_archanai_model->get( TBL_GOD_NAME, '', array('order_by' => 'name') );
            $data['stars']      = $this->kattalai_archanai_model->get( TBL_STAR, '', array('order_by' => 'name') );
            $data['ptypes']     = $this->kattalai_archanai_model->get( TBL_PAY_TYPE );
            $data['prasadams']  = $this->kattalai_archanai_model->get( TBL_PRASADAM, '', array('order_by' => 'name') );
            $data['payment_detail']   = $this->kattalai_archanai_model->payment_mode_lists();
            
            $data['fn_types']   = $this->kattalai_archanai_model->get( TBL_SERVICE, array( 'menu_name' => $menu_id ) );
        
        endif;
        
       // echo "<pre>Data: "; print_r( $data ); die;
        
        if( ( !empty( $post['submit'] ) || $is_book ) && $post['token'] == $token ) :
            // insert
            $insert_id = $this->kattalai_archanai_model->manipulate();

            if( $page == 'add' ) :
                if( $is_book ) :
                    $msg = $service_menu->service_name . ' is booked successfully.';
                else :
                    $msg = $service_menu->service_name . ' is added successfully.';
                endif;
            
            elseif( $page == 'edit' ) :
                if( $is_book ) :
                    $msg = $service_menu->service_name . ' booking is updated successfully.';
                else :
                    $msg = $service_menu->service_name . ' is updated successfully.';
                endif;
                
            endif;
            $this->session->set_flashdata('success', $msg);

            if($page == 'add' || $is_book) :
                redirect( $this->controller . '/add/' . $menu_id );
            else :
                // Redirect
                redirect( $this->controller . '/index/' . $menu_id );
            endif;

        endif;

        //echo "<pre>Data: "; print_r( $data ); die;
        
        // Load Views
        $this->render( $data, 'billing/kattalai-archanai/'.$page_file_name );
    }
    
    function delete( $id, $menu_id ) {
        $hidden_del_reason = $this->input->post('hidden_del_reason');
        $this->kattalai_archanai_model->delete( $id, $hidden_del_reason );
        
        // Redirect
        $this->session->set_flashdata('success', 'The record is deleted successfully');
        redirect( $this->controller . '/index/' . $menu_id );
        
    }
    
    function ajax() {
        $results =  $this->kattalai_archanai_model->ajax();
        
        echo json_encode( $results );
    }
    
    
    public function print_list($id,$menu_id) {
        $kattalai = $this->kattalai_archanai_model->get_by_id($id);
        #echo '<pre>';print_r($kattalai);
        
        /*
         * Print
         */
         
        $service_menu = $this->login_details_model->get_service_menu_by_id($kattalai->type_id);
        $gst_details = $this->login_details_model->get_amount_by_service_id($kattalai->service_id);
        $prefix = get_general_setting()->prefix;
        
        $q = $this->db->get_where(TBL_STAR, array( 'id' => $kattalai->bk_star_1 ));
        $star_1 =  $q->row_array();
        
        $q = $this->db->get_where(TBL_STAR, array( 'id' => $kattalai->bk_star_2 ));
        $star_2 =  $q->row_array();
       // print_r($star_2); echo $star_2['name']; echo "<br>"; die();
        
        //$print_args['amount'][] = $post['total_amount'];
        
        $kattalai_items = $this->kattalai_archanai_model->get_items_id($kattalai->id);
        #echo '<pre>';print_r($kattalai_items);die;
        
        $print_args = array();
        foreach( $kattalai_items as $k => $item ) :
            $exp_dates = explode(',', $item->bki_dates);
            
            $sub_total = $item->bki_amount;
            $start_date = $item->bki_from_date;
            $end_date = $item->bki_to_date;
            
            $this->db->select('name, tamil_name');
            $this->db->where_in('id', explode(',', $item->bki_god_ids));
            $q = $this->db->get_where(TBL_GOD_NAME, array());
            $gods = $q->result_array();
            
            $print_args['amount'][] = $sub_total;
            $print_args['data']['items'][] = $gods;
            $print_args['data']['date'][] = array(date("d/m/Y", strtotime($start_date)), date("d/m/Y", strtotime($end_date)));
            $print_args['data']['day'][] = $item->bki_day_type == '2' ? $this->kattalai_archanai_model->get_week_name( $item->bki_week_day ) : '';
            $print_args['data']['days'][] = $item->bki_no_days;
        endforeach;
        #echo '<pre>';print_r($print_args);die;
		
		//print_r($star_2); echo $star_2['name']; die();
		
        /*$args = array(
            'type'      => '6', // 11 2 Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai
            'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $kattalai->bk_rec_no,
            'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
            'amount'    => $print_args['amount'],
            'gst'       => $gst_details->gst,
            'copy'      => TRUE,
            'status'    => $kattalai->status,
            'data'      => array(
                
                // Type = 2
                'name'      => array(
                    $kattalai->bk_name_1 . ','. $star_1['name'] .','. $kattalai->bk_tamil_name_1 .','.$star_1['tamil_name'], 
                    $kattalai->bk_name_2 . ','. $star_2['name'] .','. $kattalai->bk_tamil_name_2 .','.$star_2['tamil_name'], 
                ),
                
                'items'     => $print_args['data']['items'],
                'date'      => $print_args['data']['date'],//array(date("d/m/Y", $bk_begin_strtime), date("d/m/Y", $bk_end_strtime)),
                'day'       => $print_args['data']['day'],
                //'weeks'     => $print_args['data']['week'],
                'days'      => $print_args['data']['days'],
                
            ),
            
        ); */
		
		
		
		$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'    => (($prefix == 1) ? $gst_details->prefix : '') . $kattalai->bk_rec_no,
               //'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
               //'amount'    => array($res->amount),
               'gst'       => $gst_details->gst,
               'short'     => TRUE,
               'copy'      => TRUE,
               'html'      => '<style>#items-table td:nth-child(2), #items-table td:last-child{text-align: right;}</style>', 
               'created_on' => $kattalai->created_on,

               'data'      => array( 

                   // Type = 6
                   'fields'  => array(
				   'Type'     => $service_menu->service_name . '-' . $gst_details->name,
                       //'Receipt No'    => (($prefix == 1) ? $gst_details->prefix : '') . $kattalai->bk_rec_no,
					   'Deity Name'=>$gods[0]['name'],
					   'Name'      => array(
                       $kattalai->bk_name_1 . ','. $star_1['name'], 
                       $kattalai->bk_name_2 . ','. $star_2['name'], 
                ),
                       'Date'          => $print_args['data']['date'][0],
                       'Day'          => $print_args['data']['day'][0],
                       'Total Days'   => $print_args['data']['days'],
                       'Amount'         => '<span style="font-weight: bold;">S$ '.$print_args['amount'][0].'</span>',
                   ),

                   



               ),

           );
		
		
		
		
        
        
        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_kattalai_archanai/index/' . $menu_id, 'refresh');
    }
    
    
    
} // class    

