<?php session_start(); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>

<body>
<?php 
 include 'header.php';
include '_serveur.php';

$cla1=$_SESSION['cla1'];
$title=$_SESSION['title'];
$message=$_SESSION['message'];
$date1=$_SESSION['date1'];
$i=0;
while($i<=sizeof($cla1)){
$sql = 'SELECT * from students join users on students.userID=users.id 
								join classes on students.classID=classes.id  where classes.id="'.$cla1[$i].'" order by classes.id ASC';
   if(!(mysqli_query($link, $sql))){
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$req=  mysqli_query($link, $sql);

 while($data = mysqli_fetch_array($req)) {
$classe=$data[14];
$classeid=$data[4];
$userID[$j]=$data[1];
$userType=$data[11];

$sql1= 'INSERT INTO notifications VALUES(DEFAULT,"'.$title.'","'.$message.'","'.$date1.'",NULL,"'.$userID[$j].'")';
   if(!(mysqli_query($link, $sql1))){
    echo "ERROR: Could not able to execute $sql1. " . mysqli_error($link);
        }
		$j++;
		
 }
 $i=$i+1;
}
include("sjmSendPush.php");
$res_cycle = mysqli_query($link, "SELECT cycleID FROM classes WHERE id='$classeid'");
$row_cycle = mysqli_fetch_assoc($res_cycle);
$cycleid = $row_cycle['cycleID'] ?? null;

for($p=0;$p<=$j;$p++){
if(($cycleid==1)or($cycleid==2)){
				  $sql = 'SELECT * FROM devices 
            WHERE userID="' . $userID[$p] . '" 
            OR userID IN (240200,100102, 10023)';
			                       }
								   else
								   {
				$sql = 'SELECT * FROM devices 
            WHERE userID="' . $userID[$p] . '" 
            OR userID IN (253062,100102, 10023,10010)';
									   }
   if(!(mysqli_query($link, $sql))){
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
                          }
$req=  mysqli_query($link, $sql);

echo "<table width='95%' border=1 bordercolor='#D1FAFC'>"; 
while ($data = mysqli_fetch_array($req)) {
	                 $deviceType=$data[2];
					 $pushid=$data[0];
					 $pushid=(string)$pushid;

                      if($deviceType=="ios") $deviceType="iOS";
                      $payload = array('type' =>$deviceType,
					           'data'=>["title" => $title, "body" => $message],
							   'devices' =>[$pushid]);
					 
                     echo sendPush(json_encode($payload));
                          }
					
}



 echo ' <div class="w3-panel w3-leftbar w3-sand w3-xxlarge w3-serif">
    <p><i>"Notifications déjà faite"</i></p>
  </div>';
?>
</body>
</html>