<?php
// /admin/lyrics.php
// Backend PHP (non-framework) pour gérer les paroles.
// - Colonne gauche : formulaire "Ajouter / Mettre à jour"
// - Colonne droite : liste des entrées (clé = "artist|title")
// - Bouton "Modifier" -> remplit le formulaire de gauche
// - Bouton "Sauvegarder" (rapide) sur chaque item (facultatif)
// - Soumission AJAX vers /v6/api/lyrics.php (GET/POST gérés par ton API)
// -------------------------------------------------------------------

header('Content-Type: text/html; charset=utf-8');

// Charge le store local (si dispo). Ce n'est PAS l'API ; c'est juste pour afficher la liste.
$DATA_FILE = __DIR__ . '/../v6/data/lyrics.json';
$store = [];
if (is_file($DATA_FILE)) {
  $raw = file_get_contents($DATA_FILE);
  $j = json_decode($raw, true);
  if (is_array($j)) $store = $j;
}

// helper échappement HTML
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">
  <!-- Styles basiques (pas de dépendance) -->
  <style>
    :root{ --bg:#0f1420; --panel:#151b2b; --muted:#9aa4b2; --txt:#eef2f7; --b:#263043; --acc:#00d084; --danger:#ff4d6d; --warn:#ffb703; }
    *{ box-sizing:border-box; }
    body{ margin:0; font:14px/1.5 system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial; color:var(--txt); background:var(--bg); }
    header{ padding:18px 22px; background:#0b111c; border-bottom:1px solid #0e1523; display:flex; align-items:center; justify-content:space-between; }
    header h1{ margin:0; font-size:18px; font-weight:600; }
    main{ padding:22px; }
    .grid{ display:grid; grid-template-columns:420px 1fr; gap:22px; align-items:flex-start; }
    .card{ background:var(--panel); border:1px solid #0e1626; border-radius:14px; box-shadow:0 10px 30px rgba(0,0,0,.25); }
    .card .card-hd{ padding:14px 16px; border-bottom:1px solid #0e1626; display:flex; align-items:center; justify-content:space-between; }
    .card .card-bd{ padding:16px; }
    label{ display:block; margin:0 0 6px; color:var(--muted); font-weight:600; }
    input[type="text"], textarea, input[type="search"]{
      width:100%; background:#0f1524; color:var(--txt); border:1px solid #1b2336; border-radius:10px; padding:10px 11px; outline:none;
    }
    textarea{ min-height:140px; resize:vertical; }
    .row{ display:flex; gap:10px; align-items:center; }
    .btn{ border:0; padding:10px 12px; border-radius:10px; cursor:pointer; font-weight:600; }
    .btn-primary{ background:linear-gradient(90deg,#00b36b,#00d084); color:#052612; }
    .btn-secondary{ background:#1b2336; color:#e6ebf3; border:1px solid #263147; }
    .btn-outline{ background:transparent; color:#c6d0e3; border:1px solid #2a3550; }
    .btn-danger{ background:linear-gradient(90deg,#b3003b,#ff4d6d); color:#fff; }
    .muted{ color:var(--muted); }
    .list{ display:flex; flex-direction:column; gap:12px; max-height:70vh; overflow:auto; }
    .item{ border:1px solid #1a2236; border-radius:12px; }
    .item-hd{ display:flex; justify-content:space-between; gap:10px; align-items:center; padding:12px; }
    .item-tt{ font-weight:700; }
    .item-key{ color:var(--muted); font-size:12px; }
    .item-bd{ padding: 0 12px 12px 12px; }
    .ta-small{ min-height:120px; }
    .badget{ display:inline-block; font-size:11px; color:#09121e; background:#9ab6d8; padding:2px 7px; border-radius:999px; margin-left:8px; }
    .searchbox{ display:flex; gap:10px; align-items:center; }
    .sep{ height:1px; background:#0e1626; margin:12px 0; }
    #toast{ position:fixed; right:16px; bottom:16px; padding:10px 12px; border-radius:10px; color:#fff; z-index:99999;
            box-shadow:0 8px 18px rgba(0,0,0,.25); transition:opacity .2s; opacity:0; }
  </style>
</head>
<body>
  <header>
    <h1>GLOBAL STREAMING AFRICA — Admin Paroles</h1>
    <div class="muted">Backend FULL (non-framework) • Player v6</div>
  </header>

  <main>
    <div class="grid">
      <!-- Formulaire -->
      <section class="card">
        <div class="card-hd"><strong>Ajouter / Mettre à jour</strong></div>
        <div class="card-bd">
          <form id="lyricsForm">
            <div style="margin-bottom:10px;">
              <label>Artiste</label>
              <input type="text" name="artist" placeholder="ex: Des'ree" required>
            </div>
            <div style="margin-bottom:10px;">
              <label>Titre</label>
              <input type="text" name="title" placeholder="ex: You Gotta Be" required>
            </div>
            <div style="margin-bottom:10px;">
              <label>Paroles</label>
              <textarea name="lyrics" class="ta" placeholder="Collez les paroles…" required></textarea>
            </div>
            <p class="muted" style="margin:6px 0 12px;">La clé est calculée automatiquement : <code>artiste|titre</code> (minuscules, sans accents).</p>
            <div class="row">
              <button type="submit" class="btn btn-primary">Enregistrer</button>
              <button type="reset"  class="btn btn-outline">Vider</button>
            </div>
          </form>
        </div>
      </section>

      <!-- Liste -->
      <section class="card">
        <div class="card-hd">
          <strong>Paroles</strong>
          <div class="row searchbox">
            <input id="lyricsSearch" type="search" placeholder="Rechercher (clé / texte)…" style="max-width:320px">
            <span class="badget"><?= count($store) ?></span>
          </div>
        </div>
        <div class="card-bd">
          <div id="lyricsList" class="list">
            <?php if (!count($store)): ?>
              <div class="muted">Aucune donnée.</div>
            <?php else: ?>
              <?php foreach ($store as $key => $row):
                $a = $row['artist'] ?? '';
                $t = $row['title']  ?? '';
                $l = $row['lyrics'] ?? '';
              ?>
              <article class="item" data-key="<?= h($key) ?>">
                <div class="item-hd">
                  <div>
                    <div class="item-tt"><?= h($a) ?> <span class="muted">|</span> <?= h($t) ?></div>
                    <div class="item-key">clé : <code><?= h($key) ?></code></div>
                  </div>
                  <div class="row">
                    <!-- ✅ Bouton MODIFIER : remplit le formulaire -->
                    <button type="button"
                            class="btn btn-secondary btn-edit"
                            data-artist="<?= h($a) ?>"
                            data-title="<?= h($t) ?>"
                            data-lyrics="<?= h($l) ?>">
                      Modifier
                    </button>
                    <!-- Sauvegarde rapide (facultatif) -->
                    <button type="button"
                            class="btn btn-outline btn-save-item"
                            data-key="<?= h($key) ?>">
                      Sauvegarder
                    </button>
                    <!-- Supprimer (brancher ta route si besoin) -->
                    <button type="button"
                            class="btn btn-danger btn-delete-item"
                            data-key="<?= h($key) ?>">
                      Supprimer
                    </button>
                  </div>
                </div>
                <div class="item-bd">
                  <textarea class="ta ta-small ta-item-lyrics" placeholder="Paroles…"><?= h($l) ?></textarea>
                </div>
              </article>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
      </section>
    </div>
  </main>

  <div id="toast"></div>

  <!-- JS -->
  <script>
  (function(){
    const $ = (s,r=document)=>r.querySelector(s);
    const $$= (s,r=document)=>Array.from(r.querySelectorAll(s));

    const form = $('#lyricsForm');
    const list = $('#lyricsList');
    const search = $('#lyricsSearch');

    // Toast simple
    function toast(msg, ok=true){
      const el = $('#toast');
      el.style.background = ok ? 'linear-gradient(90deg,#00b36b,#00d084)' : 'linear-gradient(90deg,#b3003b,#ff4d6d)';
      el.textContent = msg;
      el.style.opacity = '1';
      clearTimeout(el._t);
      el._t = setTimeout(()=> el.style.opacity='0', 1800);
    }

    // Normalisation pour la clé
    const deburr = (s)=> (s||'').toString().normalize('NFD').replace(/\p{Diacritic}/gu,'').replace(/\s+/g,' ').trim().toLowerCase();
    const keyOf  = (artist,title)=> `${deburr(artist)}|${deburr(title)}`;

    // ✅ Bouton MODIFIER -> remplit le formulaire
    document.addEventListener('click', (e)=>{
      const btn = e.target.closest('.btn-edit');
      if(!btn) return;
      const A = btn.getAttribute('data-artist') || '';
      const T = btn.getAttribute('data-title')  || '';
      const L = btn.getAttribute('data-lyrics') || '';
      const fA = form.querySelector('input[name="artist"]');
      const fT = form.querySelector('input[name="title"]');
      const fL = form.querySelector('textarea[name="lyrics"]');
      if (fA) fA.value = A;
      if (fT) fT.value = T;
      if (fL) fL.value = L;
      if (fL) fL.focus();
    });

    // ✅ Submit formulaire -> /v6/api/lyrics.php (POST JSON) + toast "Enregistré"
    form && form.addEventListener('submit', async (e)=>{
      e.preventDefault();
      const A = form.querySelector('input[name="artist"]')?.value || '';
      const T = form.querySelector('input[name="title"]') ?.value || '';
      const L = form.querySelector('textarea[name="lyrics"]')?.value || '';
      if (!A || !T || !L) { toast('Champs incomplets', false); return; }

      const key = keyOf(A,T);
      const btn = form.querySelector('button[type="submit"]');
      const old = btn.innerHTML;
      btn.innerHTML = 'Enregistrement…';

      try{
        const r = await fetch('/v6/api/lyrics.php', {
          method:'POST',
          headers:{ 'Content-Type':'application/json' },
          body: JSON.stringify({ artist:A, title:T, lyrics:L, key }),
          cache:'no-store'
        });
        const j = await r.json().catch(()=> ({}));
        if (r.ok && j && j.ok){
          toast('Enregistré', true);
          // Met à jour l’item si déjà visible
          let item = list && list.querySelector(`[data-key="${key}"]`);
          if (item){
            item.querySelector('.ta-item-lyrics').value = L;
            const btnEdit = item.querySelector('.btn-edit');
            if (btnEdit){
              btnEdit.setAttribute('data-artist', A);
              btnEdit.setAttribute('data-title',  T);
              btnEdit.setAttribute('data-lyrics', L);
            }
          }
        } else {
          toast(j.message || 'Erreur lors de l’enregistrement', false);
        }
      }catch(_){
        toast('Réseau indisponible', false);
      }finally{
        btn.innerHTML = old;
      }
    });

    // Sauvegarde rapide d’un item
    document.addEventListener('click', async (e)=>{
      const btn = e.target.closest('.btn-save-item');
      if(!btn) return;
      const key = btn.getAttribute('data-key') || '';
      const item = btn.closest('.item');
      if (!key || !item) return;
      const L = item.querySelector('.ta-item-lyrics')?.value || '';

      const [artistNorm, titleNorm] = key.split('|');
      const old = btn.textContent;
      btn.textContent = 'Sauvegarde…';
      try{
        const r = await fetch('/v6/api/lyrics.php', {
          method:'POST',
          headers:{ 'Content-Type':'application/json' },
          body: JSON.stringify({ artist:artistNorm, title:titleNorm, lyrics:L, key }),
          cache:'no-store'
        });
        const j = await r.json().catch(()=> ({}));
        if (r.ok && j && j.ok) toast('Enregistré', true);
        else toast(j.message || 'Erreur', false);
      }catch(_){
        toast('Réseau indisponible', false);
      }finally{
        btn.textContent = old;
      }
    });

    // (Option) Supprimer : à brancher sur ta route serveur si besoin
    document.addEventListener('click', (e)=>{
      const btn = e.target.closest('.btn-delete-item');
      if(!btn) return;
      const key = btn.getAttribute('data-key') || '';
      if (!key) return;
      alert('À brancher : suppression serveur pour la clé : ' + key);
    });

    // Recherche client
    search && search.addEventListener('input', ()=>{
      const q = search.value.trim().toLowerCase();
      $$('.item', list).forEach(it=>{
        const key = (it.getAttribute('data-key')||'').toLowerCase();
        const txt = it.querySelector('.ta-item-lyrics')?.value.toLowerCase() || '';
        const head= it.textContent.toLowerCase();
        const show = !q || key.includes(q) || txt.includes(q) || head.includes(q);
        it.style.display = show ? '' : 'none';
      });
    });
  })();
  </script>
</body>
</html>
