<?php
//session_start(); 
// if(!isset($_COOKIE['cboRecPP'])) {$GLOBALS['cboRecPP']=10;} else { $GLOBALS['cboRecPP']=$_COOKIE['cboRecPP'];}
// if(!isset($_COOKIE['PageNo']))   {$GLOBALS['PageNo']=1;} else { $GLOBALS['PageNo']=$_COOKIE['PageNo'];}
// if(!isset($_COOKIE['cboRecPP'])) {$GLOBALS['cboRecPP']=10;} else { $GLOBALS['cboRecPP']=$_COOKIE['cboRecPP'];}
 
$GLOBALS['az']="1234";
$GLOBALS['pgPP']=array(1,2,5,8,10,12,15,20,50,100,200,500,1000,5000);
$GLOBALS['TameioRecTypes']=array();
$GLOBALS['Months']=array('','Ιανουάριος', 'Φεβρουάριος','Μάρτιος','Μάϊος','Ιούνιος','Ιούλιος','Σεπτέμβριος','Οκτώβριος','Νοέμβριος','Δεκέμβριος');
$GLOBALS['Months_Gen']=array('','Ιανουαρίου', 'Φεβρουαρίου','Μάρτίου','Μάϊου','Ιουνίου','Ιουλίου','Σεπτεμβρίου','Οκτωβρίου','Νοεμβρίου','Δεκεμβρίου');
$GLOBALS['Months_3']=array('','ΙΑΝ','ΦΕΒ','ΜΑΡ','ΑΠΡ','ΜΑΙ','ΙΟΥΝ','ΙΟΥΛ','ΑΥΓ', 'ΣΕΠ','ΟΚΤ','ΝΟΕ','ΔΕΚ');
$GLOBALS['Week_Days']=array('ΚΥΡΙΑΚΗ','ΔΕΥΤΕΡΑ','ΤΡΙΤΗ','ΤΕΤΑΡΤΗ','ΠΕΜΠΤΗ','ΠΑΡΑΣΚΕΥΗ','ΣΑΒΒΑΤΟ','ΚΥΡΙΑΚΗ');
$GLOBALS['Week_Days3']=array('ΚΥΡ','ΔΕΥ','ΤΡΙ','ΤΕΤ','ΠΕΜ','ΠΑΡ','ΣΑΒ','ΚΥΡ');
 
//global $TameioRecTypes ;
//$GLOBALS['TameioCases']=array('Μετρητά','Ταμείο Έναρξης','Πιστωτική Κάρτα','Τραπεζική Κατάθεση', 'Είσπραξη Λογαριασμού');
//$GLOBALS['TameioReserve']=array('0','0','-1','Τραπεζική Κατάθεση', '0');

//$LoginError=0 ;
 
//$txtUserName = $_POST["txtUserName"];
//$txtUserPassword = $_POST["txtUserPassword"];
// =========================== 
// Connect to MySQL database /
// ===========================
global $conn;

if(!isset($_SESSION['DB_SERVER'])){
	header("Location: index.php");
}
$conn = mysqli_connect($_SESSION['DB_SERVER'], $_SESSION['inValues']['DB_PREFIX'].$_SESSION['inValues']['DB_USERNAME'], $_SESSION['DB_PASSWORD'], $_SESSION['inValues']['DB_PREFIX'].$_SESSION['inValues']['DB_NAME']) 
		or die('ΔΕΝ ΥΠΑΡΧΕΙ ΣΥΝΔΕΣΗ ΜΕ ΤΗΝ ΒΑΣΗ ΔΕΔΟΜΕΝΩΝ : ' . $_SESSION['DB_SERVER']);
mysqli_set_charset($conn, "utf8");
//$conn=$_SESSION['conn'];

//$_SESSION['conn']=$conn;

// $conn -> set_charset("gr.utf-8");

// mysqli_query("SET NAMES 'UTF8'");

 // ini_set('mbstring.substitute_character', "greek");
 
// TameioRecTypesMake($conn);



// ===============================
//    app_title
// ===============================
 function app_title() {
	 
# echo "<title>2222vs OfficeManager</title>";
# echo "<link rel='shortcut icon' href='logos/LT.png'  type='image/x-icon'>";
# echo "<link rel='icon' href='logos/LT.ico' type='image/x-icon' />";
echo '<link rel="icon" type="image/x-icon" href="logos/LT48.ico" sizes="48x48" />';
echo '<link rel="icon" type="image/x-icon" href="logos/LT32.ico" sizes="32x32" />';
echo '<link rel="icon" type="image/x-icon" href="logos/LT16.ico" sizes="16x16" />	'; 
 }	
 
function app_head(){

echo "<head>";
echo "<title>vs Contracts</title>";
echo '	<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '	<meta name="description" content="">';
echo '	<meta http-equiv="content-type" content="text/html; charset=UTF-8">';
echo '<link rel="shortcut icon"  href="icons/Asthenis_24x24.ico" />';
echo "</head>";
 
}	
// ===============================
//    Grid List Functions
// ===============================

function cboRecsPerPage($val1, $prefix){
 $pgPP = $GLOBALS['pgPP'];
 $max =  count($pgPP );
 $nm1= $prefix.'cboRecPP';
 $Style='font-size:12px;height:22px;margin-top:0px;margin-left:2px;padding-top:1px;';
 $Command='rppupd(this)';
 
 #echo '<select name="'.$nm1.' " id="'.$nm1.'" style="'.$Style.'" onChange="'.$Command.'">'; 
 echo "<select name='$nm1' id='$nm1' style='$Style' onChange='$Command' >"; 
 for ($iRow = 0; $iRow < $max; $iRow++)
    {   
		echo "<option value=$pgPP[$iRow] " ;
			 if($val1==$pgPP[$iRow]) { echo " SELECTED ";}	
		echo "> $pgPP[$iRow] </option>";
	}
  echo "</select>" ; 

}

function cboRecsPerPage__1111111($val1, $prefix){
 $pgPP = $GLOBALS['pgPP'];
 $max =  count($pgPP );
 $nm1= $prefix.'cboRecPP';
 $Style='font-size:0.90em;height:22px;margin-top:2px;margin-left:2px;';
 $Command='rppupd("'. $prefix . '")';
 
 #echo '<select name="'.$nm1.' " id="'.$nm1.'" style="'.$Style.'" onChange="'.$Command.'">'; 
 echo "<select name='$nm1' id='$nm1' style='$Style' onChange='$Command' >"; 
 for ($iRow = 0; $iRow < $max; $iRow++)
    {   
		echo "<option value=$pgPP[$iRow] " ;
			 if($val1==$pgPP[$iRow]) { echo " SELECTED ";}	
		echo "> $pgPP[$iRow] </option>";
	}
  echo "</select>" ; 
}

function cboTameioRecTypesMake($conn,$val1){
   
   $query="SELECT IDRecType, RecType, isReserve From tameio_rectypes Order By IDRecType"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;

echo "<select name='cboTameioRecTypes' id='cboTameioRecTypes' onchange=\"javascript:comboChange(this,'RecType','IDRecType');\">"; 

while ($rs = mysqli_fetch_array($result)) {
$RecType=$rs['RecType'];
$IDc=$rs['IDRecType'];
$isReserve=$rs['isReserve']; 
$myStyle="style='color:#595959;font-weight:bold;'";
if ($isReserve==-1){$myStyle="style='color:darkblue;font-weight:bold;'";}

if($IDc==$val1){$chk='Selected';}else{$chk='';}
      echo "<option ". $myStyle ." value='".$IDc."' ".$chk.">".$RecType."</option>";
 }
 	
  echo "</select>" ; 

}


function TameioRecTypesMake($conn){
 
 // $TameioRecTypes=array();
 $TameioRecTypes=$GLOBALS['TameioRecTypes'];
 
   $query="SELECT IDRecType, RecType, isReserve From tameio_rectypes Order By IDRecType"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;

	while ($rs = mysqli_fetch_array($result)) {
		$RecType=$rs['RecType'];
		$IDc=$rs['IDRecType'];
		$isReserve=$rs['isReserve']; 
    
	$a = array('IDRecType'=>$IDc,'RecType'=>$RecType,'isReserve'=>$isReserve ) ;						 
	 array_push($TameioRecTypes ,$a);						 
//echo " ============= ".	$IDc ." , ". $RecType . " , " . $isReserve . "<br>" ;

 	//array_push($TameioRecTypes[$IDc], $RecType, $isReserve);
	}
 $GLOBALS['TameioRecTypes']=$TameioRecTypes;
 
// echo "<br> =============  : " . count($TameioRecTypes);	
// echo "<br> =============  : " .	 array_search('1004', array_column($TameioRecTypes , 'IDRecType')) . "<br>";
// echo "<br> =============  : " . $TameioRecTypes[9]["RecType"];
}

function TameioRecTypesGet($IDRecType,$fldName){
   $TameioRecTypes=$GLOBALS['TameioRecTypes'];
	$no=array_search($IDRecType, array_column($TameioRecTypes , 'IDRecType'));
//	echo $IDRecType . " ---- " . $fldName;
 	return $TameioRecTypes[$no][$fldName];

}


function cboApothematikoRecTypesMake($conn,$val1){
   
   $query="SELECT IDRecType, RecType From tameio_apothematiko_rectypes Order By IDRecType"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;

echo "<select name='cboApothematikoRecTypes' id='cboApothematikoRecTypes' onchange=\"javascript:comboChange(this,'RecType','IDRecType');\">"; 

while ($rs = mysqli_fetch_array($result)) {
$RecType=$rs['RecType'];
$IDc=$rs['IDRecType'];
 
if($IDc==$val1){$chk='Selected';}else{$chk='';}
      echo "<option value='".$IDc."' ".$chk.">".$RecType."</option>";
 }
 	
  echo "</select>" ; 

}

function get_client_ip(): string
{
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    } else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    } else if (isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    } else {
        $ipaddress = 'UNKNOWN';
    }

    return $ipaddress;
}

function getUserLocation($ip = false): string
{
  if ($ip === false) $ip = $_SERVER['REMOTE_ADDR'] ?? false;
  if (!$ip) return 'ip_not_found';
  return unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $ip));
}


Function ButtonsNavigation($MyFrmName, $Page1, $Pages1, $prefix) {

// $out = iconv("UTF-8", 'Windows-1252//TRANSLIT//IGNORE', $out)
$styl1="style='padding:1px;'";
$f=$prefix.'btnFirst';
$p=$prefix."btnPrv";
$n=$prefix."btnNext";
$l=$prefix."btnLast";

	echo "<table  border='0' cellspacing='0' cellpadding='0' align='right' style='padding:5px'><tr>";
	
	# echo "<td><a href=\"javascript:gtRecPg('" . $MyFormName . ".php', " . "'first','$prefix')\"  class='btnFirst' alt=' Πρώτη σελίδα '></a> </td>";

	echo "<td $styl1><a onclick='javascript:gtRecPg(this)' class='btnFirst' name='$f' alt=' Πρώτη σελίδα '></a> </td>";
	echo "<td $styl1><a onclick='javascript:gtRecPg(this)' class='btnPrv' name='$p' alt=' Προηγούμενη σελίδα '></a></td>";
	echo "<td style='padding:0 2px 0 2px;'><input type='text' size='7' style='height: 1.6em;text-align:center;font-size:0.8em;' value=" . $Page1 . "/" . $Pages1 . " ></td>";
	echo "<td $styl1><a onclick='javascript:gtRecPg(this)' class='btnNext' name='$n' alt=' Επόμενη σελίδα '></a></td>";
	echo "<td $styl1><a onclick='javascript:gtRecPg(this)' class='btnLast' name='$l' alt=' Τελευταία σελίδα '></a></td>";
	
#	echo "<td $styl1><a href=\"javascript:gtRecPg('" . $MyFrmName . "', " . "'first','$prefix')\"  class='btnFirst' id='btnFirst' alt=' Πρώτη σελίδα '></a> </td>";
#	echo "<td $styl1><a href=\"javascript:gtRecPg('" . $MyFrmName . "', " . "'prv','$prefix')\" class='btnPrv' id='btnPrv' alt=' Προηγούμενη σελίδα '></a></td>";
#	echo "<td style='padding:0 2px 0 2px;'><input type='text' size='7' style='height: 1.6em;text-align:center;font-size:0.8em;' value=" . $Page1 . "/" . $Pages1 . " ></td>";
#	echo "<td $styl1><a href=\"javascript:gtRecPg('" . $MyFrmName . "', " . "'next','$prefix')\" class='btnNext' id='btnNext' alt=' Επόμενη σελίδα '></a></td>";
#	echo "<td $styl1><a href=\"javascript:gtRecPg('" . $MyFrmName . "', " . "'last','$prefix')\" class='btnLast' id='btnLast' alt=' Τελευταία σελίδα '></a></td>";


	echo "</tr></table>";	 

}

function HmGroupButtons($prefix, $period_type, $HmApo, $HmEos){

$day_checked="";$week_checked="";$month_checked="";$year_checked="";
$period_name="η Ημέρα";
 
 switch($period_type) {
	   case 'day':	$day_checked="checked";$period_name="η Ημέρα";break;
	   case 'week':	$week_checked="checked";$period_name="η Εβδομάδα";break;
	   case 'month':$month_checked="checked";$period_name="ος Μήνας";break;
	   case 'year':	$year_checked="checked";$period_name="ο Ετος";break;
 }	   
 
#echo "<div class='calendar_buttons_group ib '>";
#	echo "<input type='radio' name='$group_name' id='calendar_day' class='ib' $Cal_day_checked />";
#	echo "<label class='btnlabel' title=' Ημέρα ' for='calendar_day' class='ib' > </label>";
#	echo "<input type='radio' name='$group_name' id='calendar_week' class='ib' $Cal_week_checked />";
#	echo "<label class='btnlabel' title=' Ημέρα ' for='calendar_week' class='ib' > </label>";
#	echo "<input type='radio' name='$group_name' id='calendar_month' class='ib' $Cal_month_checked />";
#	echo "<label class='btnlabel' title=' Ημέρα ' for='calendar_month' class='ib' > </label>";
#	echo "<input type='radio' name='$group_name' id='calendar_year' class='ib' $Cal_year_checked />";
#	echo "<label class='btnlabel' title=' Ημέρα ' for='calendar_year' class='ib' > </label>";
#echo "</div>";	
 			
#echo "<div class='btn-vs-group' style='margin-left:10px; '>";
	 #echo "<a id='calendar_prv' href='#' class='ib button2' title=' Προηγούμεν$period_name '></a>";
#			HmApoEosButtonMake( $HmApo,  $HmEos);
	# echo "<a id='calendar_next' href='#' class='ib button2' title=' Επόμεν$period_name '></a>";
#	echo "<a id='calendar_select' href='#' class='ib button2' title=' Επιλογή Περιόδου '></a>";
#echo "</div>";
 

	#echo '<div id="vs_calendar_tool_bar" class="btn-vs-group" style="margin-left:5px;align:left;">';
	echo '<div id="vs_calendar_tool_bar" class="btn_group"  >';
#	echo '<a id="'.$prefix.'calendar_day" class="button2 calendar_day" title=" Ημέρα " ></a>';
#	echo '<a id="'.$prefix.'calendar_week" class="button2 calendar_week" title=" Εβδομάδα "></a>';
#	echo '<a id="'.$prefix.'calendar_month" class="button2 calendar_month" title=" Μήνας "></a>';
	echo '<a id="'.$prefix.'calendar_prv" class="button prv" title=" Προηγούμεν'.$period_name.' "></a>';
			HmApoEosButtonMake($prefix, $HmApo,  $HmEos);
	echo '<a id="'.$prefix.'calendar_next" class="button next" title=" Επόμεν'.$period_name.' "></a>';
#	echo '<a id="'.$prefix.'calendar_select" class="button2 calendar_select" title=" Επιλογή Περιόδου "></a>';
	echo '</div>';					
}


function HmApoEosButtonMake($prefix, $HmApo, $HmEos) {

if(!isset($simera)){$simera=date('d/m/YY');}
$val1=''; $len1=9;
  if ($HmApo==$simera) {
		$val1= 'Σήμερα' ;
	  }	
	elseif ($HmApo==$HmEos) { $val1=$HmApo ;}	
	else {
		$val1= $HmApo . " - " . $HmEos . " ";
	}
$len1= strlen($val1)-4;
//echo "<input type='text' id='HmSelect' class='button2' readOnly style='width:98%; align-self: stretch;' size='$len1' value='$val1' /> ";
echo "<a id='".$prefix."calendar_select' class='button text' >$val1</a> ";
  
//  echo "&nbsp;&nbsp; &#9662;";
//  echo "&nbsp; &#9144;&#9207;</a>";
// echo  "&nbsp;&nbsp;&#10151";
 

}


function RecordsCount($conn, $query) {
	global $conn;
	if($conn == false)
		{
		  # echo ' Δεν υπάρχει σύνδεση... ' . $_SESSION['DB_SERVER'] . ", " . $_SESSION['DB_USERNAME'] ; 
		  # $conn = mysqli_connect($_SESSION['DB_SERVER'], $_SESSION['DB_USERNAME'], $_SESSION['DB_PASSWORD'],  $_SESSION['DB_NAME']);
		  $conn = mysqli_connect($_SESSION['DB_SERVER'], $_SESSION['DB_USERNAME'], $_SESSION['DB_PASSWORD'],  $_SESSION['DB_NAME']) 
		           or die('Could not connect the database : Username or password incorrect');
		  
		  mysqli_set_charset($conn, "utf8");
		  $result = mysqli_query($conn, $query);
		  $num_rows1 = $result->num_rows;
		  return $num_rows1;		  
		}
		else
		 { 
			 $result = mysqli_query($conn, $query);
			 $num_rows1 = $result->num_rows;
			 return $num_rows1;
		 }
 }

function dbConnect() {
	//if( $conn == false)
	//	{
		 // echo ' Δεν υπάρχει σύνδεση... ';
		$conn = mysqli_connect($_SESSION['DB_SERVER'], $_SESSION['inValues']['DB_PREFIX'].$_SESSION['inValues']['DB_USERNAME'], $_SESSION['DB_PASSWORD'], $_SESSION['inValues']['DB_PREFIX'].$_SESSION['inValues']['DB_NAME']);
		mysqli_set_charset($conn, "utf8");
	//	}
 return $conn;
 }
 
 
 function myFieldType($Typos){
	$Typos='@'.$Typos;
	 if(strpos($Typos, 'int')>0) { return "Number"; }
	 if(strpos($Typos, 'double')>0) { return "Number"; }
	 elseif(strpos($Typos, 'date')>0) { return "Date"; } 
	 elseif(strpos($Typos, 'text')>0) { return "String";}
	 elseif(strpos($Typos, 'char')>0) { return "String";}
	 else{return "String";}
 }
# ============================
#        Filter Make
# ============================
function filter_make($flds_str, $find_what){
 
$gr="ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψωABGDEZHUIKLMNJOPRSTYFXCVabgdezhuiklmnjoprstyfxcv ";
$en="ABGDEZHUIKLMNJOPRSTYFXCVabgdezhuiklmnjoprstyfxcvΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψω ";
 
if(trim($find_what=="")){return "";}
if(trim($flds_str=="")){return "";}

$find_what2 = "";

for ($i = 0; $i < mb_strlen($find_what); $i++) {
		$letter= mb_substr($find_what,$i,1)  ;
		$j = mb_strpos($gr, $letter);
		if ($j==false) {$find_what2 = $find_what2 . mb_substr($find_what,$i,1);} 
			else {
				$find_what2 =$find_what2 . mb_substr($en, $j, 1);
			}
	  }
 
$flds=explode(",",$flds_str);
$finds=explode(" ",$find_what);
$finds2=explode(" ",$find_what2);
 
 $filter="";$filter2="";
 $i=0;
 foreach ($finds as $find_part) {
	 
	  if (trim($find_part," ")!=="") {	
		$txt="CONCAT ("; 
			foreach ($flds as $id) {
				$txt.="IFNULL(".$id.",''),' ', " ;				
				}	
	   }	
      $txt2 = substr($txt, 0, -2) . ") LIKE '%" . $finds2[$i] ."%' ";	
	   $txt = substr($txt, 0, -2) . ") LIKE '%" . $find_part ."%' ";	
	  
 $filter .= $txt . " AND \r\n";
 $filter2 .= $txt2 . " AND \r\n";
  $i=$i+1;
 }
 
 
 if (strlen($filter)>=6) {
	$filter="WHERE " . substr($filter, 0, -6) . " or (" .  substr($filter2, 0, -6) .")" ;
 }else{
	$filter=""; 
 }

return $filter;

## $date = "04/30/1973";
## list($month, $day, $year) = split('[/.-]', $date);
## echo "Month: $month; Day: $day; Year: $year<br />\n";

}
 
function UserTypeComboBoxMake($conn, $field_name, $val1){

    $query="SELECT IDUserType,Code, UserType FROM user_types ORDER BY Code"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;
	
//echo "<select name='UserType' id='UserType' onchange=\"javascript:comboChange(this,'RecType','IDUserType');\">";
echo "<select name='UserType' id='UserType'  required >";  
echo "<option value=''>&nbsp;</option>";

while ($rs = mysqli_fetch_array($result)) {
	$iRow +=1;
	$UserType=$rs['UserType'];

	if($UserType==$val1){$chk='Selected';}else{$chk='';}
			echo "<option value='".$UserType."' ".$chk.">".$UserType."</option>";
}
 
	echo "</select>" ; 


}


 function EponymiaComboBoxMake($conn,$val1){
    $query="SELECT IDPelati,Eponymia From pelates Order By Eponymia"; 
   $result=mysqli_query($conn, $query);

 while ($rs = mysqli_fetch_array($result)) {
$Eponymia=$rs['Eponymia'];
$IDc=$rs['IDPelati'];

if($Eponymia==$val1){$chk='Selected';}else{$chk='';}
      echo "<option value='".$IDc."' ".$chk.">".$Eponymia."</option>";
 }
    echo "<option value='0'>&nbsp;</option>";
	echo "<option value='0'>&nbsp;</option>";
}
 
 
 
function AppsComboBoxMake($conn,$val1){
    $query="SELECT IDApp, perigrafi From apps Order By perigrafi"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;
 echo "<option value=''>&nbsp;</option>";
 while ($rs = mysqli_fetch_array($result)) {
$iRow +=1;
$perigrafi=$rs['perigrafi'];
$IDc=$rs['IDApp'];
if($perigrafi==$val1){$chk='Selected';}else{$chk='';}
     echo "<option value='".$IDc."' ".$chk.">".$perigrafi."</option>";
 }
     
#	 echo "<option value=''>&nbsp;</option>";
}

function TameiakesModelsComboBoxMake($conn,$val1){
    $query="SELECT ID_Tam_Model, Tameiaki_Model From tameiakes_models Order By Tameiaki_Model"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;
 echo "<option value=''>&nbsp;</option>";
 while ($rs = mysqli_fetch_array($result)) {
$iRow +=1;
$Tameiaki_Model=$rs['Tameiaki_Model'];
$IDc=$rs['ID_Tam_Model'];
if($Tameiaki_Model==$val1){$chk='Selected';}else{$chk='';}
     echo "<option value='".$IDc."' ".$chk.">".$Tameiaki_Model."</option>";
 }   
	# echo "<option value=''>&nbsp;</option>";
}

function POSModelsComboBoxMake($conn,$val1){
    $query="SELECT ID_POS_Model, POS_Model From pos_models Order By POS_Model"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;
 echo "<option value=''>&nbsp;</option>";
 while ($rs = mysqli_fetch_array($result)) {
$iRow +=1;
$Tameiaki_Model=$rs['POS_Model'];
$IDc=$rs['ID_POS_Model'];
if($Tameiaki_Model==$val1){$chk='Selected';}else{$chk='';}
     echo "<option value='".$IDc."' ".$chk.">".$Tameiaki_Model."</option>";
 }   
	# echo "<option value=''>&nbsp;</option>";
}

function poliComboBoxMake($conn, $field_name, $val1){

    $query="SELECT Poli FROM pelates GROUP BY Poli ORDER BY Poli"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;

echo "<input list='Poleis' id='$field_name' name='$field_name'  onClick='this.select();' value='$val1'></input>";
echo "<datalist id='Poleis'>";

 while ($rs = mysqli_fetch_array($result)) {
$iRow +=1;
$Poli=$rs['Poli'];
if($Poli==$val1){$chk='Selected';}else{$chk='';}
     echo "<option value='$Poli' $chk/>";
 }
     echo "</datalist>";
}

function CountryComboBoxMake($conn, $field_name, $val1){

    $query="SELECT * FROM countries ORDER BY Country"; 
   $result=mysqli_query($conn, $query);
    $iRow=0;

echo "<input list='cboCountry' id='$field_name' name='$field_name' class='my_select' onClick='this.select();' value='$val1'></input>";
echo "<datalist id='cboCountry'>";
 
 while ($rs = mysqli_fetch_array($result)) {
	$iRow +=1;
	$Code=$rs['CountryCode'];
	$Country=$rs['Country'];
	if($Country==$val1){$chk='Selected';}else{$chk='';}
     echo "<option value='$Country' $chk/>";
 }
  echo "</datalist>";
}

Function gConvertCheck($my_value) {
  
  $return_value="unchecked";
  
     If (is_null($my_value)) {
          $return_value="unchecked"; 
     }    
     elseIf (strpos("|YES|1|-1|TRUE|ΝΑΙ|Αληθές|ΑΛΗΘΕΣ", "|".strtoupper($my_value)."|") != 0) {
          $return_value = "checked";
		}
	 
 return $return_value;
} 


 
function input_field_2080($pos1,$pos2, $caption, $field, $val, $required){

if($required==true){$required='required';}else{$required='';}

 echo "<div class='col-$pos1'><label for='$field'>$caption</label></div>"."\n";
 echo "<div class='col-$pos2'><input type='text' id='$field' name='$field' $required value='$val'></div>"."\n";
		
}

function input_field_2030_x2($caption1, $field1, $val1, $required1, $caption2, $field2, $val2, $required2 ){

if($required1==true){$required1='required';}else{$required1='';}
if($required2==true){$required2='required';}else{$required2='';}

 echo "<div class='row'>"."\n";
 echo "<div class='col-20'><label for='$field1'>$caption1</label></div>"."\n";
 echo "<div class='col-30'>"."\n";	
 echo "<input type='text' id='$field1' name='$field1' $required1 value='$val1'>"."\n";
 echo "</div>"."\n";
 echo "<div class='col-20'><label for='$field2'>$caption2</label></div>"."\n";
 echo "<div class='col-30'>"."\n";	
 echo "<input type='text' id='$field2' name='$field2' $required2 value='$val2'>"."\n";
 echo "</div>"."\n";
 
 echo "</div>"."\n";
		
}
function input_2xfield($caption1,$w11,$field1,$w12,$val1,$required1, $caption2,$w21,$field2,$w22,$val2,$required2){

if($required1==true){$required1='required';}else{$required1='';}
if($required2==true){$required2='required';}else{$required2='';}

 echo "<div class='row'>"."\n";
 echo "<div class='col-$w11'><label for='$field1'>$caption1</label></div>"."\n";
 echo "<div class='col-$w12'>"."\n";	
 echo "<input type='text' id='$field1' name='$field1' $required1 value='$val1'>"."\n";
 echo "</div>"."\n";
 echo "<div class='col-$w21'><label for='$field2'>$caption2</label></div>"."\n";
 echo "<div class='col-$w22'>"."\n";	
 echo "<input type='text' id='$field2' name='$field2' $required2 value='$val2'>"."\n";
 echo "</div>"."\n";
 
 echo "</div>"."\n";
		
}

function inputyesnoButton($fld_name, $value1) {
# style='background-color:#E8E0CA;' 
 echo "<label class='switch-container' >";    
 echo "<input type='checkbox' id='" . $fld_name . "' name='" . $fld_name . "' " . $value1 . "  class='switch-input' onclick='dt4Update();' />" ;
 echo "<div class='switch' align='middle' >" ;
 echo "<span class='switch-label'>ΝΑΙ</span>" ;
 echo "<span class='switch-label'>ΟΧΙ</span>" ;
 echo "<span class='switch-handle'></span>" ;
 echo "</div>" ;
 echo "</label>" ;
}
 

function ComboBoxMake($conn, $tblName, $field_name, $val1, $Button=""){

    $query="SELECT * FROM " . $tblName . " ORDER BY " . $field_name; 
   $result=mysqli_query($conn, $query);
    $iRow=0;
if ($Button=="") {$style1="";}else{$style1="style='width:calc(100% - 25px);margin-right:3px;'";}
echo "<input list='cbo$field_name' id='$field_name' name='$field_name' $style1 onClick='this.select();' value='$val1'></input>";
echo "<datalist id='cbo$field_name'>";
 
 while ($rs = mysqli_fetch_array($result)) {
	$iRow +=1;
	$fldValue=$rs[$field_name];
	if($fldValue==$val1){$chk='Selected';}else{$chk='';}
     echo "<option value='$fldValue' $chk/>";
 }
  echo "</datalist>";
 if ($Button!==""){
   echo "<a href='$tblName"."List.php' style='width:20px;text-align:center;padding:0px 0px 0px 0px;border-radius:3px;' class='button' >...</a>";
 }	 
}

function gConvertField($curval,$to) {
	$newVal=$curval;
	if(is_null($curval)){$newVal=$to;}
	elseif(empty($curval)){$newVal=$to;}
	elseif($curval==''){$newVal=$to;}
	else{}	
 
 return $newVal;

}
 
 
function formatMyDate($mydate , $fromTo='GrToMySql', $def_value='' ) {
	
	if($def_value!==''){ $valForExit=$def_value; } else {$valForExit=null;}
	if(is_null($mydate) || empty($mydate)==true ) {return $valForExit; }
 
    if(preg_match("/(\d{2}):(\d{2}):(\d{2})/", $mydate, $match)) {
        if (strpos($mydate,$match[0])==0) {
			return $match[0];
		};
	};
	
	// if(empty($mydate)==true){ return null; exit(); }
	//if(isdate($mydate)==false ){
	//	     return null;
	//		 exit();
	//}
 
	if($fromTo=="GrToMySql"){
		$d_array = explode('/', $mydate);
		if(!is_numeric($d_array[2]) ){return null; }
		$mydate = $d_array[2]."-".$d_array[1]."-".$d_array[0];
		
		return $mydate;
	}	
	
	if($fromTo=="MySqlToGr"){
		$d_array = explode('-', $mydate);
		$hmera=substr($d_array[2],0,2);
		$minas= $d_array[1] ;
		$etos= $d_array[0] ;
		if(is_numeric($hmera)==false || is_numeric($minas)==false || is_numeric($etos)==false ){
			return null;}
		$mydate = $hmera."/".$minas ."/".$etos ;
		return $mydate;
	}

	if($fromTo=="GrTo_YYYYMMDD"){
		$d_array = explode('/', $mydate);
		if(!is_numeric($d_array[2]) ){return null; }
		$mydate = $d_array[2]."".$d_array[1]."".$d_array[0];
		
		return $mydate;
	}	
	
	if($fromTo=="MySqlTo_YYYYMMDD"){
		$d_array = explode('-', $mydate);
		$hmera=substr($d_array[2],0,2);
		$minas= $d_array[1] ;
		$etos= $d_array[0] ;
		if(is_numeric($hmera)==false || is_numeric($minas)==false || is_numeric($etos)==false ){
			return null;}
		$mydate = $etos."".$minas ."".$hmera ;
		return $mydate;
	}
	
}



function isDate($value) {
	
    if (!$value) {
        return false;
    }

    try {
        new DateTime($value);
        return true;
    } catch (Exception $e) {
        return false;
    }
}

function date_olografos($mDate){
 
$datetime1 = new DateTime();
$myDate   = $datetime1->createFromFormat('d/m/Y', $mDate);

$day_no   = intval(date_format($myDate,'d'));
$day_w    = date_format($myDate,'w');
$month_no = intval(date_format($myDate,'m'));
$year_no  = intval(date_format($myDate, 'Y'));

$month_word=$GLOBALS['Months_3'][$month_no];
$day_word  = $GLOBALS['Week_Days'][$day_w];

$date = $day_word . ', ' . $day_no . '-' .$month_word . '-' . $year_no ;

return $date;

}


function RandomString()
    {
       // $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring .= $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }


function ExcelExport($data){
	
	function cleanData(&$str)
	  {
		if($str == 't') $str = 'TRUE';
		if($str == 'f') $str = 'FALSE';
		if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
		  $str = "'$str";
		}
		if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
	  }

	  	 $timestamp = time();
         $filename = 'Export_excel_' . $timestamp . '.xls';
        
        printf ("Content-Type: application/vnd.ms-excel"); 
        printf ("Content-Disposition: attachment; filename=\"$filename\""); 
		
  // filename for download
#  $filename = "website_data_" . date('Ymd') . ".csv";

#  header("Content-Type: text/csv");
 # header("Content-Disposition: attachment; filename=\"$filename\"");
  

  $out = fopen("php://output", 'w');
  


  $flag = true;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      fputcsv($out, array_keys($row), ',', '"');
      $flag = true;
    }
    array_walk($row, __NAMESPACE__ . '\cleanData');
    fputcsv($out, array_values($row), ',', '"');
  }

  fclose($out);
 
echo "<br>" . $filename . "<br>";
// exit;
//echo "<br>" . $filename . "2<br>";  
}

function ExcelExport2(){
	
 //namespace vaggelis;

  // Original PHP code by Chirp Internet: www.chirp.com.au
  // Please acknowledge use of this code by including this header.

  $data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
    array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
    array("firstname" => "James", "lastname" => "Brown", "age" => 31),
    array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
    array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
    array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
    array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
  );

  function cleanData(&$str)
  {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  // file name for download
  $filename = "website_data_" . date('Ymd') . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

  $flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\n";
      $flag = true;
    }
    array_walk($row, __NAMESPACE__ . '\cleanData');
    echo implode("\t", array_values($row)) . "\n";
  }
 

}


function IsWindows()
{
	$phpOS = strtolower(PHP_OS);
	if( substr_count( $phpOS, 'win' ) == 0 )
		return false;
	else
		return true;
}

//-----------------------------------------------------
// Mail utility function
//-----------------------------------------------------
	
	function SendMailReplyTo( $to, $from, $reply_to, $subj, $body )
	{
		$headers = "From: $from\r\n";
		$headers .= "Reply-To: $reply_to\r\n";
		return mail($to, $subj, $body, $headers);
	}

	function SendMail( $to, $from, $subj, $body )
	{
		return SendMailReplyTo( $to, $from, $from, $subj, $body );
	}

 

 

function user_ip_address(){

$ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

function safe_time_get($string)
{
    if(preg_match("/(\d{2}):(\d{2}):(\d{2})/", $string, $match)) {
        	return 	$match[0];
	};

 //   echo ">>>>>>>>>>>>> ". PHP_OS . " -- " .	$match[0] ."<br>";

	if(!preg_match("/\d{4}/", $string, $match)) return null; //year must be in YYYY form
    
//	echo "*/*/*/*/*/*/*/*/   " .  $match[0] . " - " . $match[1] . "<br>";
	
	$year = intval($match[0]);//converting the year to integer
    
	
	if($year >= 1970) return strtotime($string);//the year is after 1970 - no problems even for Windows
   
   if(stristr(PHP_OS, "WIN") && !stristr(PHP_OS, "DARWIN")) //OS seems to be Windows, not Unix nor Mac
    {
        $diff = 1975 - $year;//calculating the difference between 1975 and the year
        $new_year = $year + $diff;//year + diff = new_year will be for sure > 1970
        $new_date = date("Y-m-d", strtotime(str_replace($year, $new_year, $string)));//replacing the year with the new_year, try strtotime, rendering the date
        return str_replace($new_year, $year, $new_date);//returning the date with the correct year
    }
	
    return date("Y-m-d", strtotime($string));//do normal strtotime
}


# ====================================================

function isMobile() { 
$isMob = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "mobile")); 
  
// Check if the "tablet" word exists in User-Agent 
$isTab = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "tablet")); 
 
// Platform check  
$isWin = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "windows")); 
$isAndroid = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "android")); 
$isIPhone = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "iphone")); 
$isIPad = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "ipad")); 
$isIOS = $isIPhone || $isIPad; 
 
if($isMob){ 
    if($isTab){ 
      #  echo 'Using Tablet Device...'; 
		return "Tablet";
    }else{ 
       #  echo 'Using Mobile Device...'; 
		 return "Mobile";
    } 
}else{ 
  // echo 'Using Desktop...'; 
      return "Desktop";
} 


if($isIOS){ 
  //  echo 'iOS'; 
	return "iOS";
}elseif($isAndroid){ 
  //  echo 'ANDROID'; 
	 return "ANDROID";
}elseif($isWin){ 
    //echo 'WINDOWS'; 
	return "WINDOWS";
}

 
}

function isMobile1() {
   return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

	
//echo "<br>============================";

function screen_resolution() {
if (isset($_COOKIE["screen_resolution"])) {
    $currentValue = $_COOKIE["screen_resolution"];//example: 1920x1080
    $parts = explode("x", $currentValue);
    if(count($parts) == 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
        $width = (int)$parts[0];
        $height = (int)$parts[1];
    } else {
        // handle error
    }
 }
}

function input_yesno_only($label, $fldName, $sqlField, $val, $type){
 
# style='background-color:#E8E0CA;  
$isChk='unchecked'; 
if($val==-1){$isChk='checked';} 
if($type==""){$m_style="style='margin:10px 0px 0px 0px;'";}else{$m_style="";}

if($type=="button"){	echo "<a class='$type' style='padding-right:0px;'>$label ";}
	echo "<label class='t2' >" ;
	echo "<input type='checkbox' id='$fldName'' name='$fldName' $isChk onclick='javascript:chkUpd(\"$sqlField\");' /> ";
	echo "<span class='value' $m_style></span>";
	echo "</label>"; 
if($type=="button"){echo "</a>";}
			  
#echo "<div style='min-width:180px;padding-right:5px;'>"."\r\n";
 
}

function input_yesno($label, $fldName, $sqlField, $val){
 
# style='background-color:#E8E0CA;  
$isChk='unchecked'; 
if($val==-1){$isChk='checked';} 

echo "<a class='button' style='padding-right:4px;'>$label" ."\n";
	echo "<label class='t2' >"."\n";
		echo "<input type='checkbox' id='$fldName' name='$fldName' $isChk onclick='javascript:chkUpd(\"$sqlField\");' />"."\n";
		echo "<span class='value'></span>"."\n";
	echo "</label>"."\n";
echo "</a>"	."\n";
				
#echo "<div style='min-width:180px;padding-right:5px;'>"."\r\n";
#echo "<div style='float:right; text-align:right; display:table-cell; vertical-align:middle;'>"."\r\n";
#echo "<label class='switch-container' >" ."\r\n";   
#echo "<input type='checkbox' id='$fldName' name='$fldName' $isChk class='switch-input' onclick='javascript:chkUpd(\"$sqlField\");' />" ."\r\n"; 
#echo "<div class='switch' align='middle' >" ."\r\n" ;
#echo "<span class='switch-label'>ΝΑΙ</span><span class='switch-label'>ΟΧΙ</span>" ."\r\n" ;
#echo "<span class='switch-handle'></span>" ."\r\n" ;
#echo "</div>" ."\r\n" ;
#echo "</label>" ."\r\n" ;
#echo "</div>"."\r\n" ;
#echo "<div style='float:right;display:table-cell; text-align:left: font-size:0.7em; vertical-align:middle;padding:8px 5px;'>$label</div>"."\r\n"; 
#echo "</div>"."\r\n" ;
}

function input_yesno2($label, $fldName, $sqlField, $val,$h){
 
# style='background-color:#E8E0CA;  
$isChk='unchecked'; 
if($val==-1){$isChk='checked';} 
if($h!=0) { $h1="height:".$h."px;";} 
echo "<div style='min-width:180px;padding-right:5px;display:inline-block;float:right;$h1'>"."\r\n";
echo "<a class='button' style='padding-right:4px;$h1'>Εμφάνιση εκκρεμών μόνο "."\r\n";
echo "<label class='t2' style='display:inline-block;float:right;$h1' >"."\r\n";
echo "<input type='checkbox' id='$fldName' name='$fldName' $isChk onclick='javascript:chkUpd(\"$sqlField\");' />"."\r\n";
echo "<span class='value'></span>"."\r\n";
echo "</label>"."\r\n";
echo "</a>"."\r\n";
echo "</div>"."\r\n" ;				

}
 
 
 
function service_fields(){
 $myarray=array(
	     "IDService" => array("IDService","IDService", "number","right"),
		 "Πελάτης" => array("Eponymia","Πελάτης", "text","left"),
		 "HmniaParalavis" => array("HmniaParalavis","Ημερ.Παραλαβής", "date","center"),
		 "OraParalavis" => array("OraParalavis","Ωρα", "date","center"),
		 "HmniaEpiskevis" => array("HmniaEpiskevis","Ημερ.Επισκευής", "date","center"),
		 "OraEpiskevis" => array("OraEpiskevis","Ωρα", "date","center"),		 
	);
	
	return $myarray;	

	
	
}

function service_query(){

	   $sql="SELECT service.*, pelates.Eponymia,pelates.Kinito,pelates.Til,pelates.Poli,pelates.Dnsi,pelates.TK, pelates.email ";
$sql = $sql."FROM service LEFT JOIN pelates ON service.IDPelati = pelates.IDPelati ";

return $sql;
}

function tameio_query($IDc){
 
$sql=" SELECT tameio.*, 
pelates.Eponymia as Pelatis_Eponymia, pelates.Eponymo, pelates.Onoma, pelates.Dnsi,pelates.Poli,pelates.Til,pelates.Kinito,pelates.email,
promitheytes.Eponymia as Prom_Eponymia,promitheytes.Dnsi,promitheytes.Poli,promitheytes.Til1,promitheytes.Til2,promitheytes.AFM,promitheytes.eMail1
FROM tameio
LEFT JOIN pelates ON tameio.IDPelati = pelates.IDPelati
LEFT JOIN promitheytes ON tameio.IDProm = promitheytes.IDProm 
 where tameio.IDTameiou=" . $IDc ;
  
return $sql;
}


function weekdays($m_date,$No){

# if No=1 ----> Δευτέρα
# if No=7 ----> Κυριακή

$the_date=date("Y-m-d",$m_date);
$the_day_of_week =  date("w",strtotime($the_date)); //sunday is 0 
$first_day_of_week = date("Y-m-d",strtotime( $the_date )-60*60*24*($the_day_of_week)+60*60*24*1 );
 $last_day_of_week = date("Y-m-d",strtotime($first_day_of_week)+60*60*24*($No-1) );

$first_day_of_week=date("d-m-Y", strtotime($first_day_of_week));
$last_day_of_week=date("d-m-Y", strtotime($last_day_of_week));

if ($No==1){return $first_day_of_week;}
 else{return $last_day_of_week;} 
# echo " ================ " . $the_date . "     :    " . $first_day_of_week . "  ~  " . $last_day_of_week . "<br>";

 
}	
?>

 
 

