<?php
	##ERROR HANDLING
    ini_set('display_errors',1);
	error_reporting(E_ALL & ~E_NOTICE);
    include_once('base.inc.php');
    
    ## CONSTANTS DEFINITIONS
    define('BASE_DIR', dirname( dirname(__FILE__) ));
    define('LANGUAGES_DIR', BASE_DIR.'/lang');
    define('ALL_ROWS', 0);
    define('FIRST_ROW_ONLY', 1);
    define('DATA_ONLY', 0);
    define('ROWS_ONLY', 1);
    define('DATA_AND_ROWS', 2);
    define('FIELDS_ONLY', 3);
    define('FETCH_ASSOC', 'mysqli_fetch_assoc');
    define('FETCH_ARRAY', 'mysqli_fetch_array');
    
    $dbhost = DATABASE_HOST;
    $dbuser = DATABASE_USERNAME;
	$dbpass = DATABASE_PASSWORD;
	$dbname = DATABASE_NAME;
    
    ## TABLES DECLARATION
    define('TABLE_CORE_SETTINGS', 'core_settings');
    define('TABLE_CORE_SMS', 'core_sms');
    define('TABLE_CORE_CRITERIA', 'core_criteria');
    define('TABLE_ERROR_LOG', 'core_error_log');
    define('TABLE_USERS', 'users');
    define('TABLE_MODULES', 'cls_modules');
    define('TABLE_SMS_CAMPAIGN_DETAILS', 'sms_campaign_details');
    define('TABLE_SMS_AUTO_SETUP', 'sms_auto_setup');
    define('TABLE_SMS_CAMPAIGN_CRITERIA', 'sms_campaign_criteria');
    define('TABLE_SMS_OUTBOX', 'sms_outbox');
    
    require_once('classes/Database.inc.php');
    $mysqli = Database::GetConnection();
    
    function __autoload($class_name){
  		require_once('classes/'.$class_name.'.class.php');		
    }
    
    $error001 = '000 - DATABASE ERROR - PLEASE CALL THE ADMINISTRATOR!';
	
//~~~~~~global database functions
		function dbQuery($sql)
			{
				$mysqli = Database::GetConnection(); 
                $result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));		
				return $result;
			}
		function dbFetchAssoc($result)
			{
				return mysqli_fetch_assoc($result);
			}		
//~~~~~~function get global seetings
		function getGlobalSettings()
		{
			$sql = "SELECT * FROM core_settings WHERE id =1";
			$result = dbQuery($sql);
			$settings = array();
			while ($row = dbFetchAssoc($result)) {
				$settings[] = $row;
			}
			return $settings;
		}
//~~~~~~function sms global seetings
		function getSMSSettings()
		{
			$sql = "SELECT * FROM core_sms WHERE id =1";
			$result = dbQuery($sql);
			$sms_settings = array();
			while ($row = dbFetchAssoc($result)) {
				$sms_settings[] = $row;
			}
			return $sms_settings;
		}
//~~~~~~function get cls settings
		function getClsSettings()
		{
			$sql = "SELECT * FROM core_settings WHERE id =1";
			$result = dbQuery($sql);
			$cls_settings = array();
			while ($row = dbFetchAssoc($result)) {
				$cls_settings[] = $row;
			}
			return $cls_settings;
		}	
//~~~~~~function get cls modules
		function getClsModules($mod)
		{
			$sql = "SELECT * FROM cls_modules WHERE mod_name ='$mod'";
			$result = dbQuery($sql);
			$cls_modules = array();
			while ($row = dbFetchAssoc($result)) {
				$cls_modules[] = $row;
			}
			return $cls_modules;
		}			
//~~~~~~function get user seetings
		function getUserSettings($user)
		{
			$sql = "SELECT * FROM users WHERE username ='$user'";
			$result = dbQuery($sql);
			$user_settings = array();
			while ($row = dbFetchAssoc($result)) {
				$user_settings[] = $row;
			}
			return $user_settings;
		}		
//~~~~~~function get screen calibration seetings
		function getScreenSettings($screen_id)
		{
			$sql = "SELECT * FROM core_calibrations WHERE id ='$screen_id'";
			$result = dbQuery($sql);
			$screen_settings = array();
			while ($row = dbFetchAssoc($result)) {
				$screen_settings[] = $row;
			}
			return $screen_settings;
		}					
//~~~~~~~convert filesize to KB MB etc	
			function ByteSize($bytes) 
				{
				$size = $bytes / 1024;
				if($size < 1024)
					{
					$size = number_format($size, 2);
					$size .= ' KB';
					} 
				else 
					{
					if($size / 1024 < 1024) 
						{
						$size = number_format($size / 1024, 2);
						$size .= ' MB';
						} 
					else if ($size / 1024 / 1024 < 1024)  
						{
						$size = number_format($size / 1024 / 1024, 2);
						$size .= ' GB';
						} 
					}
				return $size;
				}
				
//~~~~~~~function to generate a new random password string
    			function generatePassword($length=9, $strength=0) {
    					$vowels = 'AEUYIO';
    					$consonants = 'WEBNAIL';
    					if ($strength & 1) {
    						$consonants .= 'BDGHJLMNPQRSTVWXZ';
    					}
    					if ($strength & 2) {
    						$consonants .= '0123456789';
    					}
    					$password = '';
    					$alt = time() % 2;
    					for ($i = 0; $i < $length; $i++) {
    						if ($alt == 1) {
    							$password .= $consonants[(rand() % strlen($consonants))];
    							$alt = 0;
    						} else {
    							$password .= $vowels[(rand() % strlen($vowels))];
    							$alt = 1;
    						}
    					}
    					return $password;
    				}
//~~~~~~~function to generate a new random string

					function rand_string( $length ) {
						$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	
					
						$size = strlen( $chars );
						for( $i = 0; $i < $length; $i++ ) {
							$str .= $chars[ rand( 0, $size - 1 ) ];
						}
					
						return $str;
					}		
//~~~~~~~function to get default user printer	
			
			function getDefaultPrinter() {				
			
            $mysqli = Database::GetConnection(); 
			$sql_def_print="SELECT * FROM core_printers WHERE id='$def_printer' LIMIT 1 ";				
			$def_print_result = mysqli_query($mysqli, $sql_def_print) or die("Query failed : " . mysqli_error($mysqli));
            
				if (mysqli_num_rows($def_print_result) == 0){
				if ($_SESSION['lang']=="EN"){include ('lang/en.php');}elseif ($_SESSION['lang']=="GR"){include ('lang/gr.php');}else{include ('lang/en.php');}
					echo "<u><a href='cls/modules/pos/user_printer.php' target='mainFrame'>"; 
					echo $lbl_grid_no_default_printer;
					echo "</a></u> ";
					echo "<img src='img/error.gif' border='0' width='13' />";			
				}elseif (mysqli_num_rows($def_print_result) > 0){
					$row = mysqli_fetch_array($def_print_result, MYSQLI_ASSOC);
					$printer_alias = $row['alias'];							
					echo "<u><a href='cls/modules/pos/user_printer.php'  target='mainFrame'>"; 
					echo $printer_alias;
					echo "</a></u>"; 
				}		
			return $printer_alias;		
			}			
//~~~~~~~function  get printer full
			
			function getPrinterFull($printer) {				
			
            $mysqli = Database::GetConnection();
			$sql_def_print="SELECT * FROM core_printers WHERE id='$printer' LIMIT 1 ";				
			$def_print_result = mysqli_query($mysqli, $sql_def_print) or die("Query failed : " . mysqli_error($mysqli));
				if (mysqli_num_rows($def_print_result) == 0){
					$printer_path= "No printer";
				}elseif (mysqli_num_rows($def_print_result) > 0){
					$row = mysqli_fetch_array($def_print_result, MYSQLI_ASSOC);
					$printer_path = $row['ip_address']."\\".$row['printer_name'];							
				}		
			return $printer_path;		
			}			
			
//~~~~~~~function  print test receipt
		function printTestReceipt($template, $credits, $total_credits, $transaction_id, $barcode_id, $mode) {	
		
		$mysqli = Database::GetConnection();
        $file_sql="SELECT * FROM core_printouts WHERE id='$template' LIMIT 1 ";				
		$file_result = mysqli_query($mysqli, $file_sql) or die("Query failed a : " . mysqli_error($mysqli));
			if (mysqli_num_rows($file_result) == 0){
			exit();
			}else{
				$row = mysqli_fetch_array($file_result, MYSQLI_ASSOC);
					$printout = $row['printout'];
						//header prefs
						$header_text=$row['header_text'];
						$header_font=$row['header_font'];
						$header_font_weight=$row['header_font_weight'];
						$header_font_height=$row['header_font_height'];
						$header_font_width=$row['header_font_width'];
						$header_line_height=$row['header_line_height'];
						$header_line_top=$row['header_line_top'];
						$header_orientation=$row['header_orientation'];
						//detail prefs
						$detail_text=$row['detail_text'];
						$detail_font=$row['detail_font'];
						$detail_font_weight=$row['detail_font_weight'];
						$detail_font_height=$row['detail_font_height'];
						$detail_font_width=$row['detail_font_width'];
						$detail_line_height=$row['detail_line_height'];
						$detail_line_top=$row['detail_line_top'];
						$detail_orientation=$row['detail_orientation'];
						//footer prefs
						$footer_text=$row['footer_text'];
						$footer_font=$row['footer_font'];
						$footer_font_weight=$row['footer_font_weight'];
						$footer_font_height=$row['footer_font_height'];
						$footer_font_width=$row['footer_font_width'];
						$footer_line_height=$row['footer_line_height'];	
						$footer_line_top=$row['footer_line_top'];	
						$footer_orientation=$row['footer_orientation'];
						//footer prefs				
						$barcode_type= $row['barcode_type'];
						$barcode_height= $row['barcode_height'];
						$barcode_width= $row['barcode_width'];
						$barcode_left= $row['barcode_left'];
						$bottom_margin=$row['bottom_margin'];
						$barcode_orientation=$row['barcode_orientation'];
						
					##### START PRINTER HANDLING
					error_reporting (E_ERROR); //hide warning message
					$printer=$_SESSION['default_printer'];
					
					$printer_path = getPrinterFull($printer);
					$handle = printer_open("\\\\".$printer_path); // LexmarkS500SeriesNet 
					//echo $printer_path;
				if ($handle){
				//echo "connected";
					printer_set_option($handle, PRINTER_MODE, "raw"); 
					
					//printer_set_option($handle, PRINTER_PAPER_FORMAT, PRINTER_FORMAT_CUSTOM);
					//printer_set_option($handle, PRINTER_PAPER_WIDTH, 80);
					//printer_set_option($handle, PRINTER_PAPER_LENGTH, 80);
					printer_abort($handle);
					printer_start_doc($handle, "Transaction_Receipt");
					printer_start_page($handle);
					//normalize font weight
					if ($header_font_weight=="PRINTER_FW_HEAVY"){$header_font_weight=PRINTER_FW_HEAVY;};
					if ($header_font_weight=="PRINTER_FW_MEDIUM"){$header_font_weight=PRINTER_FW_MEDIUM;};
					if ($header_font_weight=="PRINTER_FW_THIN"){$header_font_weight=PRINTER_FW_THIN;};
					if ($detail_font_weight=="PRINTER_FW_HEAVY"){$detail_font_weight=PRINTER_FW_HEAVY;};
					if ($detail_font_weight=="PRINTER_FW_MEDIUM"){$detail_font_weight=PRINTER_FW_MEDIUM;};
					if ($detail_font_weight=="PRINTER_FW_THIN"){$detail_font_weight=PRINTER_FW_THIN;};					
					if ($footer_font_weight=="PRINTER_FW_HEAVY"){$footer_font_weight=PRINTER_FW_HEAVY;};
					if ($footer_font_weight=="PRINTER_FW_MEDIUM"){$footer_font_weight=PRINTER_FW_MEDIUM;};
					if ($footer_font_weight=="PRINTER_FW_THIN"){$footer_font_weight=PRINTER_FW_THIN;};						
					
					$font_header = printer_create_font($header_font, $header_font_height, $header_font_width, $header_font_weight, false, false, false, $header_orientation);
					$font_detail = printer_create_font($detail_font, $detail_font_height, $detail_font_width, $detail_font_weight, false, false, false, $detail_orientation);
					$font_footer = printer_create_font($footer_font, $footer_font_height, $footer_font_width, $footer_font_weight, false, false, false, $footer_orientation);
					$font_barcode = printer_create_font("IDAutomationHC39M", $barcode_height, $barcode_width, PRINTER_FW_THIN, false, false, false, $barcode_orientation);
					//header
					printer_select_font($handle, $font_header);				
					$y_steph = $header_line_height;
					$strh = explode("\r\n", $header_text);
						for ($i=0;$i<count($strh);$i++) {	
						$header_line_top += $y_steph;						
						printer_draw_text($handle, iconv("UTF-8", "ISO-8859-7//TRANSLIT", $strh[$i]), 1, $header_line_top);						
						}				
					//printer_delete_font($font_header);
					//detail
					printer_select_font($handle, $font_detail); 
					$y_stepd = $detail_line_height;
					//replace variables
						if ($mode=='demo'){
							$credits=1075; //demo
							$total_credits=19700; 
							$transaction_id='7AFTFR389LQ6S05LLPQ0';
							$user=$_SESSION['user'];
							$barcode_id="10000008";
						}elseif($mode=='live'){ 
							$credits=$credits; //live
							$total_credits=$total_credits; 
							$transaction_id=$transaction_id;	
							$user=$_SESSION['user'];	
							$barcode_id=$barcode_id;			
						}
						$detail_text=str_replace("{DATE}",date('d/m/Y'),$detail_text); #date variable
						$detail_text=str_replace("{TIME}",date('H:i:s'),$detail_text); #date variable
						$detail_text=str_replace("{USER}",$user,$detail_text); #user variable
						$detail_text=str_replace("{CREDITS}",$credits,$detail_text); #credits variable
						$detail_text=str_replace("{TOTAL CREDITS}",$total_credits,$detail_text); #credits variable
						$detail_text=str_replace("{TRANSACTION ID}",$transaction_id,$detail_text); #transaction id variable	
								
					$strd = explode("\r\n", $detail_text);
						for ($i=0;$i<count($strd);$i++) {	
						$detail_line_top += $y_stepd;						
						printer_draw_text($handle, iconv("UTF-8", "CP1253//TRANSLIT", $strd[$i]), 1, $detail_line_top);						
						}				
					
					//auto
					//$autoline_height = $detail_line_height + 150;
					//printer_draw_text($handle, date('d/m/Y, H:i:s')." 500 ".$user, 1, $autoline_height);
					//footer
					printer_select_font($handle, $font_footer);
					$y_stepf = $footer_line_height;
					$strf = explode("\r\n", $footer_text);
						for ($i=0;$i<count($strf);$i++) {	
						$footer_line_top += $y_stepf;						
						printer_draw_text($handle, iconv("UTF-8", "ISO-8859-7//TRANSLIT", $strf[$i]), 1, $footer_line_top);						
						}		
					//printer_delete_font($font_footer);
					//barcode
					if ($barcode_type==''){//do nothing
						}elseif ($barcode_type=='transaction_id'){
							$barcode_text='*'.$transaction_id.'*';
							printer_select_font($handle, $font_barcode);
							$y_stepb = $footer_line_height;
							$strb = explode("\r\n", $barcode_text);
								for ($i=0;$i<count($strb);$i++) {	
								$footer_line_top += $y_stepb;						
								printer_draw_text($handle, iconv("UTF-8", "ISO-8859-7//TRANSLIT", $strb[$i]), $barcode_left, $footer_line_top);						
								}	
					//printer_delete_font($font_barcode);
						}elseif ($barcode_type=='barcode_id'){				
							$barcode_text=$barcode_id;
							printer_select_font($handle, $font_barcode);
							$y_stepb = $footer_line_height;
							$strb = explode("\r\n", $barcode_text);
								for ($i=0;$i<count($strb);$i++) {	
								$footer_line_top += $y_stepb;						
								printer_draw_text($handle, iconv("UTF-8", "ISO-8859-7//TRANSLIT", $strb[$i]), $barcode_left, $footer_line_top);						
								}	
					}
					$bottom=$footer_line_top + $bottom_margin;
					printer_select_font($handle, $font_footer); 
					printer_draw_text($handle, "-", 1, $bottom);
					
					printer_delete_font($font_header);
					printer_delete_font($font_detail);
					printer_delete_font($font_footer);
					printer_delete_font($font_barcode);
					
					printer_end_page($handle);
					printer_end_doc($handle);
					printer_close($handle);
  					
					if ($_SESSION['lang']=="EN"){include ('../../../lang/en.php');}elseif ($_SESSION['lang']=="GR"){include ('../../../lang/gr.php');}else{include ('../../../lang/en.php');}	
					//echo "<meta http-equiv=\"refresh\" content=\"0;URL=".$_SERVER['PHP_SELF']."\">";
					?>
					<script>
						document.getElementById('messagebox').setAttribute("class", "completed")
						document.getElementById('messagebox').style.visibility = 'visible';
						document.getElementById('messagetext').value = '<?php echo addslashes("$lbl_sent_to_printer \\\\").addslashes ($printer_path) ?>';
					</script>
					<?php
				}else{//if printer connected clause
					if ($_SESSION['lang']=="EN"){include ('../../../lang/en.php');}elseif ($_SESSION['lang']=="GR"){include ('../../../lang/gr.php');}else{include ('../../../lang/en.php');}	
					?>
					<script>
						document.getElementById('messagebox').setAttribute("class", "critical")
						document.getElementById('messagebox').style.visibility = 'visible';
						document.getElementById('messagetext').value = '<?php echo $lbl_printer_not_found ?>';
					</script>
					<?php
				//echo "<meta http-equiv=\"refresh\" content=\"0;URL=".$_SERVER['PHP_SELF']."\">";
				}
				}		
		}	

									
//~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~function  print test receipt
		function printTestPage($mode, $printer){
		
        $mysqli = Database::GetConnection();
		$file_sql="SELECT * FROM core_printers WHERE id='$printer' LIMIT 1 ";				
		$file_result = mysqli_query($mysqli, $file_sql) or die("Query failed : " . mysqli_error($mysqli));
			if (mysqli_num_rows($file_result) == 0){
				exit();
			}else{
				$row = mysqli_fetch_array($file_result, MYSQLI_ASSOC);
				$printer_path = $row['ip_address']."\\".$row['printer_name'];
				$handle = printer_open("\\\\".$printer_path); 
				if ($handle){
				//echo "connected";
					printer_set_option($handle, PRINTER_MODE, "raw"); 
					printer_start_doc($handle, "Test Page");
					printer_start_page($handle);
					$font = printer_create_font("Arial", "20", "8", PRINTER_FW_MEDIUM, false, false, false, 0);		
					printer_select_font($handle, $font);				
					printer_draw_text($handle, iconv("UTF-8", "CP1253//TRANSLIT", $mode), 1, 1);						
					printer_delete_font($font);
					printer_end_page($handle);
					printer_end_doc($handle);
					printer_close($handle);
  					
					if ($_SESSION['lang']=="EN"){include ('../../../lang/en.php');}elseif ($_SESSION['lang']=="GR"){include ('../../../lang/gr.php');}else{include ('../../../lang/en.php');}	
					//echo "<meta http-equiv=\"refresh\" content=\"0;URL=".$_SERVER['PHP_SELF']."\">";
					?>
					<script>
						document.getElementById('messagebox').setAttribute("class", "completed")
						document.getElementById('messagebox').style.visibility = 'visible';
						document.getElementById('messagetext').value = '<?php echo addslashes("$lbl_sent_to_printer \\\\").addslashes ($printer_path) ?>';
					</script>
					<?php
				}else{//if printer connected clause
					if ($_SESSION['lang']=="EN"){include ('../../../lang/en.php');}elseif ($_SESSION['lang']=="GR"){include ('../../../lang/gr.php');}else{include ('../../../lang/en.php');}	
					?>
					<script>
						document.getElementById('messagebox').setAttribute("class", "critical")
						document.getElementById('messagebox').style.visibility = 'visible';
						document.getElementById('messagetext').value = '<?php echo $lbl_printer_not_found ?>';
					</script>
					<?php
				//echo "<meta http-equiv=\"refresh\" content=\"0;URL=".$_SERVER['PHP_SELF']."\">";
				}
				}		
		}	
    ################################################################################ 
    
    function has_internet() { //added on 1.4.7 02/06/2014
            $connected = fsockopen("www.google.com", 80, $errno, $errstr, 5); 
            if ($connected){
                $is_conn = true;        //action when connected
                fclose($connected);
            }else{
                sleep(3);               //wait for 3 seconds
                $connected_ = fsockopen("www.google.com", 80); 
                if ($connected){
                    $is_conn = true;    //action when connected
                    fclose($connected);
                }else {
                    $is_conn = false;   //action in connection failure   
                }
            }
            return $is_conn;
        }
        
   //~~~~~~~function to query sms account balance
		function getSMSBalance() {
            $check_internet = has_internet();
            if ($check_internet == true ){
                $array_sms = getSMSSettings(); foreach ($array_sms as $sms_settings){extract($sms_settings);} 
                $balance_url = $url_balance
                . "api_id="  . UrlEncode($primary_http_api_id) 
                . "&user="  . UrlEncode($primary_acc_user) 
                . "&password=" . UrlEncode($primary_acc_pass) 
                ;
                //return $balance_url;
                $balance = '';
                if ( ($f = @fopen($balance_url, "r")))  {
                $max_zeichen = 100;
                $data = fgets($f, $max_zeichen);
                   while ($data) {
    	            $balance .= $data;
    	            $data = fgets($f, $max_zeichen);
                    //$balance = 0;
                    $credit_balance = round(substr($balance, 8),2);
                    return $credit_balance;
    	           }
                }else { 
                    $balance .= 'ERROR 253 '.$balance_url;   
                    return $balance;
                }
            }      
		} 
        
       function ValidPhonesRule($value){ ##added for SMS Module on 1.4.7 04/06/2014
        $array_sms = getSMSSettings(); foreach ($array_sms as $sms_settings){extract($sms_settings);} 
               
        if ($value == '1'){
           $mob_rule = " LENGTH(cust.phone) = ".$phones_rule_len." AND LEFT(cust.phone, 2) = ".$phones_rule_pre;
        }elseif ($value == '0'){
            $mob_rule = " (LENGTH(cust.phone) <> ".$phones_rule_len." OR LEFT(cust.phone, 2) <> ".$phones_rule_pre.")";
        }else {
            $mob_rule  = "ERROR";
        }  
       return $mob_rule;
       }       
       
       ## GET USER BRANCH DESCRIPTION
       function getBranchName($ses_branch){
            
            $mysqli = Database::GetConnection();
            $sql_16 = "SELECT branch_code, branch_name FROM cls_branches WHERE id='$ses_branch' LIMIT 1";				
            $result_16 = mysqli_query($mysqli, $sql_16) or die("Query failed : " . mysqli_error($mysqli));			
		
            if (mysqli_num_rows($result_16) > 0){
    			$row_16 = mysqli_fetch_array($result_16, MYSQLI_ASSOC);
    			$user_branch = $row_16['branch_code']." ".$row_16['branch_name'];							
            return $user_branch;
            }
       }
?>
