<?php

/* 
 * Author       : Jai K
 * Purpose      : The controller for Billing - Wedding Hall Booking
 * Created On   : 2016-08-11 18:32
 */

class Billing_Wedding_Booking extends REF_Controller {
    public $controller;
    
    function __construct() {
        parent::__construct();
        
        $segments = $this->uri->segments;
        $this->controller = $segments[1];
        
        
        $this->load->model('billing/wedding_booking_model');
        $this->load->model('login_details_model');
    }
    
    function index( $id ) {
        
        check_permission();
        $actions = $this->actions();
        
        $data = array(
            'title'          => 'Wedding Hall Booked',
            'controller'     => $this->controller,
            'actions'        => $actions,
            
            'success'        => $this->session->flashdata('success'),
            'error'          => $this->session->flashdata('error'),
        );
        
        
        $data['add_btn']    = 'Create New Booking';
        $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_wedding_booking/print_list/';
        
        $data['results'] = $this->wedding_booking_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/wedding-booking/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;
        
        $data = array(
            'id'                => $id,
            'title'             => 'Wedding Hall Booking',
            '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'),
        );
        
        if( $page != 'add' ) :
            // ID => Page ID
            
            $data['results'] 				= $this->wedding_booking_model->get_all( $id );
            $data['payments'] 				= $this->wedding_booking_model->get_payments( $id );
			$data['additional_payments'] 	= $this->wedding_booking_model->get_additional_payments($id);
			
			//echo "<pre>"; print_r($data['additional_payments']); exit;
        endif;
        
        $service_id = $page == 'add' ? $id : $data['results'][0]['service_id'];
        if( $page != 'add' ) :
            $service = $this->wedding_booking_model->get( TBL_SERVICE, array( 'id' => $service_id ), array('order_by' => 'name') );
            $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['nos']        = $this->wedding_booking_model->get_nos();
            $data['ptypes']     = $this->wedding_booking_model->get( TBL_PAY_TYPE );
            $data['fn_types']   = $this->wedding_booking_model->get( TBL_SERVICE, array( 'menu_name' => $menu_id ), array('order_by' => 'name') );
        
        endif;
        
        //echo "<pre>Data: "; print_r( $data ); die;
        
        if( !empty( $post['submit'] ) ):// && $post['token'] == $token ) :
            // insert
            $insert_id = $this->wedding_booking_model->manipulate();

            $msg = 'Wedding Hall is booked successfully.';
            if( $page != 'add' ) :
                $msg = 'Booking is updated successfully.';
            endif;
            $this->session->set_flashdata('success', $msg);


            // Redirect
            redirect( $this->controller . '/index/' . $menu_id );
            redirect( $data['form_action'] );
        endif;

        // Load Views
        $this->render( $data, 'billing/wedding-booking/'.$page_file_name );
    }
    
    function delete( $id, $menu_id ) {
        $hidden_del_reason = $this->input->post('hidden_del_reason');
        $this->wedding_booking_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->wedding_booking_model->ajax();
		//echo "<pre>"; print_r($results); exit;
		ob_clean();
        echo json_encode($results);	
    }
    
    public function print_list($id,$menu_id) {
        $wedding_hall 	= $this->wedding_booking_model->get_by_id($id);
	    $paymentDetails = $this->wedding_booking_model->get_payment_date($id);
		$add_details 	= $this->wedding_booking_model->get_additional_amt_details($id);
        $addData		= array();
		if($add_details){
			foreach($add_details as $details){
				array_push($addData, array("desc" => $details->bwh_remarks, "amuont" => $details->bwh_additional_amount));
			}
		}
        
        /*
         * Print
         */
        $service_menu = $this->login_details_model->get_service_menu_by_id(18);
        $gst_details = $this->login_details_model->get_amount_by_service_id($wedding_hall->service_id);
        $prefix = get_general_setting()->prefix;
        
        $args = array(
            'type'      => '3', // 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 : '') . $wedding_hall->bwh_rec_no,
            'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
            'amount'    => array($wedding_hall->bwh_amount, $wedding_hall->bwh_paid_amount, $wedding_hall->bwh_paid_amount),
            'gst'       => $gst_details->gst,
            'status'    => $wedding_hall->status,
            'copy'      => TRUE,
            'printType' => TRUE,
	    	'payment_date' => date('d/m/Y h:i A',strtotime($paymentDetails[0]['created_on'])),
            
            'data'      => array( 
                
                
                // Type = 1 && 3 && 4
                'name'      => array($wedding_hall->bwh_contact_name, $wedding_hall->bwh_groom_name, $wedding_hall->bwh_bride_name),
                'contact_no'=> $wedding_hall->bwh_contact_no,
                'email'     => $wedding_hall->bwh_email,
                
                // Type = 1 && 3
                'address'   => $wedding_hall->bwh_address,
                'desc'      => $wedding_hall->bwh_desc,
                'addData'	=> $addData,
                
                // Type = 3 
                'date'      => date('d/m/Y',strtotime($wedding_hall->bwh_from_date)),
                'time'      => date('H:i',strtotime($wedding_hall->bwh_from_date)) . ( !empty( $wedding_hall->bwh_to_date ) ? ' - '.date('H:i',strtotime($wedding_hall->bwh_to_date)) : '' ),
                'proof'     => array(!empty( $wedding_hall->bwh_groom_proof ) ? $wedding_hall->bwh_groom_proof : '0', !empty( $wedding_hall->bwh_bride_proof ) ? $wedding_hall->bwh_bride_proof : '0', !empty( $wedding_hall->bwh_invitation_proof ) ? $wedding_hall->bwh_invitation_proof : '0'),
                'period'    => $wedding_hall->bwh_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_wedding_booking/index/' . $menu_id, 'refresh');
    }

    
    public function print_additionalamount($id) {
		$add_details 		= $this->wedding_booking_model->get_by_self_id($id);
		$wedding_hall 		= $this->wedding_booking_model->get_by_self_id($add_details->self_id);		
		
	   if($wedding_hall->wedding_confirm_date != '0000-00-00'){
			$fn_date = $wedding_hall->wedding_confirm_date;
	   }else{
		 	$fn_date = $wedding_hall->bwh_from_date;
	   }
	   
	   if($wedding_hall->wedding_confirm_date != '0000-00-00'){
			$fn_from_time = $wedding_hall->wedding_confirm_from_time;
	   }else{
		 	$fn_from_time = $wedding_hall->bwh_from_date;
	   }
	   
	   if($wedding_hall->wedding_confirm_date != '0000-00-00'){
			$fn_to_time = $wedding_hall->wedding_confirm_to_time;
	   }else{
		 	$fn_to_time = $wedding_hall->bwh_from_date;
	   }

        /*
         * Print
         */
        $service_menu 	= $this->login_details_model->get_service_menu_by_id(18);
        $gst_details 	= $this->login_details_model->get_amount_by_service_id($wedding_hall->service_id);
        $prefix 		= get_general_setting()->prefix;
//$gst_details->amount
		$rand 			= rand(2222, 9999);
        $args 			= array(
            'type' 			=> '3', // 3 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 : '') . $add_details->bwh_rec_no,
            'title' 		=> $gst_details->name,
            'amount' 		=> array($wedding_hall->bwh_amount, $wedding_hall->bwh_paid_amount, $wedding_hall->bwh_paid_amount),
            'gst' 			=> $gst_details->gst,
            'status' 		=> $wedding_hall->status,
			'add_amount' 	=> $add_details->bwh_additional_amount,
			'add_desc' 		=> $add_details->bwh_remarks,
            'copy'			=> FALSE,
            'created_on'	=> $add_details->created_on,
            'data' 			=> array(
                // Type = 1 && 3 && 4
                'name' 			=> array($wedding_hall->bwh_contact_name, $wedding_hall->bwh_groom_name, $wedding_hall->bwh_bride_name),
                'contact_no' 	=> $wedding_hall->bwh_contact_no,
                'email' 		=> $wedding_hall->bwh_email,
                // Type = 1 && 3
                'address' 		=> $wedding_hall->bwh_address,
                'desc' 			=> $wedding_hall->bwh_desc,
                // Type = 3
                'date' 			=> date('d/m/Y', strtotime($fn_date)),
                'time' 			=> date('H:i', strtotime($fn_from_time)) . (!empty($fn_to_time) ? ' - ' . date('H:i', strtotime($fn_to_time)) : '' ),
                'proof' 		=> array(!empty($wedding_hall->bwh_groom_proof) ? $wedding_hall->bwh_groom_proof : '0', !empty($wedding_hall->bwh_bride_proof) ? $wedding_hall->bwh_bride_proof : '0', !empty($wedding_hall->bwh_invitation_proof) ? $wedding_hall->bwh_invitation_proof : '0'),
                'period' 		=> $wedding_hall->bwh_period == '1' ? 'Morning / காலை' : 'Evening  / மாலை',
            ),
        );

        if (print_rec($args))
            $this->session->set_flashdata('success', 'Additional amount receipt has been printed successfully');
        else
            $this->session->set_flashdata('error', 'Additional amoun has not been printed!');

        /*         * * End ** */

        redirect('billing_wedding_booking/view/' . $add_details->self_id, 'refresh');
    }
	
	function wedding_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, "WEDDING BOOKING\n\rTOTAL : $".$_POST['amount']); //write string to serial
		}
	}
    
} // class   