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

$message = '';
$edit_event = null;

// Gérer l'édition
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM association_events WHERE id = ?");
    $stmt->execute([$id]);
    $edit_event = $stmt->fetch();
}

// Ajouter ou Modifier un événement
if (isset($_POST['save_event'])) {
    $title = $_POST['title'];
    $association_id = !empty($_POST['association_id']) ? $_POST['association_id'] : null;
    $event_date = $_POST['event_date'];
    $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
    $start_time = !empty($_POST['start_time']) ? $_POST['start_time'] : null;
    $end_time = !empty($_POST['end_time']) ? $_POST['end_time'] : null;
    $location = $_POST['location'];
    $description = $_POST['description'];
    $id = $_POST['id'] ?? null;

    if ($id) {
        $stmt = $pdo->prepare("UPDATE association_events SET title=?, association_id=?, event_date=?, end_date=?, start_time=?, end_time=?, location=?, description=? WHERE id=?");
        $stmt->execute([$title, $association_id, $event_date, $end_date, $start_time, $end_time, $location, $description, $id]);
        $message = "Manifestation mise à jour avec succès.";
    } else {
        $stmt = $pdo->prepare("INSERT INTO association_events (title, association_id, event_date, end_date, start_time, end_time, location, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$title, $association_id, $event_date, $end_date, $start_time, $end_time, $location, $description]);
        $message = "Manifestation ajoutée avec succès.";
    }
    
    if (!$id) { header("Location: agenda.php?msg=" . urlencode($message)); exit; }
}

// Supprimer un événement
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM association_events WHERE id = ?");
    $stmt->execute([$id]);
    header("Location: agenda.php");
    exit;
}

if (isset($_GET['msg'])) $message = $_GET['msg'];

// Récupérer tous les événements et associations
$events = $pdo->query("SELECT ae.*, a.name as asso_name FROM association_events ae LEFT JOIN associations a ON ae.association_id = a.id ORDER BY ae.event_date DESC")->fetchAll();
$assos = $pdo->query("SELECT id, name FROM associations ORDER BY name ASC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Gestion de l'Agenda - Admin</title>
    <script src="../js/tailwind.min.js"></script>
    <script src="../js/lucide.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">
        <header class="h-20 bg-white shadow-sm flex items-center justify-between px-8 flex-shrink-0">
            <h1 class="text-2xl font-bold text-gray-800">Gestion des Manifestations</h1>
            <?php if($edit_event): ?>
                <a href="agenda.php" class="text-alsace-red hover:underline font-bold flex items-center">
                    <i data-lucide="plus-circle" class="w-5 h-5 mr-2"></i> Mode Ajout
                </a>
            <?php endif; ?>
        </header>

        <div class="flex-1 overflow-auto p-8 space-y-8">
            <?php if($message): ?>
                <div class="p-4 bg-blue-100 text-blue-700 rounded-lg shadow-sm border border-blue-200"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>

            <div class="bg-white rounded-xl shadow p-6 border border-gray-100">
                <div class="flex justify-between items-center mb-6 border-b pb-4 cursor-pointer" onclick="document.getElementById('event-form').classList.toggle('hidden'); document.getElementById('toggle-icon').classList.toggle('rotate-180');">
                    <h2 class="text-xl font-bold text-gray-800">
                        <?php echo $edit_event ? 'Modifier la manifestation : ' . htmlspecialchars($edit_event['title']) : 'Ajouter une manifestation'; ?>
                    </h2>
                    <i data-lucide="chevron-down" id="toggle-icon" class="w-6 h-6 transform transition-transform <?php echo $edit_event ? 'rotate-180' : ''; ?>"></i>
                </div>
                <form id="event-form" action="agenda.php" method="POST" class="space-y-6 <?php echo $edit_event ? '' : 'hidden'; ?>">
                    <?php if($edit_event): ?>
                        <input type="hidden" name="id" value="<?php echo $edit_event['id']; ?>">
                    <?php endif; ?>
                    
                    <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">Titre *</label>
                            <input type="text" name="title" value="<?php echo $edit_event ? htmlspecialchars($edit_event['title']) : ''; ?>" required class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Publié par *</label>
                            <select name="association_id" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                                <option value="" <?php echo (!$edit_event || $edit_event['association_id'] === null) ? 'selected' : ''; ?>>Mairie de Kutzenhausen</option>
                                <?php foreach($assos as $asso): ?>
                                    <option value="<?php echo $asso['id']; ?>" <?php echo ($edit_event && $edit_event['association_id'] == $asso['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($asso['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Date (Début) *</label>
                            <input type="date" name="event_date" value="<?php echo $edit_event ? $edit_event['event_date'] : ''; ?>" required class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Date de Fin (Optionnel)</label>
                            <input type="date" name="end_date" value="<?php echo $edit_event ? $edit_event['end_date'] : ''; ?>" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Heure de début (Optionnel)</label>
                            <input type="time" name="start_time" value="<?php echo $edit_event ? ($edit_event['start_time'] ? substr($edit_event['start_time'], 0, 5) : '') : ''; ?>" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Heure de fin (Optionnel)</label>
                            <input type="time" name="end_time" value="<?php echo $edit_event ? ($edit_event['end_time'] ? substr($edit_event['end_time'], 0, 5) : '') : ''; ?>" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div class="md:col-span-2">
                            <label class="block text-sm font-bold text-gray-700 mb-2">Lieu</label>
                            <input type="text" name="location" value="<?php echo $edit_event ? htmlspecialchars($edit_event['location']) : ''; ?>" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">Description</label>
                        <textarea name="description" rows="4" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none"><?php echo $edit_event ? htmlspecialchars($edit_event['description']) : ''; ?></textarea>
                    </div>

                    <button type="submit" name="save_event" class="bg-[#7b2c2d] text-white px-8 py-3 rounded-lg font-bold hover:bg-[#5c1a1b] transition shadow-md">
                        <?php echo $edit_event ? 'Enregistrer les modifications' : 'Ajouter la manifestation'; ?>
                    </button>
                </form>
            </div>

            <div class="bg-white rounded-xl shadow border border-gray-100 overflow-hidden">
                <table class="w-full text-left">
                    <thead class="bg-gray-50 border-b">
                        <tr>
                            <th class="p-4 font-bold text-gray-700">Date</th>
                            <th class="p-4 font-bold text-gray-700">Titre</th>
                            <th class="p-4 font-bold text-gray-700">Association</th>
                            <th class="p-4 font-bold text-gray-700">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        <?php foreach($events as $e): ?>
                        <tr class="hover:bg-gray-50 transition <?php echo ($edit_event && $edit_event['id'] == $e['id']) ? 'bg-red-50' : ''; ?>">
                            <td class="p-4 font-medium text-gray-600">
                                <?php if($e['end_date'] && $e['end_date'] !== $e['event_date']): ?>
                                    Du <?php echo date('d/m/Y', strtotime($e['event_date'])); ?> au <?php echo date('d/m/Y', strtotime($e['end_date'])); ?>
                                <?php else: ?>
                                    Le <?php echo date('d/m/Y', strtotime($e['event_date'])); ?>
                                <?php endif; ?>
                                
                                <?php if($e['start_time']): ?>
                                    <br><span class="text-sm text-gray-400">à <?php echo date('H:i', strtotime($e['start_time'])); ?><?php echo $e['end_time'] ? ' - ' . date('H:i', strtotime($e['end_time'])) : ''; ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 font-medium"><?php echo htmlspecialchars($e['title']); ?></td>
                            <td class="p-4 text-gray-600">
                                <?php if($e['association_id']): ?>
                                    <span class="px-2 py-1 bg-red-50 text-alsace-red text-xs font-bold rounded-full border border-red-100 uppercase">
                                        <?php echo htmlspecialchars($e['asso_name']); ?>
                                    </span>
                                <?php else: ?>
                                    <span class="px-2 py-1 bg-blue-50 text-blue-600 text-xs font-bold rounded-full border border-blue-100 uppercase">
                                        Mairie
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 flex items-center space-x-4 mt-2">
                                <a href="?edit=<?php echo $e['id']; ?>" class="text-[#7b2c2d] hover:text-black font-bold flex items-center">
                                    <i data-lucide="edit" class="w-4 h-4 mr-1"></i> Modifier
                                </a>
                                <a href="?delete=<?php echo $e['id']; ?>" class="text-red-600 hover:text-red-800 font-bold flex items-center" onclick="return confirm('Supprimer cet événement ?')">
                                    <i data-lucide="trash-2" class="w-4 h-4 mr-1"></i> Supprimer
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
    <script>lucide.createIcons();</script>
</body>
</html>
