<?php
require_once dirname(__DIR__) . '/inc/schema.php';
require_once __DIR__ . '/_layout.php';
init_schema();
$db = db();

// Actions valider / refuser
if ($_SERVER['REQUEST_METHOD']==='POST' && csrf_check($_POST['csrf']??null)) {
    $id = (int)($_POST['id'] ?? 0);
    $act = $_POST['act'] ?? '';
    $st = $db->prepare('SELECT * FROM temoignages_en_attente WHERE id=?');
    $st->execute([$id]); $m = $st->fetch();
    if ($m) {
        if ($act==='valider') {
            // créer un témoignage publié
            $titre = trim($_POST['titre'] ?? '') ?: 'Témoignage';
            $base = slugify($titre); $slug=$base; $n=2;
            while(true){ $c=$db->prepare('SELECT 1 FROM temoignages WHERE slug=?'); $c->execute([$slug]); if(!$c->fetchColumn()) break; $slug=$base.'-'.$n++; }
            // type de soin -> catégorie si correspond
            $typeId=null;
            if(!empty($m['type_soin'])){ $c=$db->prepare("SELECT id FROM categories WHERE nom=? AND type='type_de_soins'"); $c->execute([$m['type_soin']]); $typeId=$c->fetchColumn()?:null; }
            $contenu = '<p>'.nl2br(e($m['contenu'])).'</p>';
            $ins=$db->prepare("INSERT INTO temoignages (titre,slug,contenu,auteur,type_soin_id,statut,est_formation,date_pub) VALUES (?,?,?,?,?,'publie',0,datetime('now'))");
            $ins->execute([$titre,$slug,$contenu,$m['nom'],$typeId]);
            $db->prepare("UPDATE temoignages_en_attente SET statut='valide' WHERE id=?")->execute([$id]);
            $flash = 'Témoignage validé et publié.';
        } elseif ($act==='refuser') {
            $db->prepare("UPDATE temoignages_en_attente SET statut='refuse' WHERE id=?")->execute([$id]);
            $flash = 'Témoignage refusé.';
        } elseif ($act==='supprimer') {
            $db->prepare("DELETE FROM temoignages_en_attente WHERE id=?")->execute([$id]);
            $flash = 'Proposition supprimée.';
        }
    }
}

$enAttente = $db->query("SELECT * FROM temoignages_en_attente WHERE statut='en_attente' ORDER BY cree_le DESC")->fetchAll();
$traites = $db->query("SELECT * FROM temoignages_en_attente WHERE statut!='en_attente' ORDER BY cree_le DESC LIMIT 20")->fetchAll();

layout_start('Témoignages à modérer', 'attente');
$tok = csrf_token();
?>
<?php if (!empty($flash)): ?><div class="panel" style="border-left:3px solid var(--ok)"><?= e($flash) ?></div><?php endif; ?>

<div class="panel">
  <h2>En attente de modération (<?= count($enAttente) ?>)</h2>
  <?php if (!$enAttente): ?>
    <p style="color:var(--ink2)">Aucune proposition en attente.</p>
  <?php else: foreach ($enAttente as $m): ?>
    <div class="mod-item" style="border:1px solid var(--line);border-radius:8px;padding:1.2rem;margin-bottom:1rem">
      <div style="color:var(--ink2);font-size:.85rem;margin-bottom:.5rem">
        <?= e($m['nom'] ?: 'Anonyme') ?> <?= $m['email']?'· '.e($m['email']):'' ?>
        <?= $m['type_soin']?'· <b>'.e($m['type_soin']).'</b>':'' ?> · <?= e($m['cree_le']) ?>
      </div>
      <div style="background:#fafafa;border-radius:6px;padding:1rem;margin-bottom:.8rem;white-space:pre-wrap"><?= e($m['contenu']) ?></div>
      <form method="post" style="display:flex;gap:.6rem;align-items:center;flex-wrap:wrap">
        <input type="hidden" name="csrf" value="<?= e($tok) ?>">
        <input type="hidden" name="id" value="<?= (int)$m['id'] ?>">
        <input type="text" name="titre" placeholder="Titre du témoignage (ex. Entorse cervicale)" style="flex:1;min-width:220px;padding:.5rem;border:1px solid var(--line);border-radius:5px">
        <button class="btn j sm" name="act" value="valider" onclick="return confirm('Publier ce témoignage ?')">✓ Valider & publier</button>
        <button class="btn r sm" name="act" value="refuser">Refuser</button>
      </form>
    </div>
  <?php endforeach; endif; ?>
</div>

<?php if ($traites): ?>
<div class="panel">
  <h2>Historique récent</h2>
  <table>
    <tr><th>Date</th><th>Nom</th><th>Extrait</th><th>Statut</th><th></th></tr>
    <?php foreach ($traites as $m): ?>
      <tr>
        <td><?= e(substr($m['cree_le'],0,10)) ?></td>
        <td><?= e($m['nom'] ?: '—') ?></td>
        <td style="color:var(--ink2)"><?= e(mb_substr($m['contenu'],0,60)) ?>…</td>
        <td><span class="badge <?= $m['statut']==='valide'?'pub':'draft' ?>"><?= e($m['statut']) ?></span></td>
        <td><form method="post" onsubmit="return confirm('Supprimer définitivement ?')"><input type="hidden" name="csrf" value="<?= e($tok) ?>"><input type="hidden" name="id" value="<?= (int)$m['id'] ?>"><button class="btn ghost sm" name="act" value="supprimer">Suppr.</button></form></td>
      </tr>
    <?php endforeach; ?>
  </table>
</div>
<?php endif; ?>
<?php layout_end(); ?>
