<?php
require_once __DIR__ . '/../includes/config.php';
requireLogin();
$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRF($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';

    if ($action === 'save') {
        $titre = sanitize($_POST['titre'] ?? '');
        $contenu = sanitize($_POST['contenu'] ?? '');
        $lien = sanitize($_POST['lien'] ?? '');
        $ordre = (int)($_POST['ordre'] ?? 0);
        $actif = !empty($_POST['actif']) ? 1 : 0;
        $id = (int)($_POST['id'] ?? 0);

        $imgPath = !empty($_FILES['image']['name']) ? handleUpload('image', 'articles') : null;

        if ($id) {
            $stmt = $imgPath ?
                $db->prepare("UPDATE home_articles SET titre=?,contenu=?,lien=?,ordre=?,actif=?,image_path=? WHERE id=?") :
                $db->prepare("UPDATE home_articles SET titre=?,contenu=?,lien=?,ordre=?,actif=? WHERE id=?");
            $params = [$titre,$contenu,$lien,$ordre,$actif];
            if ($imgPath) $params[] = $imgPath;
            $params[] = $id;
            $stmt->execute($params);
        } else {
            $stmt = $db->prepare("INSERT INTO home_articles (titre,contenu,lien,ordre,actif" . ($imgPath ? ",image_path" : "") . ") VALUES (?,?,?,?,?" . ($imgPath ? ",?" : "") . ")");
            $params = [$titre,$contenu,$lien,$ordre,$actif];
            if ($imgPath) $params[] = $imgPath;
            $stmt->execute($params);
        }
        setFlash('success', 'Article sauvegardé.');
        redirect(SITE_URL . '/admin/home_articles');
    }

    if ($action === 'delete') {
        $id = (int)$_POST['id'];
        $row = $db->prepare("SELECT image_path FROM home_articles WHERE id = ?");
        $row->execute([$id]); $row = $row->fetch();
        if ($row && $row['image_path']) @unlink(__DIR__ . '/../' . $row['image_path']);
        $db->prepare("DELETE FROM home_articles WHERE id = ?")->execute([$id]);
        setFlash('success', 'Article supprimé.');
        redirect(SITE_URL . '/admin/home_articles');
    }

    if ($action === 'toggle_actif') {
        $db->prepare("UPDATE home_articles SET actif = NOT actif WHERE id = ?")->execute([(int)$_POST['id']]);
        redirect(SITE_URL . '/admin/home_articles');
    }
}

$articles = $db->query("SELECT * FROM home_articles ORDER BY ordre ASC")->fetchAll();
$editArticle = null;
if (!empty($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM home_articles WHERE id = ?");
    $stmt->execute([(int)$_GET['edit']]);
    $editArticle = $stmt->fetch();
}

$pageTitle = 'Articles Homepage'; $activeNav = 'home_articles';
include __DIR__ . '/layout.php';
?>

<div class="grid lg:grid-cols-2 gap-8">
  <!-- Form -->
  <div>
    <div class="bg-white border border-gray-200 p-8">
      <h2 class="font-serif text-xl font-light text-black mb-6">
        <?= $editArticle ? 'Modifier l\'article' : 'Nouvel article' ?>
      </h2>
      <form method="POST" enctype="multipart/form-data" class="space-y-6">
        <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
        <input type="hidden" name="action" value="save"/>
        <input type="hidden" name="id" value="<?=$editArticle['id']??0?>"/>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Titre *</label>
          <input type="text" name="titre" required value="<?=htmlspecialchars($editArticle['titre']??'')?>" class="input-underline"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Contenu / Extrait</label>
          <textarea name="contenu" rows="3" class="w-full border-b border-gray-200 focus:border-black outline-none py-2 text-sm font-sans resize-none"><?=htmlspecialchars($editArticle['contenu']??'')?></textarea>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Lien (URL)</label>
          <input type="text" name="lien" value="<?=htmlspecialchars($editArticle['lien']??'')?>" class="input-underline" placeholder="/hind/pages/articles"/>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Ordre d'affichage</label>
            <input type="number" name="ordre" value="<?=$editArticle['ordre']??0?>" class="input-underline" min="0"/>
          </div>
          <div class="flex items-center gap-3 mt-6">
            <input type="checkbox" name="actif" id="actif" value="1" <?=(!isset($editArticle)||$editArticle['actif'])?'checked':''?> class="w-4 h-4 accent-black"/>
            <label for="actif" class="text-sm font-sans">Visible en homepage</label>
          </div>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Image</label>
          <?php if (!empty($editArticle['image_path'])): ?>
          <img src="<?= htmlspecialchars(resolveAssetUrl($editArticle['image_path'])) ?>" class="w-full h-32 object-cover mb-3"/>
          <?php endif; ?>
          <input type="file" name="image" accept="image/*" class="text-sm font-sans text-gray-600 file:mr-4 file:py-2 file:px-4 file:border file:border-gray-200 file:text-xs file:font-sans file:tracking-[0.1em] file:uppercase file:cursor-pointer hover:file:border-black"/>
        </div>
        <div class="flex gap-3">
          <button type="submit" class="bg-black text-white text-xs tracking-[0.1em] uppercase px-6 py-3 font-sans hover:bg-gray-900 transition-colors">
            <?=$editArticle?'Enregistrer':'Créer l\'article'?>
          </button>
          <?php if($editArticle): ?>
          <a href="home_articles" class="border border-gray-200 text-xs tracking-[0.1em] uppercase px-6 py-3 font-sans hover:bg-gray-50 transition-colors text-gray-600">Annuler</a>
          <?php endif; ?>
        </div>
      </form>
    </div>
  </div>

  <!-- List -->
  <div class="bg-white border border-gray-200">
    <div class="p-5 border-b border-gray-100"><h2 class="font-serif text-lg font-light text-black">Articles ({<?=count($articles)?>})</h2></div>
    <div class="divide-y divide-gray-50">
      <?php if(empty($articles)): ?>
      <p class="p-6 text-sm text-gray-400 font-sans text-center">Aucun article.</p>
      <?php endif; ?>
      <?php foreach($articles as $art): ?>
      <div class="flex gap-4 p-4 hover:bg-gray-50 transition-colors">
        <?php if($art['image_path']): ?>
        <img src="<?= htmlspecialchars(resolveAssetUrl($art['image_path'])) ?>" class="w-14 h-14 object-cover flex-shrink-0 rounded-xs"/>
        <?php else: ?><div class="w-14 h-14 bg-gray-100 flex-shrink-0"></div><?php endif; ?>
        <div class="flex-1 min-w-0">
          <p class="text-sm font-medium text-black font-sans line-clamp-1"><?=htmlspecialchars($art['titre'])?></p>
          <p class="text-xs text-gray-400 font-sans mt-0.5 line-clamp-1"><?=htmlspecialchars($art['contenu']??'')?></p>
        </div>
        <div class="flex flex-col items-end gap-1.5 flex-shrink-0">
          <span class="text-[9px] tracking-[0.1em] uppercase px-2 py-0.5 <?=$art['actif']?'bg-black text-white':'border border-gray-200 text-gray-400'?>">
            <?=$art['actif']?'Actif':'Masqué'?>
          </span>
          <div class="flex gap-2">
            <a href="?edit=<?=$art['id']?>" class="text-[11px] text-gray-400 hover:text-black">Modifier</a>
            <form method="POST" class="inline">
              <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
              <input type="hidden" name="action" value="delete"/>
              <input type="hidden" name="id" value="<?=$art['id']?>"/>
              <button type="submit" class="text-[11px] text-red-400 hover:text-red-600" onclick="return confirm('Supprimer?')">Suppr.</button>
            </form>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<?php include __DIR__ . '/layout_footer.php'; ?>
