<!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>Posté Devoir</title>
<link rel="stylesheet" href="w3.css">
</head>

<body>
<form method="post" enctype="multipart/form-data" action="_uploaddevoirdir.php">
<?php
include 'header.php';
include '_serveur.php';

echo '<table width="90%" border="0" cellpadding="1" cellspacing="1" class="box">';

// Select classes
$sql = 'SELECT * from classes ORDER BY id ASC';
$req = mysqli_query($link, $sql);

echo '<tr><td colspan="2">';
echo '<p><label class="w3-text-teal">Classe:</label>';

$i = 0;
while ($data = mysqli_fetch_array($req)) {
    $classe = strtoupper($data['name']);
    $classeid = $data['id'];
    echo '<input class="w3-check" type="checkbox" name="cla[]" value="'.$classeid.";".$classe.'"> <label>'.$classe.'</label>';
    $i++;
    if ($i == 4) { echo "<br>"; $i = 0; }
}
echo '</td></tr>';

// Select subjects
$sql = 'SELECT * from subjects ORDER BY ordering ASC';
$req = mysqli_query($link, $sql);

echo '<tr><td colspan="2">';
echo '<p><label class="w3-text-teal">Matières:</label>';

$i = 0;
while ($data = mysqli_fetch_array($req)) {
    $subject = $data['name'];
    $subjectID = $data['id'];
    echo '<input class="w3-check" type="radio" name="mat" value="'.$subjectID.";".$subject.'"> <label>'.$subject.'</label>';
    $i++;
    if ($i == 4) { echo "<br>"; $i = 0; }
}
echo '</td></tr>';
?>

<tr>
  <td><label class="w3-text-black">Titre:</label>
    <input name="title" type="text" id="titre" style="width:200px;" /></td>
  <td><label class="w3-text-black">Date:</label>
    <input name="date" type="date" id="date" style="width:200px;" value="<?php echo date('Y-m-d'); ?>" /></td>
</tr>

<tr>
  <td><label class="w3-text-black">Devoir (file):</label>
    <input name="userfile" type="file" class="style6" id="userfile" size="50" /></td>
  <td><input name="upload" type="submit" class="style6" id="upload" value=" Publier " /></td>
</tr>

</table>
</form>

<?php
include("csgSendPush.php");

if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
    $name     = preg_replace('/[^A-Za-z0-9-_ \.\[\]]/', '', $_FILES['userfile']['name']);
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $size     = $_FILES['userfile']['size'];
    $type     = $_FILES['userfile']['type'];
    $date     = $_POST['date'];
    $title    = $_POST['title'];
    $genre    = strtolower(substr($name, -3));

    $allowed = ["jpg", "peg", "gif", "png", "pdf", "ocx", "doc", "mp4", "mov", "ppt", "pps", "ptx", "psx", "mp3"];
    if (!in_array($genre, $allowed)) {
        echo '<div class="w3-panel w3-blue w3-round-xlarge"><p align="center">Genre de fichier interdit</p></div>';
        exit;
    }

    list($subjectID, $subject) = explode(";", $_POST['mat']);
    $cla1 = $_POST['cla'];

    for ($i = 0; $i < sizeof($cla1); $i++) {
        list($classeid, $classe) = explode(";", $cla1[$i]);
        $uploadDir = "DEVOIR/".$subjectID."/".$classeid."/";
        $filepath = $uploadDir.$name;

        if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);

        // Check if already exists
        $check = mysqli_query($link, 'SELECT * FROM devoirs WHERE classID="'.$classeid.'" AND date="'.$date.'" AND type="'.$type.'" AND url="'.$filepath.'"');
        $exists = mysqli_fetch_array($check);

        if (!$exists) {
            if ($i == 0) {
                $result = move_uploaded_file($tmpName, $filepath);
                if (!$result) {
                    echo "Erreur lors du téléchargement du fichier.";
                    exit;
                }
            } else {
                copy($uploadDir.$name, $filepath);
            }

            $insert = 'INSERT INTO devoirs VALUES(DEFAULT,"'.$classeid.'","'.$subjectID.'","'.$title.'","'.$date.'","'.$type.'","'.$filepath.'")';
            if (!mysqli_query($link, $insert)) {
                echo "ERROR: Could not execute $insert. " . mysqli_error($link);
            }

            echo '<div class="w3-panel w3-blue w3-round-xlarge"><p align="center">Devoir Téléchargé</p></div>';

            $students = mysqli_query($link, 'SELECT * FROM students JOIN users ON students.userID=users.id WHERE classID="'.$classeid.'"');
            $j = 0;
            while ($data = mysqli_fetch_array($students)) {
                $userID[$j] = $data['userID'];
                $title1 = "Voir le devoir de ".$subject;
                $message = "Voir le devoir '".$title."' envoyé le ".$date;
                $notif = 'INSERT INTO notifications VALUES(DEFAULT,"'.$title1.'","'.$message.'","'.$date.'",NULL,"'.$userID[$j].'")';
                mysqli_query($link, $notif);
                $j++;
            }

            for ($p = 0; $p < $j; $p++) {
                $devices = mysqli_query($link, 'SELECT * FROM devices WHERE userID="'.$userID[$p].'"');
                while ($d = mysqli_fetch_array($devices)) {
                    $deviceType = $d['type'];
                    $pushid = (string)$d['id'];
                    if ($deviceType == "ios") $deviceType = "iOS";
                    $payload = [
                        'type' => $deviceType,
                        'data' => ["title" => $title1, "body" => $message],
                        'devices' => [$pushid]
                    ];
                    echo sendPush(json_encode($payload));
                }
            }

            // Admins
            $admins = mysqli_query($link, 'SELECT * FROM devices WHERE userID IN (10001, 10055, 230100)');
            while ($d = mysqli_fetch_array($admins)) {
                $deviceType = $d['type'];
                $pushid = (string)$d['id'];
                if ($deviceType == "ios") $deviceType = "iOS";
                $payload = [
                    'type' => $deviceType,
                    'data' => ["title" => $title1, "body" => $message],
                    'devices' => [$pushid]
                ];
                echo sendPush(json_encode($payload));
            }

        } else {
            echo '<div class="w3-panel w3-blue w3-round-xlarge"><p align="center">Devoir déjà existant</p></div>';
        }
    }
}
?>
</body>
</html>