// Module ES6 pour les appels API de l'agenda export async function apiFetch(endpoint, options = {}) { const root = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : '/wp-json/'; const base = root.endsWith('/') ? root : (root + '/'); const url = `${base}crvi/v1/${endpoint}`.replace(/([^:]\/)\/+/g, '$1'); // normaliser les doubles / const headers = { 'Content-Type': 'application/json', ...(window.wpApiSettings ? { 'X-WP-Nonce': window.wpApiSettings.nonce } : {}) }; const opts = { ...options, headers: { ...headers, ...(options.headers || {}) } }; try { // Démarrage indicateur global try { window.CRVI_LOADING && typeof window.CRVI_LOADING.start === 'function' && window.CRVI_LOADING.start(); } catch (_) {} const response = await fetch(url, opts); if (!response.ok) { let serverText = ''; try { serverText = await response.text(); } catch (_) {} const err = new Error(`HTTP ${response.status}: ${response.statusText} | endpoint=${url} | body=${serverText?.slice(0,300)}`); console.error('API error:', err); throw err; } const data = await response.json(); if (!data.success) { const errorMessage = data.error?.message || data.message || 'Erreur API'; console.error('Erreur API détectée:', errorMessage, '| endpoint=', url); throw new Error(errorMessage); } return data.data; } catch (error) { console.error('Erreur lors de l\'appel API:', error); throw error; } finally { // Fin indicateur global try { window.CRVI_LOADING && typeof window.CRVI_LOADING.end === 'function' && window.CRVI_LOADING.end(); } catch (_) {} } } export async function getEvents(params = {}) { // console.log('Appel API getEvents avec paramètres:', params); const query = new URLSearchParams(params).toString(); const endpoint = `events${query ? '?' + query : ''}`; // console.log('Endpoint appelé:', endpoint); const result = await apiFetch(endpoint); // console.log('Résultat API getEvents:', result); return result; } export async function getEvent(id) { return apiFetch(`events/${id}`); } export async function createEvent(data) { return apiFetch('events', { method: 'POST', body: JSON.stringify(data) }); } export async function updateEvent(id, data) { return apiFetch(`events/${id}`, { method: 'PUT', body: JSON.stringify(data) }); } export async function deleteEvent(id) { return apiFetch(`events/${id}`, { method: 'DELETE' }); } export async function changeEventStatus(id, status, motifAnnulation = null) { const data = { statut: status }; if (motifAnnulation) { data.motif_annulation = motifAnnulation; } return apiFetch(`events/${id}/statut`, { method: 'PUT', body: JSON.stringify(data) }); } export async function getFilters(type, params = {}) { // Gestion spéciale pour les disponibilités if (type === 'disponibilites') { const query = new URLSearchParams(params).toString(); const endpoint = `agenda/disponibilites${query ? '?' + query : ''}`; return apiFetch(endpoint); } return apiFetch(`filters/${type}`); }