<?php
require_once __DIR__ . '/../includes/config.php';
requireLogin();

$db = getDB();
$message = '';
$error = '';

// 1. Handle Form Actions: Create / Edit / Delete / Toggle Status
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save') {
        $id       = (int)($_POST['id'] ?? 0);
        $title    = trim($_POST['title'] ?? '');
        $category = trim($_POST['category'] ?? 'Marché Immobilier');
        $author   = trim($_POST['author'] ?? 'Équipe AJOUAMAI');
        $excerpt  = trim($_POST['excerpt'] ?? '');
        $content  = trim($_POST['content'] ?? '');
        $featured = isset($_POST['featured']) ? 1 : 0;
        $status   = $_POST['status'] ?? 'publie';

        // Generate slug
        $slug = slugify($title);
        if (empty($slug)) $slug = 'article-' . time();

        // Handle Image Upload or text path
        $imgPath = null;
        if (!empty($_FILES['image']['name'])) {
            $imgPath = handleUpload('image', 'articles');
        } elseif (!empty($_POST['image_path_custom'])) {
            $imgPath = trim($_POST['image_path_custom']);
        }

        if (empty($title)) {
            $error = "Le titre de l'article est obligatoire.";
        } else {
            try {
                if ($id > 0) {
                    if ($imgPath) {
                        $stmt = $db->prepare("UPDATE articles SET title=?, slug=?, category=?, author=?, excerpt=?, content=?, featured=?, status=?, image_path=? WHERE id=?");
                        $stmt->execute([$title, $slug, $category, $author, $excerpt, $content, $featured, $status, $imgPath, $id]);
                    } else {
                        $stmt = $db->prepare("UPDATE articles SET title=?, slug=?, category=?, author=?, excerpt=?, content=?, featured=?, status=? WHERE id=?");
                        $stmt->execute([$title, $slug, $category, $author, $excerpt, $content, $featured, $status, $id]);
                    }
                    $message = "Article mis à jour avec succès.";
                } else {
                    $imgPath = $imgPath ?: 'assets/img/project-1.jpg';
                    $stmt = $db->prepare("INSERT INTO articles (title, slug, category, author, excerpt, content, featured, status, image_path) VALUES (?,?,?,?,?,?,?,?,?)");
                    $stmt->execute([$title, $slug, $category, $author, $excerpt, $content, $featured, $status, $imgPath]);
                    $message = "Nouvel article publié avec succès.";
                }
            } catch (Exception $e) {
                $error = "Erreur lors de l'enregistrement : " . $e->getMessage();
            }
        }
    } elseif ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $db->prepare("DELETE FROM articles WHERE id = ?")->execute([$id]);
            $message = "Article supprimé.";
        }
    } elseif ($action === 'toggle_featured') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $db->prepare("UPDATE articles SET featured = NOT featured WHERE id = ?")->execute([$id]);
            $message = "Statut 'À la une' mis à jour.";
        }
    }
}

// 2. Fetch Item for Edit Mode if requested
$editArticle = null;
if (isset($_GET['edit'])) {
    $editId = (int)$_GET['edit'];
    $stmt = $db->prepare("SELECT * FROM articles WHERE id = ?");
    $stmt->execute([$editId]);
    $editArticle = $stmt->fetch();
}

// 3. Fetch All Articles
$articles = $db->query("SELECT * FROM articles ORDER BY id DESC")->fetchAll();

$pageTitle = 'Gestion du Journal & Articles';
$activeNav = 'articles';

include __DIR__ . '/layout.php';
?>

<!-- Header Toolbar -->
<div class="mb-8 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
  <div>
    <h1 class="text-2xl font-bold text-white tracking-tight font-serif">Journal & Articles (<?= count($articles) ?>)</h1>
    <p class="text-xs text-slate-400 mt-1">Gérez les actualités, analyses de marché et publications du blog d'actualités.</p>
  </div>
  <div>
    <a href="<?= SITE_URL ?>/admin/articles" class="bg-amber-500 hover:bg-amber-400 text-slate-950 font-semibold px-4 py-2.5 rounded-lg text-xs transition-colors inline-flex items-center gap-2 shadow-lg shadow-amber-500/10">
      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.5v15m7.5-7.5h-15"/></svg>
      Nouvel Article
    </a>
  </div>
</div>

<?php if ($message): ?>
  <div class="mb-6 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 px-4 py-3 rounded-lg text-xs flex items-center gap-2">
    <span>✓</span> <?= htmlspecialchars($message) ?>
  </div>
<?php endif; ?>

<?php if ($error): ?>
  <div class="mb-6 bg-rose-500/10 border border-rose-500/30 text-rose-400 px-4 py-3 rounded-lg text-xs flex items-center gap-2">
    <span>⚠️</span> <?= htmlspecialchars($error) ?>
  </div>
<?php endif; ?>

<!-- Edit / Create Form Block -->
<div class="bg-slate-900 border border-slate-800 rounded-xl p-6 mb-10 shadow-xl">
  <h2 class="text-base font-semibold text-white mb-6 flex items-center gap-2">
    <span class="w-2 h-2 rounded-full bg-amber-500"></span>
    <?= $editArticle ? 'Éditer l\'article #' . $editArticle['id'] : 'Publier un nouvel article' ?>
  </h2>

  <form method="POST" enctype="multipart/form-data" class="space-y-6">
    <input type="hidden" name="action" value="save">
    <input type="hidden" name="id" value="<?= $editArticle['id'] ?? 0 ?>">

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
      <div>
        <label class="block text-xs text-slate-400 mb-2 font-medium uppercase tracking-wider">Titre de l'article *</label>
        <input type="text" name="title" required value="<?= htmlspecialchars($editArticle['title'] ?? '') ?>" class="w-full bg-slate-950 border border-slate-800 text-white rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-amber-500 transition-colors" placeholder="ex: Analyse du marché immobilier à Sidi Rahal">
      </div>

      <div>
        <label class="block text-xs text-slate-400 mb-2 font-medium uppercase tracking-wider">Catégorie</label>
        <select name="category" class="w-full bg-slate-950 border border-slate-800 text-white rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-amber-500 transition-colors">
          <?php 
          $categories = ['Marché Immobilier', 'Conseils & Guide', 'Investissement', 'Architecture & Design', 'Juridique & Patrimoine', 'Art de Vivre'];
          $curCat = $editArticle['category'] ?? 'Marché Immobilier';
          foreach($categories as $cat): ?>
            <option value="<?= htmlspecialchars($cat) ?>" <?= $curCat === $cat ? 'selected' : '' ?>><?= htmlspecialchars($cat) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label class="block text-xs text-slate-400 mb-2 font-medium uppercase tracking-wider">Auteur</label>
        <input type="text" name="author" value="<?= htmlspecialchars($editArticle['author'] ?? 'Équipe AJOUAMAI') ?>" class="w-full bg-slate-950 border border-slate-800 text-white rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-amber-500 transition-colors">
      </div>

      <div>
        <label class="block text-xs text-slate-400 mb-2 font-medium uppercase tracking-wider">Statut</label>
        <select name="status" class="w-full bg-slate-950 border border-slate-800 text-white rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-amber-500 transition-colors">
          <option value="publie" <?= ($editArticle['status'] ?? 'publie') === 'publie' ? 'selected' : '' ?>>Publié</option>
          <option value="brouillon" <?= ($editArticle['status'] ?? '') === 'brouillon' ? 'selected' : '' ?>>Brouillon</option>
        </select>
      </div>
    </div>

    <!-- Image Selection -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
      <div>
        <label class="block text-xs text-slate-400 mb-2 font-medium uppercase tracking-wider">Téléverser une image de couverture</label>
        <input type="file" name="image" accept="image/*" class="w-full text-xs text-slate-400 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-slate-800 file:text-white hover:file:bg-slate-700 cursor-pointer">
      </div>

      <div>
        <label class="block text-xs text-slate-400 mb-2 font-medium uppercase tracking-wider">ou Chemin de l'image (assets/img/...)</label>
        <input type="text" name="image_path_custom" value="<?= htmlspecialchars($editArticle['image_path'] ?? '') ?>" class="w-full bg-slate-950 border border-slate-800 text-white rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-amber-500 transition-colors" placeholder="assets/img/project-1.jpg">
      </div>
    </div>

    <div>
      <label class="block text-xs text-slate-400 mb-2 font-medium uppercase tracking-wider">Extrait / Chapô (court résumé)</label>
      <textarea name="excerpt" rows="2" class="w-full bg-slate-950 border border-slate-800 text-white rounded-lg p-4 text-sm focus:outline-none focus:border-amber-500 transition-colors"><?= htmlspecialchars($editArticle['excerpt'] ?? '') ?></textarea>
    </div>

    <div>
      <label class="block text-xs text-slate-400 mb-2 font-medium uppercase tracking-wider">Contenu complet de l'article (HTML autorisé)</label>
      <textarea name="content" rows="8" class="w-full bg-slate-950 border border-slate-800 text-white rounded-lg p-4 text-sm focus:outline-none focus:border-amber-500 transition-colors font-mono text-xs"><?= htmlspecialchars($editArticle['content'] ?? '') ?></textarea>
    </div>

    <div class="flex items-center gap-6">
      <label class="inline-flex items-center gap-2 cursor-pointer">
        <input type="checkbox" name="featured" value="1" <?= !empty($editArticle['featured']) ? 'checked' : '' ?> class="w-4 h-4 rounded bg-slate-950 border-slate-800 text-amber-500 focus:ring-0">
        <span class="text-xs text-slate-300">Mettre en avant dans le Carrousel Hero Slider</span>
      </label>
    </div>

    <div class="flex items-center gap-4 pt-4 border-t border-slate-800">
      <button type="submit" class="bg-amber-500 hover:bg-amber-400 text-slate-950 font-bold px-6 py-2.5 rounded-lg text-xs transition-colors">
        <?= $editArticle ? 'Enregistrer les modifications' : 'Publier l\'article' ?>
      </button>
      <?php if ($editArticle): ?>
        <a href="<?= SITE_URL ?>/admin/articles" class="text-xs text-slate-400 hover:text-white transition-colors">Annuler</a>
      <?php endif; ?>
    </div>
  </form>
</div>

<!-- Articles List Table -->
<div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-xl">
  <div class="p-5 border-b border-slate-800 flex items-center justify-between">
    <h3 class="text-sm font-semibold text-white">Liste des articles publiés (<?= count($articles) ?>)</h3>
  </div>

  <div class="overflow-x-auto">
    <table class="w-full text-left text-xs text-slate-300">
      <thead class="bg-slate-950 text-slate-400 uppercase tracking-wider border-b border-slate-800 font-semibold">
        <tr>
          <th class="p-4">Image</th>
          <th class="p-4">Titre & Catégorie</th>
          <th class="p-4">Auteur</th>
          <th class="p-4">Hero Slider</th>
          <th class="p-4">Statut</th>
          <th class="p-4 text-right">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-800">
        <?php foreach ($articles as $art): 
          $imgUrl = resolveAssetUrl($art['image_path'] ?? 'assets/img/project-1.jpg');
        ?>
          <tr class="hover:bg-slate-800/50 transition-colors">
            <td class="p-4">
              <img src="<?= htmlspecialchars($imgUrl) ?>" class="w-14 h-10 object-cover rounded-md border border-slate-700" alt="">
            </td>
            <td class="p-4">
              <a href="<?= SITE_URL ?>/pages/article.php?slug=<?= htmlspecialchars($art['slug']) ?>" target="_blank" class="font-medium text-white hover:text-amber-400 transition-colors line-clamp-1">
                <?= htmlspecialchars($art['title']) ?>
              </a>
              <span class="text-[10px] text-amber-500 font-semibold tracking-wider uppercase block mt-1">
                <?= htmlspecialchars($art['category']) ?>
              </span>
            </td>
            <td class="p-4 text-slate-400">
              <?= htmlspecialchars($art['author'] ?? 'Équipe AJOUAMAI') ?>
            </td>
            <td class="p-4">
              <form method="POST" class="inline">
                <input type="hidden" name="action" value="toggle_featured">
                <input type="hidden" name="id" value="<?= $art['id'] ?>">
                <button type="submit" class="px-2.5 py-1 rounded text-[10px] font-semibold transition-colors <?= !empty($art['featured']) ? 'bg-amber-500/20 text-amber-300 border border-amber-500/30' : 'bg-slate-800 text-slate-400 hover:text-white' ?>">
                  <?= !empty($art['featured']) ? '★ En Vedette' : 'Standard' ?>
                </button>
              </form>
            </td>
            <td class="p-4">
              <span class="px-2 py-0.5 rounded-full text-[10px] font-medium <?= ($art['status'] ?? 'publie') === 'publie' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-slate-800 text-slate-400' ?>">
                <?= ucfirst($art['status'] ?? 'publie') ?>
              </span>
            </td>
            <td class="p-4 text-right space-x-2">
              <a href="<?= SITE_URL ?>/admin/articles?edit=<?= $art['id'] ?>" class="text-amber-400 hover:text-amber-300 font-medium text-xs">Éditer</a>
              <form method="POST" class="inline" onsubmit="return confirm('Voulez-vous vraiment supprimer cet article ?');">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $art['id'] ?>">
                <button type="submit" class="text-rose-400 hover:text-rose-300 font-medium text-xs">Supprimer</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

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