<?php
session_start();
include "_serveur.php";
include "sjmSendPush.php"; // Your push function
mysqli_set_charset($link, "utf8");

$userID = $_SESSION['id'] ?? 0;
if (!$userID) die("Utilisateur non connecté.");

if (!isset($_POST['cont'], $_FILES['userfile'], $_POST['title'], $_POST['date'])) {
    die("Champs manquants.");
}

$title = trim($_POST['title']);
$date  = $_POST['date'];
$cont  = $_POST['cont'];
$file  = $_FILES['userfile'];

if ($file['error'] !== UPLOAD_ERR_OK) die("Erreur fichier: " . $file['error']);

$filename = preg_replace('/[^A-Za-z0-9\-_.]/', '', $file['name']);
$tmpName  = $file['tmp_name'];
$type     = $file['type'];

$allowed = ['jpg','jpeg','gif','png','pdf','doc','docx','mp4','mov','ppt','pps','ptx','mp3'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) die("Type de fichier interdit.");

// Move uploaded file once to a temporary location
$baseUploadDir = "FICHE/TEMP/";
if (!is_dir($baseUploadDir)) mkdir($baseUploadDir, 0777, true);
$tempPath = $baseUploadDir . $filename;
if (!move_uploaded_file($tmpName, $tempPath)) die("Erreur lors du déplacement du fichier.");

// Loop through all selected classes
foreach ($cont as $item) {
    list($classID, $className, $subjectID, $subjectName) = explode(';', $item);

    $uploadDir = "FICHE/$subjectID/$classID/";
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

    $targetPath = $uploadDir . $filename;

    // Copy the file to the class folder
    if (!file_exists($targetPath)) copy($tempPath, $targetPath);

    // Insert into fiches table
    $stmt = mysqli_prepare($link, "INSERT INTO fiches (classID, subjectID, title, date, type, url) VALUES (?,?,?,?,?,?)");
    mysqli_stmt_bind_param($stmt, "iissss", $classID, $subjectID, $title, $date, $type, $targetPath);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    echo "<div class='w3-panel w3-blue'>Fiche publiée pour $className - $subjectName</div>";

    // Prepare push notification message
    $title1 = "Voir la fiche de $subjectName";
    $message = "Fiche '$title' envoyée le $date";

    // --- Collect all recipients: students of the class + specific users ---
    $userIDs = [];

    // Students in this class
    $sql = "SELECT students.userID FROM students WHERE students.classID = $classID";
    $res = mysqli_query($link, $sql);
    while ($row = mysqli_fetch_assoc($res)) $userIDs[] = $row['userID'];
         
    // Add specific users
    
if (in_array($classID, [101, 102, 103, 104, 105, 106, 107])) {
    $userIDs[] = 100103;
    $userIDs[] = 100102;
} else {
    $userIDs[] = 10010;
    $userIDs[] = 100102;
}    // Remove duplicates
    $userIDs = array_unique($userIDs);

    // Send notification & insert into notifications table
    foreach ($userIDs as $uid) {
        // Insert notification
        $stmt = mysqli_prepare($link, "INSERT INTO notifications (title, description, date, userType, userID) VALUES (?,?,?,?,?)");
        $userType = 0;
        mysqli_stmt_bind_param($stmt, "sssii", $title1, $message, $date, $userType, $uid);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);

        // Send push
        $sql2 = "SELECT * FROM devices WHERE userID=$uid";
        $res2 = mysqli_query($link, $sql2);
        while ($d = mysqli_fetch_assoc($res2)) {
            $deviceType = $d['deviceType'] ?? '';
            $pushid = (string)$d['id'];
            if ($deviceType == "ios") $deviceType = "iOS";

            $payload = [
                'type' => $deviceType,
                'data' => ['title' => $title1, 'body' => $message],
                'devices' => [$pushid]
            ];
            echo sendPush(json_encode($payload));
        }
    }
}

// Optional: delete temporary file
if (file_exists($tempPath)) unlink($tempPath);
?>
