let state={guests:[],dates:[],votes:[]};const $=id=>document.getElementById(id);const form=$('guest-form'); async function refresh(){state=await api('/api/admin/state');render()} function render(){let g=state.guests,confirmed=g.filter(x=>x.status==='Confirmé');$('metrics').innerHTML=[['Invités enregistrés',g.length],['Personnes confirmées',confirmed.reduce((s,x)=>s+x.party_size,0)],['En attente',g.filter(x=>x.status==='En attente').length],['Services représentés',new Set(confirmed.map(x=>x.service)).size]].map(([k,v])=>`
${k}${v}
`).join('');renderGuests();renderDates()} function renderGuests(){let search=$('search').value.toLowerCase(),filter=$('filter').value;let data=state.guests.filter(g=>(g.name+' '+g.service).toLowerCase().includes(search)&&(!filter||g.status===filter));$('guest-table').innerHTML=data.map(g=>`${escapeHtml(g.name)}${escapeHtml(g.service)}${escapeHtml(g.status)}${g.party_size}${escapeHtml(g.contribution)}${escapeHtml(g.dietary)||"—"}`).join('')||'Aucun invité pour le moment.'} window.editGuest=id=>{let g=state.guests.find(x=>x.id===id);for(let key of ['id','name','service','status','contribution','dietary','notes'])form.elements[key].value=g[key];form.elements.participants.value=g.party_size;$('edit-title').textContent='Modifier un invité';form.scrollIntoView({behavior:'smooth'})}; window.removeGuest=async id=>{if(!confirm('Supprimer cet invité et ses votes ?'))return;try{await api('/api/admin/guests/'+id,{method:'DELETE'});await refresh()}catch(e){alert(e.message)}}; function resetForm(){form.reset();form.elements.id.value='';$('edit-title').textContent='Ajouter un invité'}$('reset-form').onclick=resetForm; form.onsubmit=async e=>{e.preventDefault();let d=Object.fromEntries(new FormData(form));const id=d.id;delete d.id;d.party_size=Number(d.participants);delete d.participants;try{await api(id?'/api/admin/guests/'+id:'/api/admin/guests',{method:id?'PUT':'POST',body:JSON.stringify(d)});resetForm();await refresh();$('guest-msg').textContent='Invité enregistré.'}catch(e){$('guest-msg').textContent=e.message}}; $('search').oninput=renderGuests;$('filter').onchange=renderGuests; function renderDates(){const counts={};for(let v of state.votes){counts[v.date_id]??={Oui:0,'Peut-être':0,Non:0};counts[v.date_id][v.choice]++} $('date-admin-list').innerHTML=state.dates.map(d=>`
${escapeHtml(formatDay(d.day))} · ${escapeHtml(d.time)}${counts[d.id]?.Oui||0} oui · ${counts[d.id]?.['Peut-être']||0} peut-être · ${counts[d.id]?.Non||0} non
`).join('');$('matrix').innerHTML=`CollègueService${state.dates.map(d=>`${escapeHtml(d.day.slice(5))}`).join('')}${state.guests.map(g=>`${escapeHtml(g.name)}${escapeHtml(g.service)}${state.dates.map(d=>{let v=state.votes.find(x=>x.guest_id===g.id&&x.date_id===d.id)?.choice||'—';return `${escapeHtml(v)}`}).join('')}`).join('')}`} window.removeDate=async id=>{if(!confirm('Supprimer cette date et tous les votes associés ?'))return;try{await api('/api/admin/dates/'+id,{method:'DELETE'});await refresh()}catch(e){alert(e.message)}}; $('date-form').onsubmit=async e=>{e.preventDefault();let d=Object.fromEntries(new FormData(e.target));try{await api('/api/admin/dates',{method:'POST',body:JSON.stringify(d)});e.target.reset();await refresh();$('date-msg').textContent='Date ajoutée.'}catch(e){$('date-msg').textContent=e.message}}; for(let tab of document.querySelectorAll('.tab'))tab.onclick=()=>{for(let el of document.querySelectorAll('.tab'))el.classList.toggle('active',el===tab);for(let el of document.querySelectorAll('.tab-content'))el.classList.toggle('hidden',el.id!==tab.dataset.tab)}; // Admin-only shopping list let shoppingItems=[]; async function refreshShopping(){let r=await api('/api/admin/shopping');shoppingItems=r.items;renderShopping()} function renderShopping(){const total=shoppingItems.length,done=shoppingItems.filter(i=>i.purchased).length; $('shopping-metrics').innerHTML=[['Articles',total],['Achetés',done],['À acheter',total-done]].map(([label,n])=>`
${label}${n}
`).join(''); $('shopping-table').innerHTML=shoppingItems.map(i=>`${escapeHtml(i.label)}${escapeHtml(i.quantity)}${escapeHtml(i.category)}`).join('')||'Aucun article. Ajoute les premiers achats à prévoir.'} window.toggleShopping=async(id,checked)=>{const i=shoppingItems.find(x=>x.id===id);try{await api('/api/admin/shopping/'+id,{method:'PUT',body:JSON.stringify({...i,purchased:checked})});await refreshShopping()}catch(e){alert(e.message);await refreshShopping()}}; window.editShopping=id=>{const i=shoppingItems.find(x=>x.id===id),f=$('shopping-form');for(const key of ['id','label','quantity','category'])f.elements[key].value=i[key];$('shopping-submit').textContent='Enregistrer les modifications';f.scrollIntoView({behavior:'smooth'})}; window.removeShopping=async id=>{if(!confirm('Supprimer cet article ?'))return;try{await api('/api/admin/shopping/'+id,{method:'DELETE'});await refreshShopping()}catch(e){alert(e.message)}}; function resetShopping(){let f=$('shopping-form');f.reset();f.elements.id.value='';$('shopping-submit').textContent='Ajouter à la liste'} $('shopping-reset').onclick=resetShopping; $('shopping-form').onsubmit=async e=>{e.preventDefault();const d=Object.fromEntries(new FormData(e.target)),id=d.id;delete d.id;try{await api(id?'/api/admin/shopping/'+id:'/api/admin/shopping',{method:id?'PUT':'POST',body:JSON.stringify(d)});resetShopping();await refreshShopping();$('shopping-msg').textContent='Liste des courses mise à jour.'}catch(e){$('shopping-msg').textContent=e.message}}; refreshShopping().catch(e=>$('shopping-msg').textContent=e.message); $('logout').onclick=async()=>{await api('/api/logout',{method:'POST'});location.href='/admin/login'};refresh().catch(e=>alert(e.message));