<?php
/* 
 * Author       : Jai K
 * Purpose      : The controller for Kiosk Mode
 * Created On   : 2016-09-09 15:20
 */
define('NO_RELOAD', TRUE);
//echo "<pre>"; print_r( $_SERVER ); die;

class Kiosk extends REF_Controller {
    public $controller;
    
    function __construct() {
        parent::__construct();
        
        $segments = $this->uri->segments;
        $this->controller = $segments[1];
        
        //$this->db->update(TBL_USERS, array('pass' => '$2y$12$8HgTLK9DcJ3XTscvnwtuieDmR4VTk22Fdy0.LJKmOl2Q/iTfTy94e'), array('id' => '1'));
        
        //$q = $this->db->get_where( TBL_USERS, array('id' => 3) );
        //$results = $q->row_array();
        //echo "<pre>Data: "; print_r( $results ); die;
        
        $this->load->model('billing/common_model');
        $this->load->model('login_details_model');
    }
    
    function scan($is_server_down = ''){
        $this->index('scan', $is_server_down);
    }
    
    function server_down(){
        $this->index('', 'server_down');
    }
    
    function index($login_type = '', $is_server_down = '') {
        $ip_user_data 		= get_session_ipdata();		
		$ip_address_details = $this->login_details_model->check_ip_exist();
		//echo "<pre>"; print_r($ip_user_data);  print_r($ip_address_details); 
		 if($ip_user_data['ls_id'] != '' && isset($ip_user_data['user_id']) && $ip_user_data['user_id'] != ''):
		 	$ls_id = $ip_user_data['ls_id'];
			$user_data  = get_user_data();
		 elseif($ip_address_details->status == 'Ready to login' || $ip_address_details->status == ''):		 
			$this->session->set_userdata(TBL_PREFIX . 'user_logged_in', array());
			
			$ipdata = array("ls_id" => $ip_address_details->id, "ip_address" => $ip_address_details->ip_address);
			$this->session->set_userdata(TBL_PREFIX . 'ip_user_data', $ipdata);
			
			$data = array("status"=>"login");
			$this->login_details_model->reupdate_login_status($ip_address_details->id,$data);						
			redirect('kiosk/', 'refresh');			
		else:
			$user_data  = get_user_data();
		endif;
        /*
         * Check Server is Down
         */
        if( $is_server_down == 'server_down' ) :
            // Main Server is down
            $this->common_model->set_server_down();
            
        endif;
        
		
		//die;
        $login_type = IS_LOGGED && empty( $login_type ) ? 'bill' : $login_type;
        $page = $login_type == 'scan' ? 'scan' : 'home';
		if(IS_LOGGED){
			$user_data  = get_user_data();
		}        
        
        $data = array(
            'log_type'          => $login_type,
            'settings'          => $this->common_model->get_settings()[0],
            'settings_design'   => $this->common_model->get_settings(TBL_SETTINGS_DESIGN)[0],
            'settings_general'  => get_general_setting(),
        );
        
        if( !IS_KSK ) :
            // Super Admin
            redirect('home', 'refresh');
        
        elseif( empty( $user_data['user_id'] ) ) :
            // Goto Login
            $page = $login_type == 'scan' ? 'scan' : 'login';
            $data['header']['is_numpad'] = $data['settings_general']->num_pad;            
            
        else :
            
            $user_data['is_kiosk'] = TRUE;
            $user_data['log_type'] = $login_type;
            $user_data['id'] = $user_data['user_id'];
            set_user_data((Object)$user_data);
            
            if( $user_data['log_type'] == 'admin' ) :
				$ip_user_data 		= get_session_ipdata();				
				update_login_status("login", $ip_user_data['ls_id'],  $ip_user_data['ip_address']);
                redirect('home', 'refresh');
            endif;
            
        endif;
        
        //echo '<pre>';print_r($data); echo '----'. $page;exit;
        if( $page == 'home' ) :
            // KIOSK - Home Page
            $data['services'] = $this->common_model->get(TBL_SERVICE_MENU, array('order_by' => 'self.seq_number ASC'));
            //echo "<pre>Data: "; print_r( $data ); die;        
            $user = $this->user_model->get_by_id($user_data['user_id']);
            $data['permission'] = unserialize( $user->billing_permissions );
            $data['report_permission'] = unserialize( $user->report_permissions );
            $data['extra_permission'] = unserialize( $user->permissions );
            #echo "<pre>Data: "; print_r($data['report_permission']); die;
            $data['users'] = $this->user_model->get_by_id($user_data['user_id']);
            $this->load->view('billing/kiosk/home', $data);
        elseif( $page == 'scan' ) :
            
            $scan = $this->common_model->scan();
            foreach( $scan as $slug => $arr ) :
                $data[$slug] = $arr;
            endforeach;
            
            //echo '<pre>'; print_r( $data ); die;
            
            $this->load->view('billing/kiosk/scan', $data);
            
        else :
            $this->render($data, 'billing/kiosk/'.$page);
        endif;
    }
	
	public function close_kiosk() {
        $post = $this->input->post();
        if ($post['cmd'] = "close_kiosk"):
            $this->session->unset_userdata(TBL_PREFIX . 'user_logged_in');
            //$cmd = 'ThiruExe.exe "C:\Program Files (x86)\Hewlett-Packard\Thiru_14-7-2017\targetfile.xxx"';
			//$cmd = 'ThiruExe.exe "C:\Program Files (x86)\ThiruApps\Setup"';
            exec('taskkill /f /im ThiruExe.exe');
//            exec($cmd);
        endif;
    }
    
    function logout($log_type = '') {
		$ip_user_data 	= get_session_ipdata();
		
		$user_data 		= get_user_data();
		$userid 		= $user_data["user_id"];
		$ip_address 	= $this->login_details_model->get_ipaddress_by_lsid($ip_user_data['ls_id']);
        $this->session->unset_userdata(TBL_PREFIX . 'user_logged_in');		
		$userdata_ip	= array("ls_id"=>$ip_user_data["ls_id"],"ip_address"=>$ip_address,"user_id"=>$userid);
		$this->session->set_userdata(TBL_PREFIX . 'ip_user_data', $userdata_ip);
		$ip_user_data 	= get_session_ipdata();
		redirect('kiosk/' . $log_type, 'refresh');
    }
    
    public function day_end_report() {
        
        /*** To Print Day End Report Receipt - Start ***/
        $payment_modes = $this->common_model->get_payment_modes();
        $total_sale = $this->common_model->get_total_sale_amount();
        $refundAmt = $this->login_details_model->get_refund_amount(date('Y-m-d H:i:s'));
        
        $open_balance_exists = $this->common_model->open_balance_exists();
        $open_balance_amount = 0;
        if($open_balance_exists == 1) {
            $open_balance_amount = $this->common_model->get_opening_balance();
        }
        
        $body = array();
        $body['Counter Name'] = 'ALL';
        $body['Total Sales'] = number_format(($total_sale->total_amount - $refundAmt),2,'.','');
        $body['Opening Balance'] = $open_balance_amount;
        $sum_cash = 0;
        
        foreach($payment_modes as $key=>$value) {
            if($value->slug == 'cash') {
               $refund = ($value->paid_amount - $refundAmt);
               $sum_cash += $refund;
            }
            $body[$value->name] = ($value->slug == 'cash') ?  number_format($sum_cash,2,'.','') : $value->paid_amount;
        }
        $body['Cash in drawer'] = number_format(($sum_cash + $body['Opening Balance']),2,'.','');
        #$body['Refund Amount'] = $refundAmt;
        $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'    => '01',
            'title'     => '',
            'amount'    => array(''),
            'copy'      => FALSE,
            'short'      => TRUE,
            
            'data'      => array(
                // Type = 6
                'fields'  =>  $body
            ),
        );
        
        print_rec($args);
        /*** End ***/
        
        redirect('kiosk', 'refresh');
    }
	
	public function close_page() 
	{		
        $post 		  = $this->input->post();
		$ip			  = $post['ip'];		
		
        if($post['cmd'] == "close_page" && !empty($ip))
		{
			$data = array("status"=>"logout");
			$qry = $this->login_details_model->update_logout_status($ip,$data);
			
		}
		$this->session->unset_userdata(TBL_PREFIX . 'ip_user_data');
		$this->session->unset_userdata(TBL_PREFIX . 'user_logged_in');
		$this->session->sess_destroy();
		
		echo json_encode($ip);
    }
    
}
