<head>
<script>
function toggleAll(source, groupName) {
    const checkboxes = document.querySelectorAll(`input[name="${groupName}[]"]`);
    checkboxes.forEach(cb => cb.checked = source.checked);
}
</script>
</head>

<?php
ini_set('display_errors', 0);
error_reporting(0);

include("_serveur.php"); // mysqli connection
require_once("sjmSendPush.php"); // sendPush($payload)

function clean_input($link, $data) {
    return mysqli_real_escape_string($link, trim($data));
}

// --- Handle form submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['student_ids']) && isset($_FILES['circular_file'])) {
    $title = clean_input($link, $_POST['title']);
    $date = clean_input($link, $_POST['date']);
    $student_ids = $_POST['student_ids'];

    if (empty($student_ids)) {
        echo "<p style='color:red'>❌ Veuillez sélectionner au moins un élève.</p>";
    } else {
        // --- File validation ---
        $allowedTypes = [
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'image/jpeg','image/png','image/gif'
        ];

        $fileType = $_FILES['circular_file']['type'];
        if (!in_array($fileType, $allowedTypes)) {
            echo "<p style='color:red'>❌ Type de fichier non valide.</p>";
            exit;
        }
        if ($_FILES['circular_file']['size'] > 5*1024*1024) {
            echo "<p style='color:red'>❌ Fichier trop volumineux (max 5MB).</p>";
            exit;
        }

        // --- Upload file ---
        $uploadDir = 'circulaire/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        $filename = basename($_FILES['circular_file']['name']);
        $targetFile = $uploadDir . time() . "_" . $filename;

        if (!move_uploaded_file($_FILES['circular_file']['tmp_name'], $targetFile)) {
            echo "<p style='color:red'>❌ Échec du téléchargement du fichier.</p>";
            exit;
        }

        // --- Detect file type ---
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        $map = [
            'pdf'=>'PDF','doc'=>'Word','docx'=>'Word',
            'xls'=>'Excel','xlsx'=>'Excel',
            'jpg'=>'Image','jpeg'=>'Image','png'=>'Image','gif'=>'Image'
        ];
        $typeDetected = $map[$ext] ?? 'Autre';

        // --- Insert into circulairStudent ---
        $stmt = mysqli_prepare($link, "INSERT INTO circulairStudent (studentId, title, date, type, url) VALUES (?, ?, ?, ?, ?)");
        if ($stmt) {
            foreach ($student_ids as $sid) {
                $sid = intval($sid);
                mysqli_stmt_bind_param($stmt, "issss", $sid, $title, $date, $typeDetected, $targetFile);
                mysqli_stmt_execute($stmt);
            }
            mysqli_stmt_close($stmt);
        }

        echo "<p style='color:green'>✅ Circulaire importée avec succès pour les élèves sélectionnés.</p>";

        // --- Prepare notification messages ---
        $message = "Voir le circulaire nommé " . $title;
        $today = date('Y-m-d');
        $datetime = date('d/m/Y à H:i');

        // --- Collect student names ---
        $studentNames = [];
        foreach ($student_ids as $sid) {
            $sid = intval($sid);
            $res = mysqli_query($link, "SELECT firstname, lastname FROM students WHERE id=$sid");
            if ($r = mysqli_fetch_assoc($res)) {
                $studentNames[] = trim($r['firstname'] . ' ' . $r['lastname']);
            }
        }

        // Sort alphabetically by last name
        usort($studentNames, function($a, $b) {
            $aLast = explode(' ', $a);
            $bLast = explode(' ', $b);
            return strcasecmp(end($aLast), end($bLast));
        });

        // Limit to 5 names for display
        $displayNames = array_slice($studentNames, 0, 5);
        $studentList = implode(', ', $displayNames);
        if (count($studentNames) > 5) {
            $studentList .= ' et autres...';
        }

        // --- Direction message ---
        $dirMessage = "Un nouveau circulaire a été envoyé le $datetime aux élèves : $studentList";

        // --- Notify selected students ---
        foreach ($student_ids as $sid) {
            $sid = intval($sid);
            $res = mysqli_query($link, "SELECT userID FROM students WHERE id=$sid");
            if (!$res) continue;
            $r = mysqli_fetch_assoc($res);
            if (!$r) continue;
            $userID = intval($r['userID']);

            // Insert into notifications table
            $stmtNotif = mysqli_prepare($link, "INSERT INTO notifications (title, description, date, userType, userID) VALUES (?, ?, ?, NULL, ?)");
            if ($stmtNotif) {
                mysqli_stmt_bind_param($stmtNotif, "sssi", $title, $message, $today, $userID);
                mysqli_stmt_execute($stmtNotif);
                mysqli_stmt_close($stmtNotif);
            }

            // Send push to student's devices
            $devRes = mysqli_query($link, "SELECT * FROM devices WHERE userID=$userID");
            while ($data = mysqli_fetch_assoc($devRes)) {
                $deviceType = strtolower(trim($data['deviceType']));
                $pushid = isset($data['pushid']) ? (string)$data['pushid'] : (string)$data['id'];
                if ($deviceType == "ios") $deviceType = "iOS";
                if (!$pushid || !$deviceType) continue;

                $payload = [
                    'type' => $deviceType,
                    'data' => ["title" => $title, "body" => $message],
                    'devices' => [$pushid]
                ];

                sendPush(json_encode($payload));
            }
        }

        // --- Notify direction users (type = 1) ---
        $dirRes = mysqli_query($link, "SELECT id FROM users WHERE type = 1");
        while ($dir = mysqli_fetch_assoc($dirRes)) {
            $dirID = intval($dir['id']);

            // Insert into notifications table
            $stmtDir = mysqli_prepare($link, "INSERT INTO notifications (title, description, date, userType, userID) VALUES (?, ?, ?, NULL, ?)");
            if ($stmtDir) {
                mysqli_stmt_bind_param($stmtDir, "sssi", $title, $dirMessage, $today, $dirID);
                mysqli_stmt_execute($stmtDir);
                mysqli_stmt_close($stmtDir);
            }

            // Send push to direction devices
            $dirDevRes = mysqli_query($link, "SELECT * FROM devices WHERE userID=$dirID");
            while ($data = mysqli_fetch_assoc($dirDevRes)) {
                $deviceType = strtolower(trim($data['deviceType']));
                $pushid = isset($data['pushid']) ? (string)$data['pushid'] : (string)$data['id'];
                if ($deviceType == "ios") $deviceType = "iOS";
                if (!$pushid || !$deviceType) continue;

                $payload = [
                    'type' => $deviceType,
                    'data' => ["title" => $title, "body" => $dirMessage],
                    'devices' => [$pushid]
                ];

                echo sendPush(json_encode($payload));
            }
        }
    }
}

// --- Fetch classes & students ---
$classes = [];
$res = mysqli_query($link, "SELECT c.id, c.name, cy.name AS cycle_name
                            FROM classes c
                            LEFT JOIN cycles cy ON c.cycleID = cy.id
                            ORDER BY cy.name, c.name");
if ($res) $classes = mysqli_fetch_all($res, MYSQLI_ASSOC);

$students = [];
if (!empty($_GET['class_id'])) {
    $cid = intval($_GET['class_id']);
    $res = mysqli_query($link, "SELECT s.id, s.firstname, s.lastname, u.firstName AS fatherName
                                FROM students s
                                LEFT JOIN users u ON s.userID = u.id
                                WHERE s.classID = $cid
                                ORDER BY s.firstname, s.lastname");
    if ($res) $students = mysqli_fetch_all($res, MYSQLI_ASSOC);
}
?>

<!-- Class selection -->
<form method="get">
    <label>Choisir classe:</label>
    <select name="class_id" onchange="this.form.submit()">
        <option value="">-- Choisir --</option>
        <?php foreach ($classes as $c): ?>
            <option value="<?= $c['id'] ?>" <?= (!empty($_GET['class_id']) && $_GET['class_id']==$c['id'])?'selected':'' ?>>
                <?= htmlspecialchars($c['cycle_name']." - ".$c['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</form>

<!-- Students & circular upload -->
<?php if ($students): ?>
<form method="post" enctype="multipart/form-data">
    <input type="checkbox" onclick="toggleAll(this,'student_ids')" class="w3-check">
    <label><b>Sélectionner tout</b></label><br>

    <h3>Sélectionnez les élèves d'une classe</h3>
    <?php foreach ($students as $s): ?>
        <label>
            <input type="checkbox" name="student_ids[]" value="<?= $s['id'] ?>">
            <?= htmlspecialchars($s['firstname'].' '.$s['lastname']) ?>
            (Père: <?= htmlspecialchars($s['fatherName'] ?? 'N/A') ?>)
        </label><br>
    <?php endforeach; ?>

    <h3>Détails du circulaire</h3>
    <label>Titre: <input type="text" name="title" required></label><br>
    <label>Date: <input type="date" name="date" required></label><br>
    <label>Importer Circulaire: <input type="file" name="circular_file" required></label><br><br>
    <button type="submit">Importer Circulaire</button>
</form>
<?php endif; ?>
