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

include("_serveur.php"); // Database connection

// --- Handle deletion (DB + file) ---
if (isset($_POST['delete_id'])) {
    $delete_id = intval($_POST['delete_id']);

    // Get the file path before deleting
    $resFile = mysqli_query($link, "SELECT url FROM circulairStudent WHERE id='$delete_id' LIMIT 1");
    if ($resFile && mysqli_num_rows($resFile) > 0) {
        $fileRow = mysqli_fetch_assoc($resFile);
        $filePath = trim($fileRow['url']);

        // Build full path inside 'circulaire/' directory
        $baseDir = __DIR__ . "/circulaire/";
        $fullPath = (strpos($filePath, 'circulaire/') === false)
            ? $baseDir . basename($filePath)
            : __DIR__ . "/" . $filePath;

        // Delete file if exists
        if (file_exists($fullPath)) {
            unlink($fullPath);
        }
    }

    // Delete record from DB
    mysqli_query($link, "DELETE FROM circulairStudent WHERE id='$delete_id'");
}

// --- Optional filters ---
$selected_class = $_GET['class_id'] ?? '';
$selected_student = $_GET['student_id'] ?? '';

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

// Fetch students for selected class
$students = [];
if (!empty($selected_class)) {
    $res = mysqli_query($link, "SELECT id, firstname, lastname 
                                FROM students 
                                WHERE classID='$selected_class'
                                ORDER BY firstname, lastname");
    if ($res) $students = mysqli_fetch_all($res, MYSQLI_ASSOC);
}

// --- Fetch circulars ---
$where = [];
if (!empty($selected_student)) $where[] = "cs.studentId = '$selected_student'";
elseif (!empty($selected_class)) $where[] = "s.classID = '$selected_class'";
$filter = $where ? "WHERE " . implode(" AND ", $where) : "";

$sql = "SELECT cs.id, cs.title, cs.date, cs.type, cs.url,
               s.firstname, s.lastname, c.name AS class_name, cy.name AS cycle_name
        FROM circulairStudent cs
        LEFT JOIN students s ON cs.studentId = s.id
        LEFT JOIN classes c ON s.classID = c.id
        LEFT JOIN cycles cy ON c.cycleID = cy.id
        $filter
        ORDER BY cs.date DESC, cs.id DESC";

$res = mysqli_query($link, $sql);
$circulars = $res ? mysqli_fetch_all($res, MYSQLI_ASSOC) : [];
?>

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Voir les Circulaires</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<style>
body {
  font-family: Arial, sans-serif;
  margin: 20px;
  background-color: #f8f9fa;
}
h2 {
  color: #002b80;
  margin-bottom: 20px;
}
table {
  border-collapse: collapse;
  width: 100%;
  background: white;
}
th, td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}
th {
  background: #003366;
  color: white;
}
tr:nth-child(even) {
  background: #f2f2f2;
}
a.btn, button {
  padding: 6px 10px;
  border: none;
  border-radius: 5px;
  text-decoration: none;
  cursor: pointer;
  font-size: 14px;
}
a.btn {
  background: #003366;
  color: white;
}
a.btn:hover {
  background: #0055aa;
}
button.delete {
  background: #b30000;
  color: white;
}
button.delete:hover {
  background: #e60000;
}
form { margin-bottom: 15px; }
form.inline { display: inline; }
</style>

<script>
// Confirmation before delete
function confirmDelete(id) {
    if (confirm("Voulez-vous vraiment supprimer cette circulaire ?")) {
        document.getElementById('deleteForm_' + id).submit();
    }
}
</script>
</head>
<body>

<h2>📜 Liste des Circulaires</h2>

<!-- Filter Form -->
<form method="get" class="w3-container w3-light-grey w3-padding">
    <label>Cycle / Classe :</label>
    <select name="class_id" onchange="this.form.submit()">
        <option value="">-- Toutes les classes --</option>
        <?php foreach ($classes as $c): ?>
            <option value="<?= $c['id'] ?>" <?= $selected_class==$c['id']?'selected':'' ?>>
                <?= htmlspecialchars($c['cycle_name']." - ".$c['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <?php if ($students): ?>
        <label>Élève :</label>
        <select name="student_id" onchange="this.form.submit()">
            <option value="">-- Tous les élèves --</option>
            <?php foreach ($students as $s): ?>
                <option value="<?= $s['id'] ?>" <?= $selected_student==$s['id']?'selected':'' ?>>
                    <?= htmlspecialchars($s['firstname']." ".$s['lastname']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    <?php endif; ?>
</form>

<!-- Circulars Table -->
<?php if ($circulars): ?>
<table>
    <tr>
        <th>Titre</th>
        <th>Date</th>
        <th>Type</th>
        <th>Élève</th>
        <th>Classe</th>
        <th>Actions</th>
    </tr>
    <?php foreach ($circulars as $c): ?>
    <tr>
        <td><?= htmlspecialchars($c['title']) ?></td>
        <td><?= htmlspecialchars($c['date']) ?></td>
        <td><?= htmlspecialchars($c['type']) ?></td>
        <td><?= htmlspecialchars($c['firstname'].' '.$c['lastname']) ?></td>
        <td><?= htmlspecialchars($c['cycle_name'].' - '.$c['class_name']) ?></td>
        <td>
            <a href="<?= htmlspecialchars($c['url']) ?>" target="_blank" class="btn">📄 Voir</a>
            <a href="<?= htmlspecialchars($c['url']) ?>" download class="btn">⬇️ Télécharger</a>
            <form method="post" class="inline" id="deleteForm_<?= $c['id'] ?>">
                <input type="hidden" name="delete_id" value="<?= $c['id'] ?>">
                <button type="button" class="delete" onclick="confirmDelete(<?= $c['id'] ?>)">🗑️ Supprimer</button>
            </form>
        </td>
    </tr>
    <?php endforeach; ?>
</table>
<?php else: ?>
<p>Aucun circulaire trouvé pour ce filtre.</p>
<?php endif; ?>

</body>
</html>
