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

$flash = '';
// Actions : suppression, changement de statut
if ($_SERVER['REQUEST_METHOD']==='POST' && csrf_check($_POST['csrf']??null)) {
    $id = (int)($_POST['id'] ?? 0);
    $act = $_POST['act'] ?? '';
    if ($act==='supprimer') {
        $db->prepare('DELETE FROM temoignages WHERE id=?')->execute([$id]);
        $flash = 'Témoignage supprimé.';
    } elseif ($act==='publier') {
        $db->prepare("UPDATE temoignages SET statut='publie' WHERE id=?")->execute([$id]);
        $flash = 'Témoignage publié.';
    } elseif ($act==='depublier') {
        $db->prepare("UPDATE temoignages SET statut='brouillon' WHERE id=?")->execute([$id]);
        $flash = 'Témoignage repassé en brouillon.';
    }
}

// Filtres
$q = trim($_GET['q'] ?? '');
$filtreStatut = $_GET['statut'] ?? '';
$filtreType = $_GET['type'] ?? '';
$page = max(1,(int)($_GET['p'] ?? 1));
$parPage = 30;

$where = '1=1'; $params = [];
if ($q !== '') { $where .= ' AND (t.titre LIKE ? OR t.contenu LIKE ?)'; $params[]="%$q%"; $params[]="%$q%"; }
if ($filtreStatut !== '') { $where .= ' AND t.statut = ?'; $params[]=$filtreStatut; }
if ($filtreType === 'formation') { $where .= ' AND t.est_formation = 1'; }
elseif ($filtreType === 'soin') { $where .= ' AND t.est_formation = 0'; }

$total = (function() use($db,$where,$params){ $st=$db->prepare("SELECT COUNT(*) FROM temoignages t WHERE $where"); $st->execute($params); return (int)$st->fetchColumn(); })();
$pages = (int)ceil($total/$parPage);
$offset = ($page-1)*$parPage;

$st = $db->prepare("SELECT t.id,t.titre,t.slug,t.statut,t.est_formation,t.date_pub,c.nom AS type_nom
    FROM temoignages t LEFT JOIN categories c ON c.id=t.type_soin_id
    WHERE $where ORDER BY t.date_pub DESC LIMIT $parPage OFFSET $offset");
$st->execute($params);
$rows = $st->fetchAll();

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

<div class="panel">
  <form method="get" style="display:flex;gap:.6rem;flex-wrap:wrap;align-items:center;margin-bottom:1.2rem">
    <input type="text" name="q" placeholder="Rechercher…" value="<?= e($q) ?>" style="flex:1;min-width:180px;padding:.5rem;border:1px solid var(--line);border-radius:5px">
    <select name="statut" style="padding:.5rem;border:1px solid var(--line);border-radius:5px">
      <option value="">Tous les statuts</option>
      <option value="publie" <?= $filtreStatut==='publie'?'selected':'' ?>>Publiés</option>
      <option value="brouillon" <?= $filtreStatut==='brouillon'?'selected':'' ?>>Brouillons</option>
    </select>
    <select name="type" style="padding:.5rem;border:1px solid var(--line);border-radius:5px">
      <option value="">Soins + Formations</option>
      <option value="soin" <?= $filtreType==='soin'?'selected':'' ?>>Soins uniquement</option>
      <option value="formation" <?= $filtreType==='formation'?'selected':'' ?>>Formations uniquement</option>
    </select>
    <button class="btn sm">Filtrer</button>
    <span style="color:var(--ink2);font-size:.88rem;margin-left:auto"><?= $total ?> résultat<?= $total>1?'s':'' ?></span>
  </form>

  <table>
    <tr><th>Titre</th><th>Type</th><th>Date</th><th>Statut</th><th style="text-align:right">Actions</th></tr>
    <?php foreach($rows as $r): ?>
      <tr>
        <td><a href="temoignage_edit.php?id=<?= (int)$r['id'] ?>" style="color:var(--blue)"><?= e($r['titre']) ?></a><?= $r['est_formation']?' <span class="badge draft">formation</span>':'' ?></td>
        <td style="color:var(--ink2);font-size:.85rem"><?= e($r['type_nom'] ?: '—') ?></td>
        <td style="color:var(--ink2);font-size:.85rem"><?= e(substr($r['date_pub'],0,10)) ?></td>
        <td><span class="badge <?= $r['statut']==='publie'?'pub':'draft' ?>"><?= e($r['statut']) ?></span></td>
        <td style="text-align:right;white-space:nowrap">
          <a class="btn ghost sm" href="temoignage_edit.php?id=<?= (int)$r['id'] ?>">Modifier</a>
          <form method="post" style="display:inline" onsubmit="return confirm('Confirmer ?')">
            <input type="hidden" name="csrf" value="<?= e($tok) ?>"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
            <?php if($r['statut']==='publie'): ?>
              <button class="btn ghost sm" name="act" value="depublier">Dépublier</button>
            <?php else: ?>
              <button class="btn j sm" name="act" value="publier">Publier</button>
            <?php endif; ?>
            <button class="btn r sm" name="act" value="supprimer" onclick="return confirm('Supprimer définitivement ce témoignage ?')">Suppr.</button>
          </form>
        </td>
      </tr>
    <?php endforeach; ?>
  </table>

  <?php if($pages>1): ?>
    <div class="pagination" style="margin-top:1.5rem">
      <?php $base='temoignages.php?q='.urlencode($q).'&statut='.e($filtreStatut).'&type='.e($filtreType).'&';
      for($i=1;$i<=$pages;$i++): ?>
        <a href="<?= $base ?>p=<?= $i ?>" class="<?= $i===$page?'on':'' ?>"><?= $i ?></a>
      <?php endfor; ?>
    </div>
  <?php endif; ?>
</div>
<?php layout_end(); ?>
