<?php
require_once 'auth.php';
require_once '../config/database.php';
check_admin_login();

$id = $_GET['id'] ?? null;

// Valeurs par défaut
$title = "";
$category = "Actualités";
$content = "";
$excerpt = "";
$image = "";
$is_published = 1;
$publish_start = "";
$publish_end = "";

if ($id) {
    $stmt = $pdo->prepare("SELECT * FROM articles WHERE id = :id");
    $stmt->execute(['id' => $id]);
    $article = $stmt->fetch();
    if ($article) {
        $title = $article['title'];
        $category = $article['category'];
        $content = $article['content'];
        $excerpt = $article['excerpt'];
        $image = $article['image'];
        $is_published = $article['is_published'];
        $publish_start = $article['publish_start'];
        $publish_end = $article['publish_end'];
    } else {
        header("Location: articles.php");
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $category = $_POST['category'] ?? 'Actualités';
    $content = $_POST['content'] ?? '';
    $excerpt = $_POST['excerpt'] ?? substr(strip_tags($content), 0, 150) . '...';
    $is_published = isset($_POST['is_published']) ? 1 : 0;
    
    $publish_start = !empty($_POST['publish_start']) ? $_POST['publish_start'] : null;
    $publish_end = !empty($_POST['publish_end']) ? $_POST['publish_end'] : null;

    // Gestion de l'upload d'image
    $uploaded_image = $image;
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        $filename = $_FILES['image']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_filename = uniqid() . '.' . $ext;
            $destination = '../uploads/' . $new_filename;
            if (!is_dir('../uploads')) mkdir('../uploads', 0777, true);
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $destination)) {
                $uploaded_image = $new_filename;
            }
        }
    }

    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));

    if ($id) {
        $stmt = $pdo->prepare("UPDATE articles SET title = :title, slug = :slug, content = :content, excerpt = :excerpt, image = :image, category = :category, is_published = :is_published, publish_start = :publish_start, publish_end = :publish_end WHERE id = :id");
        $stmt->execute([
            'title' => $title, 'slug' => $slug, 'content' => $content, 'excerpt' => $excerpt, 
            'image' => $uploaded_image, 'category' => $category, 'is_published' => $is_published, 
            'publish_start' => $publish_start, 'publish_end' => $publish_end, 'id' => $id
        ]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO articles (title, slug, content, excerpt, image, category, is_published, publish_start, publish_end, author_id) VALUES (:title, :slug, :content, :excerpt, :image, :category, :is_published, :publish_start, :publish_end, :author_id)");
        $stmt->execute([
            'title' => $title, 'slug' => $slug, 'content' => $content, 'excerpt' => $excerpt, 
            'image' => $uploaded_image, 'category' => $category, 'is_published' => $is_published, 
            'publish_start' => $publish_start, 'publish_end' => $publish_end, 'author_id' => $_SESSION['admin_id'] ?? 1
        ]);
    }

    header("Location: articles.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Édition Actualité - Admin Kutzenhausen</title>
    <script src="../js/tailwind.min.js"></script>
    <script src="../js/lucide.min.js"></script>
    <link rel="stylesheet" href="../css/trumbowyg.min.css">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/trumbowyg.min.js"></script>
</head>
<body class="bg-gray-50 flex h-screen font-sans text-gray-800">

    <?php include 'includes/sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-screen overflow-hidden">
        <form action="" method="POST" enctype="multipart/form-data" class="flex flex-col h-full">
            <header class="h-20 bg-white shadow-sm flex items-center justify-between px-8 flex-shrink-0">
                <div class="flex items-center space-x-4">
                    <a href="articles.php" class="text-gray-400 hover:text-[#7b2c2d] transition"><i data-lucide="arrow-left" class="w-6 h-6"></i></a>
                    <h1 class="text-2xl font-bold text-gray-800"><?php echo $id ? "Modifier l'actualité" : "Créer une actualité"; ?></h1>
                </div>
                <div class="flex items-center space-x-3">
                    <button type="submit" class="bg-[#7b2c2d] hover:bg-[#5c1a1b] text-white px-4 py-2 rounded-md font-medium transition flex items-center shadow-sm">
                        <i data-lucide="save" class="w-5 h-5 mr-2"></i> Enregistrer
                    </button>
                </div>
            </header>
            
            <div class="flex-1 overflow-auto p-8 bg-gray-50">
                <div class="max-w-4xl mx-auto bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden p-8 space-y-6">
                    
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">Titre de l'actualité</label>
                        <input type="text" name="title" value="<?php echo htmlspecialchars($title); ?>" class="w-full text-xl font-medium border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]" required>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Catégorie</label>
                            <select name="category" class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                                <option value="Actualités" <?php if($category == 'Actualités') echo 'selected'; ?>>Actualités générales</option>
                                <option value="Événements" <?php if($category == 'Événements') echo 'selected'; ?>>Événements / Fêtes</option>
                                <option value="Flash Info" <?php if($category == 'Flash Info') echo 'selected'; ?>>Flash Info / Alerte</option>
                                <option value="Travaux" <?php if($category == 'Travaux') echo 'selected'; ?>>Travaux</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Image de couverture</label>
                            <?php if ($image): ?>
                                <p class="text-sm text-gray-500 mb-2">Image actuelle : <?php echo htmlspecialchars($image); ?></p>
                            <?php endif; ?>
                            <input type="file" name="image" accept="image/*" class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-red-50 file:text-[#7b2c2d] hover:file:bg-red-100">
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Date de début de parution</label>
                            <input type="date" name="publish_start" value="<?php echo htmlspecialchars($publish_start); ?>" class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                            <p class="text-xs text-gray-500 mt-1">Laisser vide pour publier immédiatement.</p>
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Date de fin de parution</label>
                            <input type="date" name="publish_end" value="<?php echo htmlspecialchars($publish_end); ?>" class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                            <p class="text-xs text-gray-500 mt-1">Laisser vide pour une parution permanente.</p>
                        </div>
                    </div>

                    <div>
                        <label class="flex items-center space-x-3 cursor-pointer">
                            <input type="checkbox" name="is_published" value="1" <?php if($is_published) echo 'checked'; ?> class="w-5 h-5 text-[#7b2c2d] rounded border border-gray-300 focus:ring-[#7b2c2d]">
                            <span class="text-sm font-bold text-gray-700">Publié (visible sur le site)</span>
                        </label>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">Résumé (pour l'accueil)</label>
                        <textarea name="excerpt" rows="3" class="w-full border border-gray-300 rounded-md p-4 outline-none focus:border-[#7b2c2d]"><?php echo htmlspecialchars($excerpt); ?></textarea>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">Contenu complet</label>
                        <textarea id="content" name="content" class="w-full"><?php echo htmlspecialchars($content); ?></textarea>
                    </div>

                </div>
            </div>
        </form>
    </main>

    <script>
        lucide.createIcons();
        $('#content').trumbowyg({
            lang: 'fr',
            svgPath: '../css/trumbowyg-icons.svg'
        });
    </script>
</body>
</html>
