<?php
// admin/_galeries_ui.php - UI partagee galeries (grille) / sliders (bandeau).
require_once __DIR__ . '/_layout.php';
$TYPE = $TYPE ?? 'gal';
$estSlider = $TYPE === 'slider';
$titre = $estSlider ? 'Sliders' : 'Galeries';
$actif = $estSlider ? 'slides' : 'galeries';
$motSing = $estSlider ? 'slider' : 'galerie';
$exemple = $estSlider ? '[slider:nom]' : '[galerie:nom]';
layout_start($titre, $actif);
?>
<div class="panel">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:1rem;flex-wrap:wrap">
    <h2 style="margin:0"><?= $titre ?></h2>
    <div style="display:flex;gap:.5rem">
      <input type="text" id="newNom" placeholder="Nom du nouveau <?= $motSing ?>" style="padding:.5rem .7rem;border:1px solid var(--line);border-radius:6px">
      <button class="btn" id="btnCreate">+ Creer</button>
    </div>
  </div>
  <p style="color:var(--ink2);margin:.6rem 0 0">
    Pour afficher un <?= $motSing ?> dans une page, copiez son code (ex. <code><?= $exemple ?></code>)
    et collez-le dans une zone de texte de la page voulue. Tant qu'il est vide, il reste invisible pour les visiteurs.
  </p>
  <div id="liste" class="gx-liste"></div>
</div>
<div class="zpick" id="gmodal" aria-hidden="true">
  <div class="zpick-box" style="max-width:900px">
    <div class="zpick-head"><b id="gmTitre">Images</b><button type="button" class="zpick-close" id="gmClose">&times;</button></div>
    <div style="padding:1rem 1.2rem">
      <div style="margin-bottom:.5rem;color:var(--ink2);font-size:.9rem">Glissez pour reordonner, cliquez la croix pour retirer.</div>
      <div id="gmItems" class="gx-items"></div>
      <hr style="margin:1rem 0;border:0;border-top:1px solid var(--line)">
      <div style="font-weight:600;margin-bottom:.5rem">Ajouter depuis la mediatheque</div>
      <div id="gmPool" class="gx-pool"></div>
    </div>
  </div>
</div>
<style>
.gx-liste{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:1rem;margin-top:1rem}
.gx-card{border:1px solid var(--line);border-radius:10px;overflow:hidden;background:#fff}
.gx-card .thumb{aspect-ratio:16/10;background:#0001;overflow:hidden}
.gx-card .thumb img{width:100%;height:100%;object-fit:cover}
.gx-card .thumb.vide{display:flex;align-items:center;justify-content:center;color:#aaa;font-style:italic;font-size:.85rem}
.gx-card .body{padding:.7rem .8rem}
.gx-card .nm{font-weight:600}
.gx-card .code{font-family:monospace;font-size:.8rem;color:var(--gold);cursor:pointer;margin-top:.2rem}
.gx-card .acts{display:flex;gap:.4rem;margin-top:.6rem;flex-wrap:wrap}
.gx-card .acts button{font-size:.8rem;padding:.35rem .6rem;border:1px solid var(--line);background:#fff;border-radius:5px;cursor:pointer}
.gx-card .acts .open{background:var(--gold);color:#fff;border-color:var(--gold)}
.gx-items{display:flex;flex-wrap:wrap;gap:.6rem;min-height:60px}
.gx-items .it{position:relative;width:110px;height:84px;border-radius:8px;overflow:hidden;border:2px solid transparent;cursor:grab;background:#0001}
.gx-items .it.drag{opacity:.4}
.gx-items .it img{width:100%;height:100%;object-fit:cover}
.gx-items .it .x{position:absolute;top:2px;right:2px;width:20px;height:20px;border:0;border-radius:50%;background:rgba(0,0,0,.6);color:#fff;cursor:pointer;font-size:.8rem;line-height:1}
.gx-pool{display:grid;grid-template-columns:repeat(auto-fill,minmax(90px,1fr));gap:.5rem;max-height:240px;overflow:auto;padding:.3rem;border:1px solid var(--line);border-radius:8px}
.gx-pool .p{aspect-ratio:1;border-radius:6px;overflow:hidden;cursor:pointer;border:2px solid transparent;position:relative}
.gx-pool .p img{width:100%;height:100%;object-fit:cover}
.gx-pool .p.in{border-color:var(--gold)}
.gx-pool .p.in::after{content:"\2713";position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(176,141,87,.45);color:#fff;font-size:1.4rem}
</style>
<script>
const TYPE='<?= $TYPE ?>';
const EP='galerie_action.php';
const liste=document.getElementById('liste');
let curGid=null, inIds=new Set();

function api(action,opts){ return fetch(EP+'?action='+action,Object.assign({credentials:'same-origin'},opts||{})).then(r=>r.json()); }
function post(action,data){ const fd=new FormData(); fd.append('action',action); Object.keys(data).forEach(k=>fd.append(k,data[k])); return fetch(EP,{method:'POST',body:fd,credentials:'same-origin'}).then(r=>r.json()); }

function loadListe(){
  api('list_galeries&type='+TYPE).then(rows=>{
    liste.innerHTML='';
    if(!rows.length){ liste.innerHTML='<p style="color:#888">Aucun element pour l\'instant. Creez-en un ci-dessus.</p>'; return; }
    rows.forEach(g=>{
      const d=document.createElement('div'); d.className='gx-card';
      d.innerHTML='<div class="thumb'+(g.vignette?'':' vide')+'">'+(g.vignette?'<img src="../'+g.vignette+'">':'vide')+'</div>'+
        '<div class="body"><div class="nm">'+g.nom+'</div>'+
        '<div class="code" title="Copier le code">'+g.code+'</div>'+
        '<div style="font-size:.8rem;color:#888">'+g.n+' image(s)</div>'+
        '<div class="acts"><button class="open" data-id="'+g.id+'" data-nom="'+g.nom+'">Gerer les images</button>'+
        '<button class="ren" data-id="'+g.id+'" data-nom="'+g.nom+'">Renommer</button>'+
        '<button class="del" data-id="'+g.id+'">Suppr.</button></div></div>';
      liste.appendChild(d);
    });
    liste.querySelectorAll('.code').forEach(c=>c.addEventListener('click',()=>{if(navigator.clipboard)navigator.clipboard.writeText(c.textContent);c.textContent='copie !';setTimeout(loadListe,900);}));
    liste.querySelectorAll('.open').forEach(b=>b.addEventListener('click',()=>openModal(b.dataset.id,b.dataset.nom)));
    liste.querySelectorAll('.ren').forEach(b=>b.addEventListener('click',()=>{const n=prompt('Nouveau nom :',b.dataset.nom);if(n&&n.trim())post('rename',{id:b.dataset.id,nom:n.trim()}).then(loadListe);}));
    liste.querySelectorAll('.del').forEach(b=>b.addEventListener('click',()=>{if(confirm('Supprimer ? Les images restent dans la mediatheque.'))post('delete',{id:b.dataset.id}).then(loadListe);}));
  });
}
document.getElementById('btnCreate').addEventListener('click',()=>{
  const nom=document.getElementById('newNom').value.trim(); if(!nom)return;
  post('create',{nom:nom,type:TYPE}).then(d=>{ if(d.ok){document.getElementById('newNom').value='';loadListe();} else alert(d.error||'Erreur'); });
});
const modal=document.getElementById('gmodal');
const gmItems=document.getElementById('gmItems');
const gmPool=document.getElementById('gmPool');

function openModal(gid,nom){ curGid=gid; document.getElementById('gmTitre').textContent='Images - '+nom; modal.classList.add('on'); refresh(); }
function closeModal(){ modal.classList.remove('on'); curGid=null; loadListe(); }
document.getElementById('gmClose').addEventListener('click',closeModal);
modal.addEventListener('click',e=>{ if(e.target===modal) closeModal(); });

function refresh(){
  api('galerie&id='+curGid).then(d=>{
    if(!d.ok)return;
    inIds=new Set(d.medias.map(m=>String(m.id)));
    gmItems.innerHTML='';
    d.medias.forEach(m=>{
      const it=document.createElement('div'); it.className='it'; it.draggable=true; it.dataset.id=m.id;
      it.innerHTML='<img src="../'+m.url+'"><button class="x" title="Retirer">\u2715</button>';
      it.querySelector('.x').addEventListener('click',()=>post('remove_media',{galerie_id:curGid,media_id:m.id}).then(refresh));
      gmItems.appendChild(it);
    });
    enableDrag(); loadPool();
  });
}
function loadPool(){
  api('mediatheque').then(rows=>{
    gmPool.innerHTML='';
    rows.forEach(m=>{
      const p=document.createElement('div'); p.className='p'+(inIds.has(String(m.id))?' in':''); p.dataset.id=m.id;
      p.innerHTML='<img src="../'+m.url+'">';
      p.addEventListener('click',()=>{
        if(inIds.has(String(m.id))) post('remove_media',{galerie_id:curGid,media_id:m.id}).then(refresh);
        else post('add_media',{galerie_id:curGid,media_id:m.id}).then(refresh);
      });
      gmPool.appendChild(p);
    });
  });
}
function enableDrag(){
  let dragEl=null;
  gmItems.querySelectorAll('.it').forEach(it=>{
    it.addEventListener('dragstart',()=>{dragEl=it;it.classList.add('drag');});
    it.addEventListener('dragend',()=>{it.classList.remove('drag');saveOrder();});
    it.addEventListener('dragover',e=>{e.preventDefault();const a=[...gmItems.children];const after=a.indexOf(it)>a.indexOf(dragEl);gmItems.insertBefore(dragEl,after?it.nextSibling:it);});
  });
}
function saveOrder(){
  const ordre=[...gmItems.querySelectorAll('.it')].map(x=>x.dataset.id);
  post('reorder',{galerie_id:curGid,ordre:JSON.stringify(ordre)});
}
loadListe();
</script>
<?php layout_end(); ?>
