<?php
require_once dirname(__DIR__) . '/inc/schema.php';
require_once __DIR__ . '/_layout.php';
init_schema();
layout_start('Médiathèque', 'medias');
?>
<div class="panel">
  <div class="media-toolbar">
    <div id="mdrop">
      <div class="big">Glisser-déposer des images, ou <kbd>Ctrl</kbd>+<kbd>V</kbd> pour coller</div>
      <div class="small">converties en WebP optimisé — ou cliquez pour choisir un fichier</div>
      <input type="file" id="mfile" accept="image/*" multiple hidden>
    </div>
  </div>
  <div id="mstatus"></div>
  <div class="mgrid" id="mgrid"></div>
</div>

<script>
const drop=document.getElementById('mdrop'),file=document.getElementById('mfile'),
      st=document.getElementById('mstatus'),grid=document.getElementById('mgrid');
drop.addEventListener('click',()=>file.click());
file.addEventListener('change',()=>{for(const f of file.files)send(f);});
['dragenter','dragover'].forEach(e=>drop.addEventListener(e,ev=>{ev.preventDefault();drop.classList.add('over');}));
['dragleave','drop'].forEach(e=>drop.addEventListener(e,ev=>{ev.preventDefault();drop.classList.remove('over');}));
drop.addEventListener('drop',e=>{for(const f of e.dataTransfer.files)if(f.type.startsWith('image/'))send(f);});
window.addEventListener('paste',e=>{for(const it of e.clipboardData.items)if(it.type.startsWith('image/')){const f=it.getAsFile();if(f)send(f);}});

function setSt(m,c){st.textContent=m;st.className=c||'';}
function endpoint(q){
  // chemin relatif, mais on force le protocole de la barre d'adresse (https) pour éviter le mixed-content
  var origin = location.protocol + '//' + location.host;
  return origin + location.pathname.replace(/[^/]*$/, '') + 'media_action.php' + (q||'');
}
function send(f){
  setSt('Envoi de '+(f.name||'image collée')+'…');
  const fd=new FormData();fd.append('action','upload');fd.append('file',f,f.name||'collee.png');
  fetch(endpoint(),{method:'POST',body:fd,credentials:'same-origin'})
    .then(r=>{ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
    .then(d=>{
      if(d.ok){setSt('✓ '+d.name+' ('+d.w+'×'+d.h+')','ok');load();}
      else setSt('✗ '+(d.error||'Erreur'),'err');
    })
    .catch(e=>setSt('✗ Envoi impossible : '+e.message+' — '+endpoint(),'err'));
}
function copyText(t,btn){
  const done=()=>{btn.textContent='✓';btn.classList.add('copied');setTimeout(()=>{btn.textContent='Copier';btn.classList.remove('copied');},1200);};
  if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(t).then(done).catch(()=>fb(t,done));}else fb(t,done);
}
function fb(t,done){const ta=document.createElement('textarea');ta.value=t;ta.style.position='fixed';ta.style.opacity='0';
  document.body.appendChild(ta);ta.select();try{document.execCommand('copy');done();}catch(e){prompt('Copier :',t);}document.body.removeChild(ta);}
function del(id,btn){
  if(!confirm('Supprimer cette image ?'))return;
  const fd=new FormData();fd.append('action','delete');fd.append('id',id);
  fetch(endpoint(),{method:'POST',body:fd,credentials:'same-origin'}).then(r=>{if(!r.ok)throw new Error('HTTP '+r.status);return r.json();}).then(d=>{if(d.ok)load();else alert(d.error||'Erreur');}).catch(e=>alert('Suppression impossible : '+e.message));
}
function load(){
  fetch(endpoint('?action=list'),{credentials:'same-origin'}).then(r=>{if(!r.ok)throw new Error('HTTP '+r.status);return r.json();}).then(list=>{
    grid.innerHTML='';
    if(!list.length){grid.innerHTML='<p style="color:#888">Aucune image. Envoyez-en une ci-dessus.</p>';return;}
    for(const it of list){
      const d=document.createElement('div');d.className='mitem';
      d.innerHTML=`<div class="imgwrap"><img src="../${it.url}" loading="lazy"></div>
        <div class="meta"><div class="nm">${it.full}</div>
        <div class="acts"><button data-u="${it.full}">Copier</button>
        <button class="del" data-id="${it.id}">Suppr.</button></div></div>`;
      grid.appendChild(d);
    }
    grid.querySelectorAll('.acts button:not(.del)').forEach(b=>b.addEventListener('click',()=>copyText(b.dataset.u,b)));
    grid.querySelectorAll('.del').forEach(b=>b.addEventListener('click',()=>del(b.dataset.id,b)));
  }).catch(e=>{ grid.innerHTML='<p style="color:#c0392b">Chargement impossible : '+e.message+'</p>'; });
}
load();
</script>
<?php layout_end(); ?>
