`;
}
this.selectionMenu.innerHTML = congeSection + gardeSection;
this.positionAndShowMenu(e);
}
positionAndShowMenu(e) {
this.selectionMenu.style.display = "block";
this.selectionMenu.style.left = `${e.pageX + 5}px`;
this.selectionMenu.style.top = `${e.pageY + 5}px`;
this.menuJustOpened = true;
}
async handleMenuClick(e) {
const button = e.target.closest("button[data-action]");
if (!button) return;
const { action, eventId, newType, type, person, date } = button.dataset;
// === AJOUT MULTI-JOURS (sélection de plusieurs cellules) ===
if (action === "add") {
const selectedDates = this.selectedCells.map((c) => c.dataset.date);
const existingOnDates = this.dbEvents.filter((evt) =>
selectedDates.includes(evt.date)
);
// Contrôles métier : pas de double congé / pas de double mode de garde
if (CONGE_TYPES.includes(type)) {
const hasCongeConflict = existingOnDates.some((evt) =>
CONGE_TYPES.includes(evt.type)
);
if (hasCongeConflict) {
alert(
"Impossible d'ajouter un congé : au moins une date a déjà un congé (Off/Extra Off)."
);
this.clearSelection();
return;
}
} else if (GUARDE_TYPES.includes(type)) {
const hasGardeConflict = existingOnDates.some((evt) =>
GUARDE_TYPES.includes(evt.type)
);
if (hasGardeConflict) {
alert(
"Impossible d'ajouter un mode de garde : au moins une date a déjà Centre/Avis."
);
this.clearSelection();
return;
}
}
const newEvents = this.selectedCells.map((cell) => ({
date: cell.dataset.date,
type,
person,
duration: 1.0,
}));
this.clearSelection();
try {
const response = await fetch("/api/save-events.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newEvents),
});
if (!response.ok) {
throw new Error("Erreur HTTP " + response.status);
}
// Resync DB events
const resEvents = await fetch("/api/get-events.php");
if (!resEvents.ok) {
throw new Error("Erreur lors du rechargement des événements.");
}
const dataEvents = await resEvents.json();
this.dbEvents = dataEvents.events || [];
this.events = [...this.dbEvents, ...this.fixedEvents];
this.reprocessAndRender();
} catch (err) {
console.error(err);
alert("Erreur lors de l'ajout.");
}
return;
}
// === AJOUT SUR UNE SEULE DATE (menu combiné d'un jour) ===
if (action === "add-single") {
const targetDate = date;
const existingOnDate = this.dbEvents.filter(
(evt) => evt.date === targetDate
);
if (CONGE_TYPES.includes(type)) {
const hasCongeConflict = existingOnDate.some((evt) =>
CONGE_TYPES.includes(evt.type)
);
if (hasCongeConflict) {
alert("Un congé existe déjà ce jour-là.");
this.clearSelection();
return;
}
} else if (GUARDE_TYPES.includes(type)) {
const hasGardeConflict = existingOnDate.some((evt) =>
GUARDE_TYPES.includes(evt.type)
);
if (hasGardeConflict) {
alert("Un mode de garde existe déjà ce jour-là.");
this.clearSelection();
return;
}
}
const newEvent = {
date: targetDate,
type,
person,
duration: 1.0,
};
this.clearSelection();
try {
const response = await fetch("/api/save-events.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify([newEvent]),
});
if (!response.ok) {
throw new Error("Erreur HTTP " + response.status);
}
// Resync DB events
const resEvents = await fetch("/api/get-events.php");
if (!resEvents.ok) {
throw new Error("Erreur lors du rechargement des événements.");
}
const dataEvents = await resEvents.json();
this.dbEvents = dataEvents.events || [];
this.events = [...this.dbEvents, ...this.fixedEvents];
this.reprocessAndRender();
} catch (err) {
console.error(err);
alert("Erreur lors de l'ajout.");
}
return;
}
// === SUPPRESSION ===
if (action === "delete") {
if (!eventId) {
console.warn("Bouton delete sans eventId, action ignorée.");
this.clearSelection();
return;
}
this.clearSelection();
try {
const response = await fetch("/api/manage-event.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "delete", event_id: eventId }),
});
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(
errData.message || "Erreur HTTP " + response.status
);
}
// Resync DB events
const resEvents = await fetch("/api/get-events.php");
if (!resEvents.ok) {
throw new Error("Erreur lors du rechargement des événements.");
}
const dataEvents = await resEvents.json();
this.dbEvents = dataEvents.events || [];
this.events = [...this.dbEvents, ...this.fixedEvents];
this.reprocessAndRender();
} catch (err) {
console.error(err);
alert("Erreur lors de la suppression : " + err.message);
}
return;
}
// === MODIFICATION (change OFF <-> EXTRA ou CENTRE <-> AVIS) ===
if (action === "update") {
console.log("[UPDATE] click sur bouton update", { eventId, newType });
if (!eventId) {
console.warn("Bouton update sans eventId, action ignorée.");
this.clearSelection();
return;
}
this.clearSelection();
try {
const response = await fetch("/api/manage-event.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "update",
event_id: eventId,
new_type: newType,
}),
});
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(
errData.message || "Erreur HTTP " + response.status
);
}
// Resync DB events
const resEvents = await fetch("/api/get-events.php");
if (!resEvents.ok) {
throw new Error("Erreur lors du rechargement des événements.");
}
const dataEvents = await resEvents.json();
this.dbEvents = dataEvents.events || [];
this.events = [...this.dbEvents, ...this.fixedEvents];
this.reprocessAndRender();
} catch (err) {
console.error("[UPDATE] Erreur lors de la modification :", err);
alert("Erreur lors de la modification : " + err.message);
}
return;
}
}
async manageEvent(payload) {
try {
const response = await fetch("/api/manage-event.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || "Erreur HTTP " + response.status);
}
const resEvents = await fetch("/api/get-events.php");
if (!resEvents.ok) {
throw new Error("Erreur lors du rechargement des événements.");
}
const dataEvents = await resEvents.json();
this.dbEvents = dataEvents.events || [];
this.events = [...this.dbEvents, ...this.fixedEvents];
this.reprocessAndRender();
this.renderMonthCalendar();
} catch (error) {
console.error("Erreur manageEvent :", error);
alert("Erreur: " + error.message);
}
}
// ================== CALENDRIER MENSUEL ==================
navigateMonth(direction) {
this.currentMonth.setMonth(this.currentMonth.getMonth() + direction);
this.renderMonthCalendar();
}
renderMonthCalendar() {
if (!this.monthCalendar) return;
const year = this.currentMonth.getFullYear();
const month = this.currentMonth.getMonth();
const monthName = getMonthNameFr(month);
// Mettre à jour le titre
const monthTitle = document.getElementById("fc-current-month-year");
if (monthTitle) {
monthTitle.textContent = `${monthName} ${year}`;
}
// Premier jour du mois et dernier jour
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const daysInMonth = lastDay.getDate();
const startDayOfWeek =
firstDay.getDay() === 0 ? 6 : firstDay.getDay() - 1; // Lundi = 0
// Noms des jours
const dayNames = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];
let html = '
';
dayNames.forEach((day) => {
html += `
${day}
`;
});
html += "
";
// Jours du mois précédent (si nécessaire)
let dayCount = 0;
html += "
";
for (let i = 0; i < startDayOfWeek; i++) {
html += '
';
dayCount++;
}
// Jours du mois actuel
for (let day = 1; day <= daysInMonth; day++) {
if (dayCount % 7 === 0 && day > 1) {
html += "
";
}
const date = new Date(year, month, day);
const isoDate = `${year}-${String(month + 1).padStart(2, "0")}-${String(
day
).padStart(2, "0")}`;
// Trouver les événements pour ce jour
const dayEvents = this.events.filter((evt) => evt.date === isoDate);
let classes = "fc-month-day";
let hasGarde = false;
let gardeType = null;
dayEvents.forEach((evt) => {
const classMap = {
VACANCES_SCOLAIRES: "fc-day--school-holiday",
PUBLIC_HOLIDAY: "fc-day--public-holiday",
OFF_CAROLE: "fc-day--off-carole",
EXTRA_OFF_CAROLE: "fc-day--extra-off-carole",
};
if (classMap[evt.type]) {
classes += " " + classMap[evt.type];
}
if (GUARDE_TYPES.includes(evt.type)) {
hasGarde = true;
gardeType = evt.type;
}
});
if (hasGarde) {
classes += " fc-day--has-guard";
if (gardeType === "CENTRE") classes += " fc-day--centre";
if (gardeType === "AVIS") classes += " fc-day--avis";
}
// Week-end
const dayOfWeek = date.getDay();
if (dayOfWeek === 0 || dayOfWeek === 6) {
classes += " fc-day--weekend";
}
html += `
${day}
`;
dayCount++;
}
// Jours du mois suivant (pour compléter la dernière ligne)
const remainingDays = 7 - (dayCount % 7);
if (remainingDays < 7) {
for (let i = 0; i < remainingDays; i++) {
html += '