<?php

$id=uniqid();
global $sessionId;

$test = array_key_exists("test",$_GET) ? rawurlencode($_GET['test']) : null;
$teacher = rawurlencode(strtoupper ($_GET['teacher']));

function postPayload($data,$sessionId)
{
	
$url = 'https://bulme.webuntis.com/WebUntis/jsonrpc.do';

// Create a new cURL resource
$ch = curl_init($url);
	

// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

curl_setopt($ch, CURLOPT_COOKIE,' JSESSIONID=' . $sessionId);
// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the POST request
$result = curl_exec($ch);

// Close cURL resource
curl_close($ch);
return $result;
	
}

function login($id,$username,$password,$sessionId) {
	$data='{"id":"'.$id.'","method":"authenticate","params":{"user":"'.$username.'","password":"'.$password.'", "client":"webphp"},"jsonrpc":"2.0"}';
	return  postPayload($data,$sessionId);
}

function logout($id,$sessionId) {
	$data='{"id":"'.$id.'","method":"logout","params":{},"jsonrpc":"2.0"}';
	return  postPayload($data,$sessionId);
}


function getSubstitutions($id,$sessionId,$startdate,$enddate){
	$data='{"id":"'.$id.'","method":"getSubstitutions","params":{"startDate":'.$startdate.',"endDate":'.$enddate.',"departmentId":0},"jsonrpc":"2.0"}';
	return  postPayload($data,$sessionId);
}

function getTeachers($id,$sessionID) {
	$data='{"id":"'.$id.'","method":"getTeachers","params":{},"jsonrpc":"2.0"}';
	return  postPayload($data,$sessionID);
}

function getRooms($id,$sessionID) { 
	$data='{"id":"'.$id.'","method":"getRooms","params":{},"jsonrpc":"2.0"}';
	return  postPayload($data,$sessionID);
}



function getDepartments($id,$sessionID) {
	$data='{"id":"'.$id.'","method":"getDepartments","params":{},"jsonrpc":"2.0"}';
	return  postPayload($data,$sessionID);
}

$endtime=0;
$con=json_decode(login($id,'shr','jkl9fds3',$sessionId));


$sessionId=$con->result->sessionId;

$subTeachers=json_decode(getTeachers($id,$sessionId));


foreach($subTeachers->result as $sub)
{
	if (isset($sub->name)  && $sub->name==$teacher)
	{
      $teacherName=$sub->foreName.' '.$sub->longName;
	}
}


// echo date_format(date_add(new DateTime(), date_interval_create_from_date_string("1 days")),'Ymd');
//if (isset($test)) print_r(date_format(date_add(new DateTime(), date_interval_create_from_date_string("2 days")),'Ymd'));
$result =json_decode(getSubstitutions($id,$sessionId,date_format(new DateTime(),'Ymd'),date_format(date_add(new DateTime(), date_interval_create_from_date_string("2 days")),'Ymd')));
//$result =json_decode(getSubstitutions($id,$sessionId,'20221220','20221223'));


//print_r(json_decode(getTeachers($id,$sessionId)));

//print_r(json_decode(getRooms($id,$sessionId)));

//print_r(json_decode(getDepartments($id,$sessionId)));

$resultLogout= logout($id,$sessionId);

$subTeachers='';

$my=new mysqli("127.0.0.1","epaper",'NT_$U51cZr8jwA',"gwp_actual");

if ($my->connect_error) {
  die("Connection failed: " . $my->connect_error);
  echo "Connected failed";
}
// echo "Connected successfully";

$i=0;
$jsonArray=array();
$subTeachers='';
//if (isset($test)) 
{

foreach($result->result as $sub)
{
	if (isset($sub->te[0])  && $sub->te[0]->name==$teacher)
	{
		if (isset($sub->te[0]->orgname)) 
			{
			//if (isset($test)) print_r($sub);
			$subDate=$sub->date;
			$subStartTime=substr($sub->startTime,0,2).':'.substr($sub->startTime,2,2);
			$subEndTime=substr($sub->endTime,0,2).':'.substr($sub->endTime,2,2);
			$subRoom=$sub->ro[0]->name;
			
//TIME_FORMAT(addtime( timediff ( DATE(gtd.day), DATE(now())) , subtime(hs.end,'0:02:0.0') ),'%H:%i') as refreshtime,	
$subTeachers.=($subTeachers=='' ? '' : ' UNION ' )." SELECT gt.numbering,gtt.order,t.kz as subkz,t.name_long as subteacher, '$teacher' as kz, '".$teacherName."' as teacher,r.name as subroom,'$subRoom' as room
,gh.name as class,TIME_FORMAT('$subStartTime','%H:%i') as start,TIME_FORMAT('$subEndTime','%H:%i')  as end,
TIME_FORMAT(subtime(hs.end,'0:02:0.0') ,'%H:%i') as refreshtime,
TIMESTAMPDIFF(SECOND, now(),timestamp(DATE( gtd.day ),hss.start)) as refresh_seconds, 1 as supplierung
,t_o.name as unittype,gtd.group as 'group',DATE_FORMAT(DATE(gtd.day),'%d.%m.%Y') as day, '' as subject_short,'Supplierung' as subject 
FROM `gwp_timetable_teachers`  as gtt left join teachers as t on gtt.teacherid=t.id
 left join gwp_timetable gt on gtt.timetableid=gt.id
left join rooms r on gtt.room=r.id
left join gwp_head gh on gt.headid=gh.id 
left join gwp_timetable_days gtd on gtd.timetableid=gtt.timetableid 
left JOIN sessions se on gh.`session`=se.id 
LEFT JOIN session_days sed ON se.id=sed.session_id AND sed.day=gtd.`day`  
left join teaching_objects t_o on t_o.id=gt.object
left join competence c on c.id=gtt.object
left join hourschool hs on hs.hour=gt.lesson_end
left join hourschool hss on hss.hour=gt.lesson_start
where  NOW() BETWEEN se.`start` AND se.`end` and  t.kz = '".$sub->te[0]->orgname."'

and sed.day='$subDate' and TIME_FORMAT(date_sub(hs.start, interval -5 Minute),'%H:%i') between  TIME_FORMAT('$subStartTime','%H:%i') and TIME_FORMAT('$subEndTime','%H:%i')
and gh.name not like '$%'

";

		}
	}
}

//--TIME_FORMAT(addtime( timediff ( DATE(gtd.day), DATE(now())) , subtime(hs.end,'0:02:0.0') ),'%H:%i') as refreshtime,

$subTeachers.=($subTeachers=='' ? '' : ' UNION ALL ' )." SELECT gt.numbering,gtt.order,'' as subkz, '' as subteacher,t.kz,t.name_long as teacher,'' as subroom,r.name as room
,gh.name as class,TIME_FORMAT(hss.start,'%H:%i') as start,TIME_FORMAT(hs.end,'%H:%i') as end,

TIME_FORMAT(subtime(hs.end,'0:02:0.0') ,'%H:%i') as refreshtime,
TIMESTAMPDIFF(SECOND, now(),timestamp(DATE( gtd.day ),hss.start)) as refresh_seconds
,0 as supplierung 
,t_o.name as unittype,gtd.group as 'group',DATE_FORMAT(DATE(gtd.day),'%d.%m.%Y') as day, c.name_short as subject_short,c.name_long as subject 
FROM `gwp_timetable_teachers`  as gtt left join teachers as t on gtt.teacherid=t.id
 left join gwp_timetable gt on gtt.timetableid=gt.id
left join rooms r on gtt.room=r.id
left join gwp_head gh on gt.headid=gh.id 
left join gwp_timetable_days gtd on gtd.timetableid=gtt.timetableid 
left JOIN sessions se on gh.`session`=se.id 
LEFT JOIN session_days sed ON se.id=sed.session_id AND sed.day=gtd.`day` 
left join teaching_objects t_o on t_o.id=gt.object
left join competence c on c.id=gtt.object
left join hourschool hs on hs.hour=gt.lesson_end
left join hourschool hss on hss.hour=gt.lesson_start
where NOW() BETWEEN se.`start` AND se.`end` and  t.kz = '$teacher'

and (timestamp(DATE( sed.day ),hs.end)>=addtime(now(),'0:15:0.0')) 
and gh.name not like '$%'

".' order by refresh_seconds limit 0,5'; 
//and (timestamp(DATE( sed.day ),hs.end)<=date_add(now(),Interval 10 day)) 

//if (isset($test)) echo $subTeachers; , start,end


			if (isset($test) && $test=='sub') {

	print_r($subTeachers);
}		




function bmp_to_hex($bmp) {
  $output = array();
  
  for($i=0; $i < strlen($bmp); $i++) {
	  print_r(dechex(ord($bmp[$i])).' ');
    	$output[]= dechex(ord($bmp[$i]));  
  }
  return $output;
}




if (isset($test)) {
	
	$image = imagecreatefromstring(file_get_contents("https://sis.bulme.at/lehrerfoto/".strtolower($teacher).".jpg"));
	$image=imagescale($image,158,240);
	imagefilter($image, IMG_FILTER_GRAYSCALE); 
//	header('Content-Type: image/png');
//	imagepng($image);

	 print_r(init2($image,158,240));
} 




$img='';
$img = array_key_exists("img",$_GET) ? rawurlencode($_GET['img']) : null;



$w = array_key_exists("w",$_GET) ? rawurlencode($_GET['w']) : null;
$h =  array_key_exists("h",$_GET) ? rawurlencode($_GET['h']) : null;

if ($img=='png') header('Content-type: image/png; charset=utf-8');
else if ($img=='byte') echo '';
else header('Content-type: text/json; charset=utf-8');


	//echo "hallo";

$img_width= $w!=null ? $w : 800;
$img_height= $h!=null ? $h: 480;

//$im = @imagecreate($img_width, $img_height)
//$im = @imagecreatetruecolor ($img_width, $img_height)
//      or die("Kann keinen neuen GD-Bild-Stream erzeugen");

//$background_color = imagecolorallocatealpha($im,255, 255,255,127);
//imagefill($im, 0, 0, $background_color);
//if ($img=='png' || $img=='byte') {

//      imagealphablending($im, false);
//imagesavealpha($im, true);

//}
//$ratio=($img_height/800);
//echo "hallo";
$line="";
$fontsize=30*$ratio;
$row=1;
$refresh=0;

 if ($sqlResult = $my->query($subTeachers)) {
	 
	 //if ($sqlResult->affected_rows>0) {
  while($obj = $sqlResult->fetch_object()){
	  
	$obj->numbering=json_decode($obj->numbering);
	
	if ($refresh==0 && $obj->refresh_seconds>0) 
	{
		$refresh=$obj->refresh_seconds;
		unset($obj->refresh_seconds);
	}
	else unset($obj->refresh_seconds);
	
	if ($obj->numbering[$obj->order][$obj->group]==0) continue;

		$obj->teacher=html_entity_decode($obj->teacher);

	
	if ($img=='png' || $img=='byte') {
		$lastrow=printRow($im,$img_width,$row++,150,$obj->room,100*$ratio,0,$ratio);
		$lastrow=printRow($im,$img_width,$row++,25,'Klasse: '.$obj->class,50*$ratio,$lastrow,$ratio);
		//$lastrow=printRow($im,$img_width,$row++,25,$obj->class,50*$ratio,$lastrow,$ratio);
        $lastrow=printRow($im,$img_width,$row++,25,'Lehrer: '.html_entity_decode($obj->teacher,ENT_QUOTES),$fontsize,$lastrow,$ratio);
		$lastrow=printRow($im,$img_width,$row++,25,'Gruppe: '.$obj->numbering[$obj->order][$obj->group],50*$ratio,$lastrow,$ratio);
		
		if ($obj->supplierung==0)
			$lastrow=printRow($im,$img_width,$row++,25,html_entity_decode($obj->subject_short).' - '.html_entity_decode($obj->subject),40*$ratio,$lastrow,$ratio);
		//	$lastrow=printRow($im,$img_width,$row++,25,html_entity_decode($obj->subject),40*$ratio,$lastrow,$ratio);		
		else
			$lastrow=printRow($im,$img_width,$row++,25,html_entity_decode($obj->subject).' für '.html_entity_decode($obj->subteacher),40*$ratio,$lastrow,$ratio);
        $lastrow=printRow($im,$img_width,$row++,25,$obj->start.' - '.$obj->end,$fontsize,$lastrow,$ratio);

      $endtime=$obj->refreshtime;
      imagesavealpha($im, true);
      imagefilter($im, IMG_FILTER_GRAYSCALE);
		break;
	}
	else {

		$obj->group=$obj->numbering[$obj->order][$obj->group];
		
		unset($obj->numbering);
		unset($obj->order);
		
//	print_r($obj)
		$jsonArray[$i++]=$obj;	
	}
  }
  
//print_r("test");
	$sqlResult->close();
    unset($obj);
    unset($subTeachers);
    //uasort($jsonArray,sortbyDay);

/* }
 
	else {
		
        $lastrow=printRow($im,$img_width,$row++,150,'ECN ',100*$ratio,0,$ratio);
		$lastrow=printRow($im,$img_width,$row++,25,' ',50*$ratio,$lastrow,$ratio);

        $lastrow=printRow($im,$img_width,$row++,25,'Lehrer: Gerald Scherr',$fontsize,$lastrow,$ratio);
		$lastrow=printRow($im,$img_width,$row++,25,'',50*$ratio,$lastrow,$ratio);
		
 
			$lastrow=printRow($im,$img_width,$row++,25,'Sommer? Ferien!',40*$ratio,$lastrow,$ratio);
	
        $lastrow=printRow($im,$img_width,$row++,25,'08.07.2023 - 05.09.2023',$fontsize,$lastrow,$ratio);

      $endtime=0;
      imagesavealpha($im, true);
      imagefilter($im, IMG_FILTER_GRAYSCALE);
	 
	}*/
 }
}



/*$sql = "SELECT gt.numbering,gtt.order,t.kz,t.name_long as teacher,r.name as room,gh.name as class,TIME_FORMAT(hss.start,'%H:%i') as start,TIME_FORMAT(hs.end,'%H:%i') as end,
TIME_FORMAT(addtime( timediff ( DATE(gtd.day), DATE(now())) , subtime(hs.end,'0:02:0.0') ),'%H:%i') as refreshtime
,t_o.name as unittype,gtd.group as 'group',DATE_FORMAT(DATE(gtd.day),'%d.%m.%Y') as day,c.name_short as subject_short,c.name_long as subject FROM `gwp_timetable_teachers`  as gtt left join teachers as t on gtt.teacherid=t.id
 left join gwp_timetable gt on gtt.timetableid=gt.id
left join rooms r on gtt.room=r.id
left join gwp_head gh on gt.headid=gh.id
left join teaching_objects t_o on t_o.id=gt.object
left join gwp_timetable_days gtd on gtd.timetableid=gtt.timetableid
left join competence c on c.id=gtt.object
left join hourschool hs on hs.hour=gt.lesson_end
left join hourschool hss on hss.hour=gt.lesson_start
where  t.kz='$teacher'
and (timestamp(DATE( gtd.day ),hs.end)>=addtime(now(),'0:15:0.0'))
and gh.name not like '$%'
order by gtd.day,end
limit 0,".($img=='png' || $img=='byte' ? 5 : 5);
*/
//if (isset($test)) print_r($sql);



//if (!isset($test))
{
/*
 if ($result = $my->query($sql)) {
  while($obj = $result->fetch_object()){

  //print_r(json_decode($obj->numbering)[$obj->order][$obj->group]);
  $obj->numbering=json_decode($obj->numbering);
  if ($obj->numbering[$obj->order][$obj->group]==0) continue;

  $obj->teacher=html_entity_decode($obj->teacher);

if ($img=='png' || $img=='byte') {
		$lastrow=printRow($im,$img_width,$row++,150,$obj->room,100*$ratio,0,$ratio);
		$lastrow=printRow($im,$img_width,$row++,25,'Klasse: '.$obj->class,50*$ratio,$lastrow,$ratio);
        $lastrow=printRow($im,$img_width,$row++,25,'Lehrer: '.html_entity_decode($obj->teacher,ENT_QUOTES),$fontsize,$lastrow,$ratio);
		$lastrow=printRow($im,$img_width,$row++,25,'Gruppe: '.$obj->numbering[$obj->order][$obj->group],50*$ratio,$lastrow,$ratio);
		$lastrow=printRow($im,$img_width,$row++,25,html_entity_decode($obj->subject_short).' - '.html_entity_decode($obj->subject),40*$ratio,$lastrow,$ratio);
        $lastrow=printRow($im,$img_width,$row++,25,$obj->start.' - '.$obj->end,$fontsize,$lastrow,$ratio);

      $endtime=$obj->refreshtime;
      imagesavealpha($im, true);
      imagefilter($im, IMG_FILTER_GRAYSCALE);
	//break;
}
else {
	$obj->group=$obj->numbering[$obj->order][$obj->group];
	unset($obj->numbering);
	unset($obj->order);
	$jsonArray[$i++]=$obj;

}

}

	$result->close();
    unset($obj);
    unset($sql);
    unset($query);
 }
 else echo($my->error);
*/
}

if ($img=='png') {


imagepng($im,null,0,PNG_ALL_FILTERS );
}
else if($img=='byte') {


}
else {
	
//echo"hallo";
	if (isset($test) && $test=='sub') {
		$sortarray=array();
	/*	foreach($jsonArray as $lesson)
		{
			//print_r(new DateTime($lesson->day));
			
			if (count($sortarray)>0) {
				$tmpArray=$sortarray;
				$newArray=array();
				foreach($tmpArray as $sort){
					if (new DateTime($lesson->day)< new DateTime($sort->day)) {
					$newArray[]=$lesson;
					}
					$newArray[]=$sort;
				}
				$sortarray=$newArray;
			}
			else $sortarray[]=$lesson;
		}
		//print_r($sortarray);*/
		}
		
		
	echo json_encode(array('lessons' => $jsonArray,'refresh_seconds'=>$refresh,	'linkurl'=>'https://rb.gy/p8dhkm',
	'linkdescription'=>'EMC Wiki',
	'photourl'=>'https://sis.bulme.at/lehrerfoto/'.strtolower($teacher).'.jpg'
	));
}
function printRow(&$im,$img_width, $row,$left,$text,$fontsize,$lastrow,$ratio) {
	$font="./OpenSans-Regular.ttf";
	$text_color = imagecolorallocate($im, 0,0, 0);

	 list($lf,$bottom,$rf) = imageftbbox( $fontsize, 0, $font, $text);
	 $width=$rf-$lf;

   if ($width>=$img_width) {
      $fontsize=$fontsize*0.8;

      list($lf,$bottom,$rf) = imageftbbox( $fontsize, 0, $font, $text);
      $width=$rf-$lf;
    }

    if ($width>=$img_width) {
       $fontsize=$fontsize*0.7;

       list($lf,$bottom,$rf) = imageftbbox( $fontsize, 0, $font, $text);
       $width=$rf-$lf;
     }

    $pos=(($img_width/2)-($width/2));

	imagettftext($im, $fontsize, 0, $pos, $lastrow+($row*60)+20+($fontsize/2), $text_color,$font, $text);

	return $bottom+55*$ratio;
}



if ($img=='png' || $img=='byte') {



  $buf=init($im,$img_width,$img_height);

 $i=0;
  for ($r=0;$r<96;$r++){
    $line=substr($buf,$r*1000,1000).'iodaLOAD';
    echo $line;
    if ($i*1000 > strlen($buf)) break;
    $i++;
  }

  echo $endtime;

  imagedestroy($im);

  //$name = './epapertest.txt';
//$fp = fopen($name, 'rb');

// Gib Bild aus und stoppe Skript
//fpassthru($fp);
}


function init($im,$w,$h)
        {
            $array = array(); // Array of pixels
            $k = 0;            // Index of pixel in the array of pixels

            // Loading pixels into array
            //-------------------------------------------------

            for ($y = 0; $y < $h; $y++)
                for ($x = 0; $x < $w; $x++) {
                  $array[$k++]=getVal($im,imagecolorat($im,$x,$y));
                }

                $pxInd = 0;
                $buffInd=0;
                $BUFF_SIZE = $w*$h;
                $buffArr= "";

                while (($pxInd < count($array)) && ($buffInd < $BUFF_SIZE))
                               {
                                   $v = 0;
                                   for ($i = 0; $i < 8; $i++)
                                   {
                                       if (($pxInd < count($array)) && ($array[$pxInd] != 0)) $v |= (128 >> $i);
                                       $pxInd++;
                                   }

                                   $buffArr.=byteToStr($v);
                                   $buffInd++;
                               }
              return $buffArr;
        }



function init2($im,$w,$h)
        {
            $array = array(); // Array of pixels
            $k = 0;            // Index of pixel in the array of pixels

            // Loading pixels into array
            //-------------------------------------------------

            for ($y = 0; $y < $h; $y++)
                for ($x = 0; $x < $w; $x++) {
                  $array[$k++]=getVal($im,imagecolorat($im,$x,$y));
                }
				
				$pxInd = 0;
                $buffInd=0;
                $BUFF_SIZE = $w*$h;
                $buffArr= array();

				
						while (($pxInd < count($array)) && ($buffInd < $BUFF_SIZE))
                               {
                                   $v = 0;
                                   for ($i = 0; $i < 8; $i++)
                                   {
                                       if (($pxInd < count($array)) && ($array[$pxInd] != 0)) $v |= (128 >> $i);
                                       $pxInd++;
                                   }

                                   $buffArr[]=dechex($v);
                                   $buffInd++;
                               }
                
		
				
				
              return $buffArr;
        }

function byteToStr($v){
  return chr(($v & 0xF) + 97).chr((($v >> 4) & 0xF) + 97);
}

function byteToHex($v){
  return chr(($v & 0xF)).chr((($v >> 4) & 0xF) );
}

function getVal($im,$color)
         {
           $colors = imagecolorsforindex($im, $color);

            $r =$colors["red"];
            $b = $colors["blue"];
            $g = $colors["green"];


             if(($r == 0xFF) && ($b == 0xFF)) return 1;
             if(($r == 0x7F) && ($b == 0x7F)) return 2;
             if(($r == 0xFF) && ($b == 0x00)) return 3;
            return $r * $r + $g * $g + $b * $b;
            // return 0;
         }


?>

