<?php
// /admin-radio/lyrics.php
// Gestion simple des paroles (lecture/édition) alignée sur l’API /v6/api/lyrics.php
// - Liste avec Modifier / Sauvegarder / Supprimer
// - Formulaire à gauche remplit par "Modifier"
// - Sauvegarde => POST JSON vers /v6/api/lyrics.php (message "Succès")
// - Suppression locale ici (met à jour /v6/data/lyrics.json)

declare(strict_types=1);
header('X-Frame-Options: SAMEORIGIN');
$JSON_FILE = $_SERVER['DOCUMENT_ROOT'].'/v6/data/lyrics.json';

/* --- suppression locale (POST) --- */
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && ($_POST['action'] ?? '') === 'delete') {
  $key = trim((string)($_POST['key'] ?? ''));
  $store = is_file($JSON_FILE) ? json_decode(@file_get_contents($JSON_FILE), true) : [];
  if (!is_array($store)) $store = [];
  if ($key !== '' && isset($store[$key])) {
    unset($store[$key]);
    @file_put_contents($JSON_FILE, json_encode($store, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok'=>true]);
    exit;
  }
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode(['ok'=>false]);
  exit;
}

/* --- lecture --- */
$store = is_file($JSON_FILE) ? json_decode(@file_get_contents($JSON_FILE), true) : [];
if (!is_array($store)) $store = [];

/* utilitaires */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Admin Paroles — Player v6</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
  :root{--bg:#0f1220;--card:#151a2d;--muted:#9aa4b2;--txt:#e6ebf1;--accent:#20c997;--danger:#ff6b6b}
  html,body{margin:0;padding:0;background:var(--bg);color:var(--txt);font:14px/1.45 Inter,system-ui,Segoe UI,Roboto,Arial}
  .wrap{display:grid;grid-template-columns:360px 1fr;gap:18px;padding:22px}
  .card{background:var(--card);border-radius:14px;box-shadow:0 8px 24px rgba(0,0,0,.25)}
  .card .hd{padding:14px 16px;border-bottom:1px solid rgba(255,255,255,.06);font-weight:600}
  .card .bd{padding:14px 16px}
  label{display:block;margin:8px 0 6px;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.04em}
  input[type=text],textarea{width:100%;background:#0e1324;border:1px solid transparent;color:var(--txt);
    padding:10px 12px;border-radius:10px;outline:none}
  textarea{min-height:120px;resize:vertical}
  .row{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}
  .btn{appearance:none;border:0;border-radius:10px;padding:10px 14px;font-weight:600;cursor:pointer}
  .btn-primary{background:var(--accent);color:#093b2f}
  .btn-ghost{background:#0e1324;color:var(--txt)}
  .btn-danger{background:var(--danger);color:#3b0b0b}
  .grid{display:grid;gap:12px}
  .item{background:#0e1324;border:1px solid rgba(255,255,255,.06);border-radius:12px}
  .item .k{padding:10px 12px;border-bottom:1px solid rgba(255,255,255,.06);color:var(--muted);font-size:12px}
  .item .k b{color:var(--txt);font-weight:600}
  .item .bd{padding:10px 12px}
  .item .actions{display:flex;gap:8px;padding:10px 12px;border-top:1px solid rgba(255,255,255,.06)}
  .note{position:fixed;left:16px;bottom:16px;background:#000b;color:#fff;padding:10px 12px;border-radius:12px;box-shadow:0 8px 20px #0008;opacity:0;transform:translateY(10px);transition:.2s}
  .note.show{opacity:1;transform:translateY(0)}
  .topbar{padding:10px 16px;border-bottom:1px solid rgba(255,255,255,.06);display:flex;justify-content:space-between;align-items:center}
  .search{width:280px}
  @media (max-width:980px){.wrap{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="topbar">
  <div><b>GLOBAL STREAMING AFRICA</b> — Admin Paroles</div>
  <input id="q" class="search" type="text" placeholder="Rechercher (clé, artiste ou texte)…">
</div>

<div class="wrap">
  <!-- colonne gauche : formulaire -->
  <div class="card">
    <div class="hd">Ajouter / Mettre à jour</div>
    <div class="bd">
      <form id="f">
        <input type="hidden" name="key" id="f_key" value="">
        <label>Artiste</label>
        <input type="text" name="artist" id="f_artist" placeholder="ex: Des'ree" required>
        <label>Titre</label>
        <input type="text" name="title" id="f_title" placeholder="ex: You Gotta Be" required>
        <label>Paroles</label>
        <textarea name="lyrics" id="f_lyrics" placeholder="Collez les paroles…"></textarea>
        <div class="row">
          <button class="btn btn-primary" type="submit">Enregistrer</button>
          <button class="btn btn-ghost" type="button" id="btnReset">Vider</button>
        </div>
        <p style="margin-top:8px;color:var(--muted);font-size:12px">La clé est calculée automatiquement : <code>artiste|titre</code> (minuscules, sans accents).</p>
      </form>
    </div>
  </div>

  <!-- colonne droite : liste -->
  <div class="card">
    <div class="hd">Paroles (<?= count($store) ?>)</div>
    <div class="bd">
      <div id="list" class="grid">
        <?php foreach ($store as $k => $row):
          $artist = $row['artist'] ?? ''; $title = $row['title'] ?? ''; $lyrics = $row['lyrics'] ?? ''; ?>
          <div class="item" data-key="<?= h($k) ?>" data-artist="<?= h($artist) ?>" data-title="<?= h($title) ?>">
            <div class="k">clé: <b><?= h($k) ?></b></div>
            <div class="bd">
              <textarea class="ta" spellcheck="false"><?= h($lyrics) ?></textarea>
            </div>
            <div class="actions">
              <button class="btn btn-ghost btn-edit"   type="button">Modifier</button>
              <button class="btn btn-primary btn-save" type="button">Sauvegarder</button>
              <button class="btn btn-danger btn-del"   type="button">Supprimer</button>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</div>

<div id="note" class="note"></div>

<script>
  const $ = (s, r=document)=>r.querySelector(s);
  const $$ = (s, r=document)=>Array.from(r.querySelectorAll(s));
  const note = (m)=>{ const n=$("#note"); n.textContent=m; n.classList.add("show"); clearTimeout(n._t); n._t=setTimeout(()=>n.classList.remove("show"),1800); };

  // Remplir le formulaire depuis un item
  function fillForm(item){
    const k = item.getAttribute('data-key')||'';
    const a = item.getAttribute('data-artist')||'';
    const t = item.getAttribute('data-title')||'';
    const l = item.querySelector('.ta')?.value || '';
    $('#f_key').value = k;
    $('#f_artist').value = a;
    $('#f_title').value  = t;
    $('#f_lyrics').value = l;
    window.scrollTo({top:0,behavior:'smooth'});
  }

  // Sauvegarde via l'API centrale
  async function saveEntry({artist,title,lyrics,key}){
    const body = JSON.stringify({artist,title,lyrics,key});
    const r = await fetch('/v6/api/lyrics.php', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body, cache:'no-store'
    });
    const j = await r.json().catch(()=>({}));
    if (j && j.ok) { note('Succès — paroles enregistrées'); return true; }
    note('Erreur — impossible d’enregistrer'); return false;
  }

  // Handlers
  $('#f').addEventListener('submit', async (e)=>{
    e.preventDefault();
    const artist = $('#f_artist').value.trim();
    const title  = $('#f_title').value.trim();
    const lyrics = $('#f_lyrics').value;
    const key    = $('#f_key').value.trim(); // optionnel
    const ok = await saveEntry({artist,title,lyrics,key});
    if (ok) location.reload();
  });

  $('#btnReset').addEventListener('click', ()=>{
    $('#f_key').value=''; $('#f_artist').value=''; $('#f_title').value=''; $('#f_lyrics').value='';
  });

  // bouton Modifier / Sauvegarder / Supprimer dans la liste
  $$('.item').forEach(it=>{
    it.querySelector('.btn-edit').addEventListener('click', ()=> fillForm(it));

    it.querySelector('.btn-save').addEventListener('click', async ()=>{
      const artist = it.getAttribute('data-artist')||'';
      const title  = it.getAttribute('data-title')||'';
      const key    = it.getAttribute('data-key')||'';
      const lyrics = it.querySelector('.ta').value;
      const ok = await saveEntry({artist,title,lyrics,key});
      if (ok) note('Sauvegardé'); 
    });

    it.querySelector('.btn-del').addEventListener('click', async ()=>{
      if (!confirm('Supprimer ces paroles ?')) return;
      const key = it.getAttribute('data-key')||'';
      const fd = new FormData(); fd.append('action','delete'); fd.append('key',key);
      const r = await fetch(location.href, { method:'POST', body:fd });
      const j = await r.json().catch(()=>({}));
      if (j && j.ok) { note('Supprimé'); it.remove(); } else { note('Erreur suppression'); }
    });
  });

  // Recherche instantanée
  $('#q').addEventListener('input', (e)=>{
    const q = (e.target.value||'').toLowerCase();
    $$('.item').forEach(it=>{
      const k = (it.getAttribute('data-key')||'').toLowerCase();
      const a = (it.getAttribute('data-artist')||'').toLowerCase();
      const t = (it.getAttribute('data-title')||'').toLowerCase();
      const l = (it.querySelector('.ta')?.value||'').toLowerCase();
      const show = k.includes(q)||a.includes(q)||t.includes(q)||l.includes(q);
      it.style.display = show ? '' : 'none';
    });
  });
  
  
  
  
  
  
  <script>
  const $ = (s, r=document)=>r.querySelector(s);
  const $$ = (s, r=document)=>Array.from(r.querySelectorAll(s));
  const note = (m)=>{ const n=$("#note"); n.textContent=m; n.classList.add("show"); clearTimeout(n._t); n._t=setTimeout(()=>n.classList.remove("show"),1800); };

  // --- Normalisation identique à l'API ---
  function deburr(s){
    s = (s||'').toString().normalize('NFD').replace(/\p{Diacritic}/gu,'');
    s = s.replace(/[^A-Za-z0-9|\-\s_]/g,' ').replace(/\s+/g,' ').trim().toLowerCase();
    return s;
  }
  function mkKey(a,t){ return `${deburr(a)}|${deburr(t)}`; }

  // Remplir le formulaire depuis un item
  function fillForm(item){
    const k = item.getAttribute('data-key')||'';
    const a = item.getAttribute('data-artist')||'';
    const t = item.getAttribute('data-title')||'';
    const l = item.querySelector('.ta')?.value || '';
    $('#f_key').value = k || mkKey(a,t);   // clé visible et modifiable si besoin
    $('#f_artist').value = a;
    $('#f_title').value  = t;
    $('#f_lyrics').value = l;
    window.scrollTo({top:0,behavior:'smooth'});
  }

  // Calcul auto de la clé en tapant Artiste/Titre
  ['f_artist','f_title'].forEach(id=>{
    $('#'+id).addEventListener('input', ()=>{
      $('#f_key').value = mkKey($('#f_artist').value, $('#f_title').value);
    });
  });

  // Sauvegarde via l'API centrale
  async function saveEntry({artist,title,lyrics,key}){
    // clé prioritaire = champ visible, sinon calculée
    const finalKey = key && key.trim() ? deburr(key) : mkKey(artist,title);
    const body = JSON.stringify({artist,title,lyrics,key: finalKey});
    const r = await fetch('/v6/api/lyrics.php', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body, cache:'no-store'
    });
    const j = await r.json().catch(()=>({}));
    if (j && j.ok) { note('Succès — paroles enregistrées'); return true; }
    note('Erreur — impossible d’enregistrer'); return false;
  }

  // Formulaire gauche
  $('#f').addEventListener('submit', async (e)=>{
    e.preventDefault();
    const artist = $('#f_artist').value.trim();
    const title  = $('#f_title').value.trim();
    const lyrics = $('#f_lyrics').value;
    const key    = $('#f_key').value.trim();
    const ok = await saveEntry({artist,title,lyrics,key});
    if (ok) location.reload();
  });

  $('#btnReset').addEventListener('click', ()=>{
    $('#f_key').value=''; $('#f_artist').value=''; $('#f_title').value=''; $('#f_lyrics').value='';
  });

  // Liste : Modifier / Sauvegarder / Supprimer
  $$('.item').forEach(it=>{
    it.querySelector('.btn-edit').addEventListener('click', ()=> fillForm(it));

    it.querySelector('.btn-save').addEventListener('click', async ()=>{
      const artist = it.getAttribute('data-artist')||'';
      const title  = it.getAttribute('data-title')||'';
      const key    = it.getAttribute('data-key')||'';
      const lyrics = it.querySelector('.ta').value;
      const ok = await saveEntry({artist,title,lyrics,key});
      if (ok) note('Sauvegardé');
    });

    it.querySelector('.btn-del').addEventListener('click', async ()=>{
      if (!confirm('Supprimer ces paroles ?')) return;
      const key = it.getAttribute('data-key')||'';
      const fd = new FormData(); fd.append('action','delete'); fd.append('key', key);
      const r = await fetch(location.href, { method:'POST', body:fd });
      const j = await r.json().catch(()=>({}));
      if (j && j.ok) { note('Supprimé'); it.remove(); } else { note('Erreur suppression'); }
    });
  });

  // Recherche instantanée
  $('#q').addEventListener('input', (e)=>{
    const q = (e.target.value||'').toLowerCase();
    $$('.item').forEach(it=>{
      const k = (it.getAttribute('data-key')||'').toLowerCase();
      const a = (it.getAttribute('data-artist')||'').toLowerCase();
      const t = (it.getAttribute('data-title')||'').toLowerCase();
      const l = (it.querySelector('.ta')?.value||'').toLowerCase();
      it.style.display = (k.includes(q)||a.includes(q)||t.includes(q)||l.includes(q)) ? '' : 'none';
    });
  });
</script>

  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
</script>
</body>
</html>
