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

$flash = '';

// Actions : créer, supprimer, publier/dépublier
if ($_SERVER['REQUEST_METHOD']==='POST' && csrf_check($_POST['csrf']??null)) {
    $act = $_POST['act'] ?? '';
    if ($act==='creer') {
        $titre = trim($_POST['titre'] ?? '');
        if ($titre !== '') {
            // slug unique
            $base = slugify($titre);
            $slug = $base; $i = 2;
            while ($db->query("SELECT 1 FROM articles WHERE slug=" . $db->quote($slug))->fetchColumn()) {
                $slug = $base . '-' . $i; $i++;
            }
            $db->prepare("INSERT INTO articles (titre,slug,extrait,contenu,statut,cree_le,modifie_le)
                VALUES (?,?,'','','brouillon',datetime('now'),datetime('now'))")->execute([$titre,$slug]);
            $newId = $db->lastInsertId();
            header('Location: article_edit.php?id=' . $newId); exit;
        }
        $flash = 'Indiquez un titre.';
    } elseif ($act==='supprimer') {
        $db->prepare('DELETE FROM articles WHERE id=?')->execute([(int)($_POST['id']??0)]);
        $flash = 'Article supprimé.';
    } elseif ($act==='publier') {
        $db->prepare("UPDATE articles SET statut='publie' WHERE id=?")->execute([(int)($_POST['id']??0)]);
        $flash = 'Article publié.';
    } elseif ($act==='depublier') {
        $db->prepare("UPDATE articles SET statut='brouillon' WHERE id=?")->execute([(int)($_POST['id']??0)]);
        $flash = 'Article repassé en brouillon.';
    }
}

$articles = $db->query("SELECT a.*, c.nom AS cat_nom
    FROM articles a LEFT JOIN categories c ON c.id=a.categorie_id
    ORDER BY a.cree_le DESC")->fetchAll();

layout_start('Articles', 'articles');
$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="post" style="display:flex;gap:.8rem;align-items:flex-end;flex-wrap:wrap">
    <input type="hidden" name="csrf" value="<?= e($tok) ?>">
    <input type="hidden" name="act" value="creer">
    <label style="flex:1;min-width:260px">
      <span style="display:block;font-size:.82rem;color:var(--ink2);margin-bottom:.3rem">Titre du nouvel article</span>
      <input type="text" name="titre" placeholder="Ex. : Le Qigong au quotidien" style="width:100%;padding:.6rem;border:1px solid var(--line);border-radius:5px;font-size:1rem">
    </label>
    <button class="btn">+ Créer l'article</button>
  </form>
</div>

<div class="panel">
  <?php if (!$articles): ?>
    <p style="color:var(--ink2)">Aucun article pour le moment. Créez-en un ci-dessus.</p>
  <?php else: ?>
    <table>
      <tr><th>Titre</th><th>Catégorie</th><th>Statut</th><th>Créé le</th><th style="text-align:right">Actions</th></tr>
      <?php foreach($articles as $a): ?>
        <tr>
          <td><a href="article_edit.php?id=<?= (int)$a['id'] ?>" style="color:var(--blue);font-weight:500"><?= e($a['titre']) ?></a></td>
          <td><?= e($a['cat_nom'] ?? '—') ?></td>
          <td>
            <?php if($a['statut']==='publie'): ?>
              <span style="color:var(--ok)">● Publié</span>
            <?php else: ?>
              <span style="color:var(--ink2)">○ Brouillon</span>
            <?php endif; ?>
          </td>
          <td style="color:var(--ink2);font-size:.85rem"><?= e(date('d/m/Y', strtotime($a['cree_le']))) ?></td>
          <td style="text-align:right;white-space:nowrap">
            <a href="article_edit.php?id=<?= (int)$a['id'] ?>" class="btn ghost sm">Modifier</a>
            <form method="post" style="display:inline" onsubmit="return confirm('Supprimer cet article ?')">
              <input type="hidden" name="csrf" value="<?= e($tok) ?>">
              <input type="hidden" name="act" value="supprimer">
              <input type="hidden" name="id" value="<?= (int)$a['id'] ?>">
              <button class="btn ghost sm" style="color:var(--err)">Supprimer</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
    </table>
  <?php endif; ?>
</div>
<?php layout_end(); ?>
