<?php
require_once 'config/database.php';

$stmt = $pdo->query("
    SELECT ae.*, a.name as asso_name 
    FROM association_events ae
    LEFT JOIN associations a ON ae.association_id = a.id
    WHERE (ae.end_date >= CURDATE() OR (ae.end_date IS NULL AND ae.event_date >= CURDATE()))
    ORDER BY ae.event_date ASC
");
$events = $stmt->fetchAll();

// Préparer les données pour FullCalendar
$calendar_events = [];
foreach($events as $event) {
    $start = $event['event_date'];
    if($event['start_time']) {
        $start .= 'T' . $event['start_time'];
    }
    
    $author_name = $event['asso_name'] ?: 'Mairie';
    $event_data = [
        'title' => $event['title'] . ' (' . $author_name . ')',
        'start' => $start,
        'description' => $event['description'],
        'location' => $event['location']
    ];

    // Gérer la fin de l'événement (date et heure)
    if ($event['end_date'] || $event['end_time']) {
        $endDate = $event['end_date'] ?: $event['event_date'];
        $end = $endDate;
        if ($event['end_time']) {
            $end .= 'T' . $event['end_time'];
        } elseif (!$event['start_time']) {
            // Si pas d'heure du tout (all-day), FullCalendar exclut le jour de fin, donc +1 jour
            $d = new DateTime($endDate);
            $d->modify('+1 day');
            $end = $d->format('Y-m-d');
        }
        $event_data['end'] = $end;
    }

    $calendar_events[] = $event_data;
}

include 'includes/header.php';
?>

<!-- FullCalendar CSS/JS -->
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js'></script>

<main class="min-h-screen py-16 bg-alsace-cream">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex flex-col md:flex-row justify-between items-center mb-12 border-b-2 border-alsace-red pb-4">
            <h2 class="font-serif text-3xl md:text-4xl font-bold text-alsace-red">
                Agenda des Manifestations
            </h2>
            
            <!-- Toggle View Buttons -->
            <div class="flex mt-4 md:mt-0 space-x-2 bg-white rounded-lg shadow-sm border border-gray-200 p-1">
                <button id="btn-list-view" class="px-4 py-2 text-sm font-bold rounded-md bg-alsace-red text-white flex items-center transition">
                    <i data-lucide="list" class="w-4 h-4 mr-2"></i> Liste
                </button>
                <button id="btn-cal-view" class="px-4 py-2 text-sm font-bold rounded-md text-gray-600 hover:bg-gray-100 flex items-center transition">
                    <i data-lucide="calendar" class="w-4 h-4 mr-2"></i> Calendrier
                </button>
            </div>
        </div>

        <?php if(empty($events)): ?>
            <div class="bg-white rounded-2xl shadow-md p-12 text-center border border-gray-100">
                <i data-lucide="calendar-off" class="w-16 h-16 text-gray-300 mx-auto mb-4"></i>
                <p class="text-gray-500 text-lg italic">Aucune manifestation n'est programmée pour le moment.</p>
            </div>
        <?php else: ?>
            
            <!-- LIST VIEW -->
            <div id="list-view" class="grid grid-cols-1 gap-8">
                <?php foreach($events as $event): ?>
                <div class="bg-white rounded-2xl shadow-md overflow-hidden border border-gray-100 hover:shadow-xl transition flex flex-col md:flex-row">
                    <!-- Date Badge -->
                    <div class="bg-alsace-red text-white p-6 md:w-48 flex flex-col items-center justify-center text-center shrink-0">
                        <?php if($event['end_date'] && $event['end_date'] !== $event['event_date']): ?>
                            <span class="text-xs uppercase font-bold tracking-widest opacity-80 mb-1">Du</span>
                            <span class="text-2xl font-black mb-2"><?php echo date('d/m/Y', strtotime($event['event_date'])); ?></span>
                            <span class="text-xs uppercase font-bold tracking-widest opacity-80 mb-1">Au</span>
                            <span class="text-2xl font-black"><?php echo date('d/m/Y', strtotime($event['end_date'])); ?></span>
                        <?php else: ?>
                            <span class="text-sm uppercase font-bold tracking-widest opacity-80"><?php echo strftime('%b', strtotime($event['event_date'])); ?></span>
                            <span class="text-5xl font-black my-1"><?php echo date('d', strtotime($event['event_date'])); ?></span>
                            <span class="text-sm font-bold opacity-80"><?php echo date('Y', strtotime($event['event_date'])); ?></span>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Content -->
                    <div class="p-8 flex-grow">
                        <div class="flex flex-wrap items-center gap-3 mb-4">
                            <?php if($event['association_id']): ?>
                                <span class="px-3 py-1 bg-red-50 text-alsace-red text-xs font-bold rounded-full border border-red-100 uppercase tracking-wider">
                                    <?php echo htmlspecialchars($event['asso_name']); ?>
                                </span>
                            <?php else: ?>
                                <span class="px-3 py-1 bg-blue-50 text-blue-600 text-xs font-bold rounded-full border border-blue-100 uppercase tracking-wider">
                                    Mairie
                                </span>
                            <?php endif; ?>
                            <?php if($event['start_time']): ?>
                            <span class="flex items-center text-gray-500 text-sm font-medium">
                                <i data-lucide="clock" class="w-4 h-4 mr-1"></i>
                                <?php echo date('H:i', strtotime($event['start_time'])); ?><?php echo $event['end_time'] ? ' - ' . date('H:i', strtotime($event['end_time'])) : ''; ?>
                            </span>
                            <?php endif; ?>
                            <?php if($event['location']): ?>
                            <span class="flex items-center text-gray-500 text-sm font-medium">
                                <i data-lucide="map-pin" class="w-4 h-4 mr-1"></i>
                                <?php echo htmlspecialchars($event['location']); ?>
                            </span>
                            <?php endif; ?>
                        </div>
                        
                        <h3 class="font-serif text-2xl font-bold text-gray-900 mb-4"><?php echo htmlspecialchars($event['title']); ?></h3>
                        <p class="text-gray-600 leading-relaxed">
                            <?php echo nl2br(htmlspecialchars($event['description'])); ?>
                        </p>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- CALENDAR VIEW -->
            <div id="calendar-view" class="hidden bg-white p-6 rounded-2xl shadow-md border border-gray-100">
                <div id="calendar"></div>
            </div>

        <?php endif; ?>
    </div>
</main>

<style>
/* Custom FullCalendar Colors */
.fc .fc-col-header-cell-cushion { padding: 8px; font-weight: bold; color: #5c1a1b; }
.fc-theme-standard td, .fc-theme-standard th { border-color: #f3f4f6; }
.fc .fc-daygrid-day.fc-day-today { background-color: #fff1f2; }
.fc-h-event { background-color: #7b2c2d; border: none; padding: 2px 4px; border-radius: 4px; }
.fc-h-event .fc-event-title { font-weight: bold; }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        if(typeof lucide !== 'undefined') {
            lucide.createIcons();
        }

        const listView = document.getElementById('list-view');
        const calView = document.getElementById('calendar-view');
        const btnList = document.getElementById('btn-list-view');
        const btnCal = document.getElementById('btn-cal-view');
        
        let calendarRendered = false;

        // Bascule vers la vue Calendrier
        btnCal?.addEventListener('click', function() {
            listView.classList.add('hidden');
            calView.classList.remove('hidden');
            
            // Styliser les boutons
            btnCal.classList.replace('text-gray-600', 'text-white');
            btnCal.classList.replace('hover:bg-gray-100', 'bg-alsace-red');
            btnList.classList.replace('bg-alsace-red', 'hover:bg-gray-100');
            btnList.classList.replace('text-white', 'text-gray-600');

            // Render du calendrier uniquement au premier clic
            if(!calendarRendered) {
                var calendarEl = document.getElementById('calendar');
                var calendar = new FullCalendar.Calendar(calendarEl, {
                    initialView: 'dayGridMonth',
                    locale: 'fr',
                    headerToolbar: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'dayGridMonth,timeGridWeek,listWeek'
                    },
                    buttonText: {
                        today: 'Aujourd\'hui',
                        month: 'Mois',
                        week: 'Semaine',
                        list: 'Planning'
                    },
                    allDayText: 'Toute la journée',
                    events: <?php echo json_encode($calendar_events); ?>,
                    eventClick: function(info) {
                        alert(
                            info.event.title + '\n\n' + 
                            (info.event.extendedProps.description || 'Pas de description') + '\n\n' + 
                            (info.event.extendedProps.location ? 'Lieu : ' + info.event.extendedProps.location : '')
                        );
                    }
                });
                calendar.render();
                calendarRendered = true;
            }
        });

        // Bascule vers la vue Liste
        btnList?.addEventListener('click', function() {
            calView.classList.add('hidden');
            listView.classList.remove('hidden');
            
            // Styliser les boutons
            btnList.classList.replace('text-gray-600', 'text-white');
            btnList.classList.replace('hover:bg-gray-100', 'bg-alsace-red');
            btnCal.classList.replace('bg-alsace-red', 'hover:bg-gray-100');
            btnCal.classList.replace('text-white', 'text-gray-600');
        });
    });
</script>

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