<?php
$lesson=array();   
$d1=$day."1";$d2=$day."2";$d3=$day."3";$d4=$day."4";$d5=$day."5";$d6=$day."6";$d7=$day."7";
   mysqli_set_charset($con, "utf8");
   mysqli_query($con,"DROP TEMPORARY TABLE IF EXISTS t1") ;
   $result = mysqli_query($con,"CREATE  TEMPORARY TABLE t1  (SELECT id,Teacher, ".$d1.",".$d2.",".$d3.",".$d4.",".$d5.",".$d6.",".$d7." FROM timetable WHERE Teacher='$teach')");
   $result = mysqli_query($con,"SELECT * FROM t1 " );
   $rowsub = mysqli_fetch_array($result);
   $id=$rowsub['id']+1;
   $result = mysqli_query($con,"INSERT INTO t1  (SELECT id,Teacher, ".$d1.",".$d2.",".$d3.",".$d4.",".$d5.",".$d6.",".$d7." FROM timetable WHERE id='$id')"); 
	
   $result = mysqli_query($con,"SELECT * FROM t1 " ); 
   $rowsub = mysqli_fetch_array($result);
   $n=mysqli_num_rows($result);
   $id=$rowsub['id'];
   $i=1;
   while ($i<=7) {
     $in=$day.$i;
     $l=$rowsub["$in"];
     $lesson[$i]= rtrim(ltrim($l));
     $i++;
   }
  
   //print_r($lesson)."xxx"."<br>";
   
   $res = mysqli_query($con,"SELECT * FROM allages WHERE date='$dt' and idteacher= '$id' " );
   $id1=$id+1; 
   if (mysqli_num_rows($res) > 0){
	   while ($rowu = mysqli_fetch_array($res)) {
		   $id=$rowu['idteacher'];
		   $fromper=$rowu['fromper'];
		   $toper=$rowu['toper'];
		   
		   $ltochange=$lesson[$fromper];  
		   $ftoblanc=$day.$fromper;
		   $ftochange=$day.$toper;
		   $resu = mysqli_query($con,"UPDATE t1 SET ".$ftochange." = '$ltochange',".$ftoblanc."=' '  WHERE id='$id'  " );
	       $result = mysqli_query($con,"SELECT * FROM t1 WHERE id='$id1'  " ); 
           $rowsub = mysqli_fetch_array($result);
          $d1=$day.$fromper;$d2=$day.$toper;
         $l1=$rowsub["$d1"];
          $resu = mysqli_query($con,"UPDATE t1 SET ".$ftochange." = '$l1',".$ftoblanc."=' '  WHERE id='$id1'  " );
       }
   }