<?php

/* 
 * Author       : Jai K
 * Purpose      : The controller for Billing - Prasadam
 * Created On   : 2016-08-12 12:10
 */

class Billing_Prasadam extends REF_Controller {
    public $controller;
    
    function __construct() {
        parent::__construct();
        
        $segments = $this->uri->segments;
        $this->controller = $segments[1];
        
        
        $this->load->model('billing/prasadam_model');
        $this->load->model('login_details_model','',TRUE);
        $this->load->library('Datatables');
    }
    
    function index( $id='' ) {
        
        check_permission();
        $actions = $this->actions();
        
        $data = array(
            'title'          => 'Prasadam',
            '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_prasadam/print_list/';
        
        $data['results'] = $this->prasadam_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/prasadam/new_index' );
    }
       function datatable() {
        $user_data = get_user_data();
        $this->datatables->select('@i:=@i+1 AS iterator, so.id AS soId,so.bp_rec_no as rec_no,so.bp_dev_name_1 as pname,if(so.bp_period=1,"Morning","Evening") as pperiod,so.bp_contact_no as contact_no,serv.name AS ptype, so.bp_amount as pamount, DATE_FORMAT(so.created_on,"%d/%m/%Y") AS pdate', FALSE)
                ->where('so.bp_book_status = 1')
                ->join(TBL_SERVICE . ' AS serv', 'serv.id = so.service_id', 'left')
                ->join(TBL_STAR . ' AS star1', 'star1.id = so.star_id_1', 'left')
                ->join(TBL_STAR . ' AS star2', 'star2.id = so.star_id_2', 'left')
                ->add_column('Actions', $this->get_buttons('$1', '$2'), 'soId', 'file_status')
                ->from(TBL_BP.' AS so,(SELECT @i:=0) AS foo');
        echo $this->datatables->generate();
    }
    function get_buttons($id, $file_status) {
//        echo $file_status;
        $actions = $this->actions();

        $html = '<span class="actions">';
         $html .='<a class="label btn btn-warning view" href="' .base_url() . 'billing_prasadam/print_list/' . $id . '" style="background-color: #00a65a; border-color: #00a65a;"><span>Print</span></a>&nbsp';
        if (in_array(1, $this->permission)) {
            $html .='<a class="label btn btn-warning view" href="' . $actions['view'] . '/' . $id . '/15"><span>View</span></a>&nbsp';
        }
        if (in_array(3, $this->permission)) {
            $html .='<a class="label btn btn-primary edit" href="' . $actions['edit'] . '/' . $id . '/15"><span>Edit</span></a>&nbsp';
        }
        if (in_array(4, $this->permission)) {
            $html .='<a class="label btn btn-danger pop_up_confirm delete delete_otp" href="#" data-confirm="Do you want to delete the Billing Prasadam" data-href="' . $actions['delete'] . '/' . $id . '/15" data-otp-ids="'.form_prep(serialize($service_menu_id)).'"><span>Delete</span></a>';
        }

       
        //$html .=' <a style="line-height: 15px; margin-right: 2px; margin-top: 5px; display: inline-block;" class="label btn btn-success do_copy" data-attr="' . $id . '" href="#" title="Scan Copy"><span><i class="fa fa-upload" aria-hidden="true"></i>&nbsp;Scan</span></a>&nbsp';
        $html.='</span>';
        return $html;
    }
    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'             => 'Prasadam',
            '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->prasadam_model->get_all_booked_details( $id );						
            $data['items'] = $this->prasadam_model->get_items( $id );
            $data['payments'] = $this->prasadam_model->get_payments( $id );
			
        endif;
        
        $service_id = $page == 'add' ? $id : $data['results'][0]['service_id'];
        if( $page != 'add' ) :
            $service = $this->prasadam_model->get( TBL_SERVICE, array( 'id' => $service_id ) );			
            $data['service'] = $service[0];
            $menu_id = $service[0]['menu_name'];
            $data['refund_detail'] = $this->login_details_model->get_refund_details_by_ids('15',$service_id,$id);
			
        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'] );
            
			if($data['items'][0]['god_id']){
				$god_id = array('id' => $data['items'][0]['god_id']);
			}else{
				$god_id = '';
			}
			
            $data['gods']       		= $this->prasadam_model->get( TBL_GOD_NAME, $god_id, array('order_by' => 'name') );
            $data['stars']      		= $this->prasadam_model->get( TBL_STAR, '', array('order_by' => 'name') );
            $data['ptypes']     		= $this->prasadam_model->get( TBL_PAY_TYPE );
            $data['prasadams']  		= $this->prasadam_model->get( TBL_PRASADAM, '', array('order_by' => 'name') );
            $data['payment_detail']   	= $this->prasadam_model->payment_mode_lists();
            
			//if(empty($id)){
            //	$data['fn_types']   = $this->prasadam_model->get( TBL_SERVICE, array( 'menu_name' => //$menu_id ) );
			//}
			
			
			
 $data['fn_types']   = $this->prasadam_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->prasadam_model->manipulate();

            if( $page == 'add' ) :
                if( $is_book ) :
                    $msg = $service_menu->service_name . ' is booked successfully.';
                else :
                    $msg = 'Billing for ' . $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 = 'Billing for ' . $service_menu->service_name . ' is updated successfully.';
                endif;
                
            endif;
            $this->session->set_flashdata('success', $msg);

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

        // Load Views
        $this->render( $data, 'billing/prasadam/'.$page_file_name );
    }
    
    function delete( $id, $menu_id ) {
        $hidden_del_reason = $this->input->post('hidden_del_reason');
        $this->prasadam_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->prasadam_model->ajax();
        
        echo json_encode( $results );
    }
    
    public function print_list($id,$menu_id) {
        $prasadam = $this->prasadam_model->get_by_id($id);
        $prasadam_details = $this->prasadam_model->get_items_id($id);
        
        /*** To Print Receipt - Start ***/
        $gst_details = $this->prasadam_model->get_amount_by_service_id($prasadam->service_id);
        $prefix = get_general_setting()->prefix;
        
        $gods = $prasadams= $print_body = $print_head = array();
       
        if($prasadam->is_deity == 1) : // is Deity
              foreach( $prasadam_details as $k => $details ) :
               $args = array();
                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[$details['god_id']][] = array(
                    ((!empty($gods[$details['god_id']]['name'])) ? $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>' : ''),
                    $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['bpi_qty'] . ' x ' . $details['bpi_price'] .'</div>',
                    '<div style="text-align: right;">'.number_format( $details['bpi_qty']*$details['bpi_price'], 2 ).'</div>',
                );
                
                $print_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>');
                    
               
            endforeach;
        else :  // No Deity
            $args = array();
            foreach( $prasadam_details 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['single'][$k] = array(
                    $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['bpi_qty'] . ' x ' . $details['bpi_price'] .'</div>',
                    '<div style="text-align: right;">'.number_format( $details['bpi_qty']*$details['bpi_price'], 2 ).'</div>',
                );
                
                $print_head = array('Prasadam Name<div class="sub-lbl">பிரசாதம்<div>','Qty x Unit Price($)<div class="sub-lbl">எண்ணிக்கை x ஒன்றின் விலை<div>', 'Amount($)<div class="sub-lbl">தொகை<div>');
            endforeach;
        endif;
        
		           /* $q  = $this->db->get_where( TBL_STAR, array('id' => $prasadam['star_1']) );
                    $str1 = $q->row_array();
					print_r(str1);
die(); */
//echo $prasadam->star_id_1;
//print_r($prasadam);
                     $str1 = $this->prasadam_model->get_star($prasadam->star_id_1);
					 //print_r($str1);
					// echo $this->db->last_query();
					// $star1 = $str1->name.' / '.$str1->tamil_name;
					 $star1 = $str1->tamil_name;


					
                    $this->db->where('id',$prasadam->star_id_2);
                    $str2 = $this->db->get(TBL_STAR)->row();
					//$star2 = $str2->name.' / '.$str2->tamil_name;
					$star2 = $str2->tamil_name;
					// print_r($star2);
					// die();
		
		
		
        
        if(count($print_body) > 0) :
           
            foreach ($print_body as $z => $body) :
              

			  $args = array(
                    'type'      => '10', // 6 Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
                    'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $prasadam->bp_rec_no,
                    'title'     => 'Prasadam - ' . $gst_details->name,
                    'amount'    => array($prasadam->bp_amount),
                    'gst'       => $gst_details->gst,
                    'status'    => $prasadam->status,
                    'copy'      => FALSE,
                    'created_on' => $prasadam->created_on,
					'ref_type'   => '15',
                    
                    'data'      => array( 
                        
                        // Type = 6
                        'fields'  => array(
                            'Name<div class="sub-lbl">பெயர்<div>'          => $prasadam->bp_dev_name_1 . ((!empty($prasadam->bp_tamil_name_1)) ? '  / <span class="linear-lbl lang-tamil">'. $prasadam->bp_tamil_name_1 .'</span>' : ''). ' ' . $star1, // . tamil( $prasadam->bp_tamil_name_1, 'border: none; font-weight: bold; font-size: 24px;' ),
                            /* 'Tamil Name<div class="sub-lbl">தமிழ் பெயர்<div>'    => tamil( $prasadam->bp_tamil_name_1, 'border: none; font-weight: bold; font-size: 24px;' ), */
							''          => $prasadam->bp_dev_name_2 . ((!empty($prasadam->bp_tamil_name_2)) ? '  / <span class="linear-lbl lang-tamil">'. $prasadam->bp_tamil_name_2 .'</span>' : ''). ' - ' . $star2,
                            'Date<div class="sub-lbl">தேதி<div>' => date('d/m/Y',strtotime(str_replace('-', '/', $prasadam->bp_fn_date ))),
                            'Period<div class="sub-lbl">காலம்<div>'        => $prasadam->bp_period == '1' ? 'Morning / காலை' : 'Evening / மாலை',
                            'Contact No<div class="sub-lbl">தொடர்பு எண்<div>'    => $prasadam->bp_contact_no,
                            'Email ID<div class="sub-lbl">மின்னஞ்சல்<div>'      => $prasadam->bp_email,
                        ),
                        
                        'tables' => array(
                            'head'  => $print_head,
                            'body'  => $body,
                        ),
                        
                    ),
                    
                );
                $return = print_rec_A4($args,($z+1));
            endforeach;
        endif;
        
        if($return)
            $this->session->set_flashdata('success', 'Receipt has been printed successfully');
        
        else 
            $this->session->set_flashdata('error', 'Receipt has not been printed!');
            
        /*** End ***/
        
        redirect( 'billing_prasadam/index/' . $menu_id, 'refresh');
        
    }
    
    public function get_prasadam_price() {
        $data = $this->prasadam_model->get_prasadam_price($_POST['id']);
        echo json_encode($data);
    }
    
    public function get_basic_details() {
        $data['prasadam'] = $this->prasadam_model->get_basic_details($_POST['contact_no']);
        echo json_encode($data);
    }
    
} // class    

