<?php
include 'db.php';

$message = '';
$error = '';
$article = [
    'id' => '',
    'title' => '',
    'content' => '',
    'author' => '',
    'excerpt' => '',
    'category' => '',
    'status' => 'published'
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'create' || $action === 'update') {
        $id = $_POST['id'] ?? '';
        $title = trim($_POST['title'] ?? '');
        $content = trim($_POST['content'] ?? '');
        $author = trim($_POST['author'] ?? '');
        $excerpt = trim($_POST['excerpt'] ?? '');
        $category = trim($_POST['category'] ?? '');
        $status = $_POST['status'] ?? 'published';
        
        if (empty($title)) {
            $error = 'Le titre est obligatoire';
        } elseif (empty($content)) {
            $error = 'Le contenu est obligatoire';
        } elseif (empty($author)) {
            $error = 'L\'auteur est obligatoire';
        } else {
            if ($action === 'create') {
                $date = date('Y-m-d H:i:s');
                
                $stmt = mysqli_prepare($conn, "INSERT INTO articles (title, content, date_publication, author, excerpt, category, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
                mysqli_stmt_bind_param($stmt, 'sssssss', $title, $content, $date, $author, $excerpt, $category, $status);
                
                if (mysqli_stmt_execute($stmt)) {
                    $message = 'Article créé avec succès';
                    $article = [
                        'id' => '',
                        'title' => '',
                        'content' => '',
                        'author' => '',
                        'excerpt' => '',
                        'category' => '',
                        'status' => 'published'
                    ];
                } else {
                    $error = 'Erreur lors de la création de l\'article: ' . mysqli_error($conn);
                }
                
                mysqli_stmt_close($stmt);
            } elseif ($action === 'update') {
                $stmt = mysqli_prepare($conn, "UPDATE articles SET title = ?, content = ?, author = ?, excerpt = ?, category = ?, status = ? WHERE id = ?");
                mysqli_stmt_bind_param($stmt, 'ssssssi', $title, $content, $author, $excerpt, $category, $status, $id);
                
                if (mysqli_stmt_execute($stmt)) {
                    $message = 'Article mis à jour avec succès';
                } else {
                    $error = 'Erreur lors de la mise à jour de l\'article: ' . mysqli_error($conn);
                }
                
                mysqli_stmt_close($stmt);
            }
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? '';
        
        if (!empty($id)) {
            $stmt = mysqli_prepare($conn, "DELETE FROM articles WHERE id = ?");
            mysqli_stmt_bind_param($stmt, 'i', $id);
            
            if (mysqli_stmt_execute($stmt)) {
                $message = 'Article supprimé avec succès';
                $article = [
                    'id' => '',
                    'title' => '',
                    'content' => '',
                    'author' => '',
                    'excerpt' => '',
                    'category' => '',
                    'status' => 'published'
                ];
            } else {
                $error = 'Erreur lors de la suppression de l\'article: ' . mysqli_error($conn);
            }
            
            mysqli_stmt_close($stmt);
        }
    } elseif ($action === 'edit') {
        $id = $_POST['id'] ?? '';
        
        if (!empty($id)) {
            $result = mysqli_query($conn, "SELECT * FROM articles WHERE id = $id");
            
            if ($result && mysqli_num_rows($result) > 0) {
                $article = mysqli_fetch_assoc($result);
            } else {
                $error = 'Article non trouvé';
            }
        }
    }
}

$articles = mysqli_query($conn, "SELECT id, title, DATE_FORMAT(date_publication, '%d/%m/%Y %H:%i') as formatted_date, status FROM articles ORDER BY date_publication DESC");
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Articles - Vert Chasseur</title>
    <link rel="icon" type="image/png" href="logo_new.png">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #fafafa;
        }
    </style>
</head>
<body class="bg-white text-gray-800">
    <div class="container mx-auto px-4 py-8 max-w-5xl">
        <div class="flex justify-between items-center mb-8">
            <h1 class="text-xl font-medium">Gestion des Articles</h1>
            <div>
                <a href="../media" class="px-3 py-1.5 bg-gray-50 rounded text-sm font-medium hover:bg-gray-100 mr-2 inline-flex items-center">
                    <i class="fas fa-newspaper mr-1.5 text-gray-500"></i>Voir les actualités
                </a>
                <a href="/" class="px-3 py-1.5 bg-gray-50 rounded text-sm font-medium hover:bg-gray-100 inline-flex items-center">
                    <i class="fas fa-home mr-1.5 text-gray-500"></i>Accueil
                </a>
            </div>
        </div>

        <?php if (!empty($message)): ?>
        <div class="mb-5 bg-green-50 text-green-700 px-3 py-2 rounded text-sm">
            <?= $message ?>
        </div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
        <div class="mb-5 bg-red-50 text-red-700 px-3 py-2 rounded text-sm">
            <?= $error ?>
        </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div class="lg:col-span-1">
                <div class="bg-white p-5 rounded-lg shadow-sm border border-gray-100">
                    <h2 class="text-lg font-medium mb-4"><?= empty($article['id']) ? 'Créer un article' : 'Modifier l\'article' ?></h2>
                    
                    <form method="post" action="">
                        <input type="hidden" name="action" value="<?= empty($article['id']) ? 'create' : 'update' ?>">
                        <input type="hidden" name="id" value="<?= $article['id'] ?? '' ?>">
                        
                        <div class="mb-3">
                            <label for="title" class="block text-sm text-gray-600 mb-1">Titre</label>
                            <input type="text" id="title" name="title" value="<?= htmlspecialchars($article['title'] ?? '') ?>" class="w-full px-3 py-2 rounded border border-gray-200 focus:outline-none focus:border-blue-400 text-sm">
                        </div>
                        
                        <div class="mb-3">
                            <label for="author" class="block text-sm text-gray-600 mb-1">Auteur</label>
                            <input type="text" id="author" name="author" value="<?= htmlspecialchars($article['author'] ?? '') ?>" class="w-full px-3 py-2 rounded border border-gray-200 focus:outline-none focus:border-blue-400 text-sm">
                        </div>
                        
                        <div class="mb-3">
                            <label for="category" class="block text-sm text-gray-600 mb-1">Catégorie</label>
                            <input type="text" id="category" name="category" value="<?= htmlspecialchars($article['category'] ?? '') ?>" class="w-full px-3 py-2 rounded border border-gray-200 focus:outline-none focus:border-blue-400 text-sm">
                        </div>
                        
                        <div class="mb-3">
                            <label for="excerpt" class="block text-sm text-gray-600 mb-1">Extrait (optionnel)</label>
                            <textarea id="excerpt" name="excerpt" rows="2" class="w-full px-3 py-2 rounded border border-gray-200 focus:outline-none focus:border-blue-400 text-sm"><?= htmlspecialchars($article['excerpt'] ?? '') ?></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="content" class="block text-sm text-gray-600 mb-1">Contenu</label>
                            <textarea id="content" name="content" rows="8" class="w-full px-3 py-2 rounded border border-gray-200 focus:outline-none focus:border-blue-400 text-sm"><?= htmlspecialchars($article['content'] ?? '') ?></textarea>
                        </div>
                        
                        <div class="mb-4">
                            <label for="status" class="block text-sm text-gray-600 mb-1">Statut</label>
                            <select id="status" name="status" class="w-full px-3 py-2 rounded border border-gray-200 focus:outline-none focus:border-blue-400 text-sm">
                                <option value="published" <?= ($article['status'] ?? '') === 'published' ? 'selected' : '' ?>>Publié</option>
                                <option value="draft" <?= ($article['status'] ?? '') === 'draft' ? 'selected' : '' ?>>Brouillon</option>
                            </select>
                        </div>
                        
                        <div class="flex justify-between">
                            <button type="submit" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded text-sm">
                                <?= empty($article['id']) ? 'Créer l\'article' : 'Mettre à jour' ?>
                            </button>
                            
                            <?php if (!empty($article['id'])): ?>
                            <button type="button" class="px-4 py-2 bg-gray-100 text-gray-600 rounded text-sm hover:bg-gray-200" onclick="resetForm()">
                                Annuler
                            </button>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="lg:col-span-2">
                <div class="bg-white p-5 rounded-lg shadow-sm border border-gray-100">
                    <h2 class="text-lg font-medium mb-4">Liste des articles</h2>
                    
                    <?php if (mysqli_num_rows($articles) > 0): ?>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="border-b border-gray-100">
                                    <th class="py-2 px-2 text-left text-sm font-medium text-gray-500">Titre</th>
                                    <th class="py-2 px-2 text-left text-sm font-medium text-gray-500">Date</th>
                                    <th class="py-2 px-2 text-left text-sm font-medium text-gray-500">Statut</th>
                                    <th class="py-2 px-2 text-right text-sm font-medium text-gray-500">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($row = mysqli_fetch_assoc($articles)): ?>
                                <tr class="border-b border-gray-50 hover:bg-gray-50">
                                    <td class="py-2 px-2 text-sm"><?= htmlspecialchars($row['title']) ?></td>
                                    <td class="py-2 px-2 text-sm text-gray-500"><?= $row['formatted_date'] ?></td>
                                    <td class="py-2 px-2 text-sm">
                                        <?php if ($row['status'] === 'published'): ?>
                                        <span class="px-2 py-0.5 bg-green-50 text-green-600 rounded-full text-xs">Publié</span>
                                        <?php else: ?>
                                        <span class="px-2 py-0.5 bg-yellow-50 text-yellow-600 rounded-full text-xs">Brouillon</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="py-2 px-2 text-right text-sm">
                                        <form method="post" action="" class="inline-block mr-1">
                                            <input type="hidden" name="action" value="edit">
                                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                            <button type="submit" class="text-blue-500 hover:text-blue-700">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                        </form>
                                        
                                        <form method="post" action="" class="inline-block" onsubmit="return confirm('Êtes-vous sûr de vouloir supprimer cet article ?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                            <button type="submit" class="text-red-500 hover:text-red-700">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                        
                                        <a href="article.php?id=<?= $row['id'] ?>" class="inline-block ml-1 text-gray-500 hover:text-gray-700" target="_blank">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <div class="text-center py-4 text-gray-400 text-sm">
                        Aucun article trouvé. Crée ton premier article!
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        function resetForm() {
            window.location.href = window.location.pathname;
        }
    </script>
</body>
</html>