<?php
/* 

 * Author       : Jai K

 * Purpose      : The controller for Abishegam

 * Created On   : 2016-07-30 18:34

 */



class Billing_Abishegam extends REF_Controller {

    public $controller;

    

    function __construct() {

        parent::__construct();

        

        $segments = $this->uri->segments;

        $this->controller = $segments[1];
        $this->load->model('billing/abishegam_model');
        $this->load->model('login_details_model','',TRUE);
		$this->uri_key_index = 0;

    }

    

    function index( $id='' ) {
        check_permission();

        $actions = $this->actions();

        

        $data = array(

            'title'          => 'Abishegam OLD',

            '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_abishegam/print_list/';

        

        $data['menu_id'] = $id;

        $data['results'] = $this->abishegam_model->get_all();

        //echo "<pre>Data: "; print_r( $data); die;

        

        $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/abishegam/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();

        $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'             => 'Abishegam',

            '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'),

        );

        $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');

        

        if( $page != 'add' ) :

            // ID => Page ID

            

            $data['results'] = $this->abishegam_model->get_all_booked_details( $id );

            $data['items'] = $this->abishegam_model->get_items( $id );

            $data['payments'] = $this->abishegam_model->get_payments( $id );

        endif;

        

        $service_id = $page == 'add' ? $id : $data['results'][0]['service_id'];

        if( $page != 'add' ) :

            $service = $this->abishegam_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->abishegam_model->get( TBL_GOD_NAME,'', array('order_by' => 'name') );

            $data['stars']      = $this->abishegam_model->get( TBL_STAR, '', array('order_by' => 'name') );

            $data['ptypes']     = $this->abishegam_model->get( TBL_PAY_TYPE );

            $data['prasadams']  = $this->abishegam_model->get( TBL_PRASADAM, '', array('order_by' => 'name') );

            $data['payment_detail']   = $this->abishegam_model->payment_mode_lists();

            

            $data['fn_types']   = $this->abishegam_model->get( TBL_SERVICE, array( 'menu_name' => $menu_id ) );

        

        endif;

        

        $data[''] = $menu_id;

        

        if( ( !empty( $post['submit'] ) || $is_book ) && $post['token'] == $token ) :

            // insert

            $insert_id = $this->abishegam_model->manipulate();

            if( $page == 'add' ) :
                if( $is_book ) :
                   $msg = 'Abishegam is booked successfully.';
                else :
                    $msg = 'Billing for Abishegam is added successfully.';
                endif;
            elseif( $page == 'edit' ) :
                if( $is_book ) :
                    $msg = 'Abishegam booking is updated successfully.';
                else :
                    $msg = 'Billing for Abishegam is updated successfully.';
                endif;
            endif;

            $this->session->set_flashdata('success', $msg);
			
            if($page == 'add' || $is_book) :
				//echo "HERE: ".$this->controller;
                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/abishegam/'.$page_file_name );
    }

    

    function delete( $id, $menu_id ) {

        $hidden_del_reason = $this->input->post('hidden_del_reason');

        $this->abishegam_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->abishegam_model->ajax();

		echo json_encode($results);

    }

    

    public function get_prasadam_price() {

        $data = $this->abishegam_model->get_prasadam_price($_POST['id']);

        echo number_format($data->price,2);

    }

    

    public function print_list($id,$menu_id) {

        $abishegam = $this->abishegam_model->get_by_print($id);

        $items = $this->abishegam_model->get_items( $id );

		$paymentDetails = $this->abishegam_model->get_payment_date($id);



        #echo '<pre>';print_r($items);die;

        

        /*** To Print Receipt - Start ***/

        $service_menu = $this->login_details_model->get_service_menu_by_id(1);

        $gst_details = $this->login_details_model->get_amount_by_service_id($abishegam->service_id);

        $prefix = get_general_setting()->prefix;

        

        $gods = $prasadams= $print_body = array();

        foreach( $items as $k => $details ) :

        

            if( !array_key_exists( $details['god_id'], $gods ) ) :

                $q  =$this->db->get_where( TBL_GOD_NAME, array('id' => $details['god_id']) );

                $gods[$details['god_id']] = $q->row_array();

            endif;

            

            if( !array_key_exists( $details['prasadam_id'], $prasadams ) ) :

                $q  =$this->db->get_where( TBL_PRASADAM, array('id' => $details['prasadam_id']) );

                $prasadams[$details['prasadam_id']] = $q->row_array();

            endif;

            

            $print_body[] = array(

                (!empty($details['god_id']) ? ($gods[$details['god_id']]['name'] . ((!empty($gods[$details['god_id']]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $gods[$details['god_id']]['tamil_name'] .'</span>' : '')) : '<center> - </center>'),

                $prasadams[$details['prasadam_id']]['name'] . ((!empty($prasadams[$details['prasadam_id']]['tamil_name'])) ?  ' / <span class="linear-lbl lang-tamil">' . $prasadams[$details['prasadam_id']]['tamil_name'] .'</span>' : ''),

                '<div style="text-align: right;">'.$details['bai_qty'] . ' x ' . $details['bai_price'] .'</div>',

                '<div style="text-align: right;">'.number_format( $details['bai_qty']*$details['bai_price'], 2 ).'</div>',

            );

        endforeach;

            

        $args = array(

            'type'      => '1', 

            'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $abishegam->ba_rec_no,

            'title'     => $service_menu->service_name . ' - ' . $gst_details->name,

            'amount'    => array($abishegam->ba_paid_amount), // Currently Paid

            'gst'       => $gst_details->gst,

            'copy'      => TRUE,

            'status'    => $abishegam->status,

            'printType' => TRUE,

	    	'payment_date' => date('d/m/Y h:i A',strtotime($paymentDetails[0]['created_on'])),

            

            'data'      => array(

                

                // Type = 1 && 3 && 4

                'name'      => array($abishegam->ba_name_1 .','. $abishegam->star_name_1 .','. $abishegam->ba_tamil_name_1 . ',' . $abishegam->star_tamil_name1, $abishegam->ba_name_2 .','. $abishegam->star_name_2 .','. $abishegam->ba_tamil_name_2 . ',' . $abishegam->star_tamil_name2),

                'contact_no'=> $abishegam->ba_contact_no,

                'email'     => $abishegam->ba_email,

                // Type = 1 && 3

                'address'   => $abishegam->ba_address,

                'desc'      => $abishegam->ba_desc,

                

                'section'  => array(

                    array(

                        'Date<div class="sub-lbl"> தேதி</div>' => date('d/m/Y',strtotime($abishegam->ba_fn_from_date)),

                        'Time<div class="linear-lbl"> நேரம்</div>'      => date('H:i',strtotime($abishegam->ba_fn_from_date)) . ' - ' . date('H:i',strtotime($abishegam->ba_fn_to_date)),

                        'Period<div class="linear-lbl"> காலம்</div>'    => ($abishegam->ba_period == 1) ? 'Morning / காலை' : 'Evening / மாலை',

                        'Deity<div class="linear-lbl"> தெய்வம்</div>'     => ((!empty($abishegam->god_id)) ? $this->abishegam_model->get_deity_name($abishegam->god_id)->name : ''),

                    ),

                ),

                

                'tables' => array(

                    'head'  => array('God Name<div class="sub-lbl">கடவுள் பெயர்<div>', 'Prasadam Name<div class="sub-lbl">பிரசாதம்<div>','Qty x Unit Price($)<div class="sub-lbl">எண்ணிக்கை x ஒன்றின் விலை<div>', 'Amount($)<div class="sub-lbl">தொகை<div>'),

                    'body'  => $print_body,

                ),

                

            ),

            

        );

        

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

    }

	function abishegam_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, "ABISHEGAM\n\rTOTAL : $".$_POST['amount']); //write string to serial
		}
	}
    
} // class
?>