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

$stmt = $pdo->prepare("SELECT * FROM pages WHERE slug = :slug");
$stmt->execute(['slug' => 'salles']);
$page = $stmt->fetch();
$content = $page ? $page['content'] : 'Contenu non trouvé.';
$title = $page ? $page['title'] : 'Salles communales';

$message = '';
$error_message = '';

$hall_colors = [
    'Salle des fêtes' => '#ef4444',
    'Clubhouse Kutzenhausen' => '#3b82f6',
    'Clubhouse Oberkutzenhausen' => '#10b981'
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['book_hall'])) {
    $hall_name = $_POST['hall_name'];
    $booking_option = $_POST['booking_option'] ?? 'Entière';
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    
    // Vérifier les conflits de dates (seulement les réservations approuvées)
    $conflict_stmt = $pdo->prepare("SELECT booking_option FROM hall_reservations WHERE hall_name = ? AND status = 'approved' AND start_date <= ? AND end_date >= ?");
    $conflict_stmt->execute([$hall_name, $end_date, $start_date]);
    $conflicts = $conflict_stmt->fetchAll();
    
    $has_conflict = false;
    foreach ($conflicts as $c) {
        if ($hall_name === 'Salle des fêtes') {
            // Conflit si l'un demande entière, ou si les deux demandent la même (Petite ou Grande)
            if ($booking_option === 'Salle entière' || $c['booking_option'] === 'Salle entière' || $booking_option === $c['booking_option']) {
                $has_conflict = true; break;
            }
        } else {
            $has_conflict = true; break;
        }
    }

    if ($has_conflict) {
        $error_message = "<div class='bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded shadow-sm' role='alert'>
            <p class='font-bold'>Dates indisponibles</p>
            <p>La salle demandée est déjà réservée sur cette période. Veuillez consulter le calendrier et choisir d'autres dates.</p>
        </div>";
    } else {
        $user_name = $_POST['user_name'];
        $user_email = $_POST['user_email'];
        $user_phone = $_POST['user_phone'];
        $user_msg = $_POST['message'];
        
        $stmt = $pdo->prepare("INSERT INTO hall_reservations (hall_name, booking_option, start_date, end_date, user_name, user_email, user_phone, message) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$hall_name, $booking_option, $start_date, $end_date, $user_name, $user_email, $user_phone, $user_msg])) {
            $message = "<div class='bg-green-50 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded shadow-sm' role='alert'>
                <p class='font-bold'>Demande envoyée !</p>
                <p>Votre demande de réservation a bien été transmise à la mairie. Nous vous recontacterons très vite.</p>
            </div>";

            // Notification Admin
            $stmt_notif = $pdo->prepare("SELECT value FROM site_settings WHERE `key` = 'notify_hall_reservation'");
            $stmt_notif->execute();
            if ($stmt_notif->fetchColumn() == '1') {
                require_once 'includes/mailer.php';
                $notif_body = "Une nouvelle demande de réservation a été faite sur le site :\n\n";
                $notif_body .= "Salle : $hall_name\n";
                $notif_body .= "Option : $booking_option\n";
                $notif_body .= "Dates : du $start_date au $end_date\n";
                $notif_body .= "Nom : $user_name\n";
                $notif_body .= "Email : $user_email\n";
                $notif_body .= "Tél : $user_phone\n";
                $notif_body .= "Message : $user_msg\n";
                send_site_notification($pdo, "Nouvelle Réservation de Salle", $notif_body);
            }
        }
    }
}

// Fetch approved reservations for public calendar
$approved_reservations = $pdo->query("SELECT hall_name, booking_option, start_date, end_date FROM hall_reservations WHERE status = 'approved'")->fetchAll();
$public_events = [];
foreach($approved_reservations as $r) {
    // Add 1 day for FullCalendar exclusive end date handling
    $end_date_cal = date('Y-m-d', strtotime($r['end_date'] . ' +1 day'));
    $color = $hall_colors[$r['hall_name']] ?? '#dc2626';
    
    $event_title = 'Occupé (' . $r['hall_name'] . ')';
    if ($r['hall_name'] === 'Salle des fêtes' && $r['booking_option'] !== 'Salle entière') {
        $event_title = 'Occupé (' . $r['hall_name'] . ' - ' . $r['booking_option'] . ')';
    }
    
    $public_events[] = [
        'title' => $event_title,
        'start' => $r['start_date'],
        'end' => $end_date_cal,
        'color' => $color,
        'allDay' => true
    ];
}

$extra_head = "
<script src='js/fullcalendar.min.js'></script>
<script src='js/fullcalendar-fr.min.js'></script>
<style>
    .fc-theme-standard td, .fc-theme-standard th { border-color: #e5e7eb; }
    .fc-col-header-cell-cushion { padding: 8px !important; color: #374151; font-weight: bold; text-decoration: none !important; }
    .fc-daygrid-day-number { color: #4b5563; text-decoration: none !important; padding: 4px !important; }
    .fc-event { border-radius: 4px; border: none; padding: 2px 4px; font-size: 0.75rem; }
    .fc-toolbar-title { font-size: 1.25rem !important; color: #7b2c2d; font-family: 'Merriweather', serif; font-weight: bold; }
    .fc-button-primary { background-color: #7b2c2d !important; border-color: #7b2c2d !important; }
    .fc-button-primary:hover { background-color: #5c1a1b !important; border-color: #5c1a1b !important; }
    .fc-button-active { background-color: #5c1a1b !important; border-color: #5c1a1b !important; }
</style>
";

include 'includes/header.php';
?>

<main class="min-h-screen py-16 bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <h2 class="font-serif text-3xl md:text-4xl font-bold text-alsace-red mb-8 border-b-2 border-alsace-red pb-4">
            <?php echo htmlspecialchars($title); ?>
        </h2>
        
        <?php echo $message; ?>
        <?php echo $error_message; ?>

        <?php if (!empty(strip_tags($content)) && trim(strip_tags($content)) !== 'Contenu à définir'): ?>
        <div class="bg-white rounded-xl shadow-md p-8 border border-gray-100 prose max-w-none mb-12">
            <?php echo $content; ?>
        </div>
        <?php endif; ?>

        <!-- CALENDRIER PUBLIC -->
        <div class="bg-white rounded-xl shadow-md border border-gray-100 overflow-hidden p-6 md:p-8 mb-12">
            <h3 class="text-2xl font-bold text-gray-800 mb-6 flex items-center">
                <i data-lucide="calendar-days" class="w-6 h-6 text-alsace-red mr-2"></i> Calendrier d'occupation des salles
            </h3>
            <p class="text-gray-600 mb-4">Consultez les dates déjà réservées avant de faire votre demande. Les événements inscrits ci-dessous correspondent aux réservations confirmées par la mairie.</p>
            <div class="flex flex-wrap items-center gap-4 mb-6 text-sm font-bold text-gray-700">
                <span class="flex items-center"><span class="w-3 h-3 rounded-full bg-red-500 mr-2"></span> Salle des fêtes</span>
                <span class="flex items-center"><span class="w-3 h-3 rounded-full bg-blue-500 mr-2"></span> Clubhouse Kutzenhausen</span>
                <span class="flex items-center"><span class="w-3 h-3 rounded-full bg-green-500 mr-2"></span> Clubhouse Oberkutzenhausen</span>
            </div>
            <div id='public-calendar' class="max-h-[500px] overflow-hidden"></div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-12">
            
            <!-- LISTE DES SALLES -->
            <div class="space-y-8">
                <h3 class="text-2xl font-bold text-gray-800 mb-6 flex items-center">
                    <i data-lucide="home" class="w-6 h-6 text-alsace-red mr-2"></i> Nos salles disponibles
                </h3>
                
                <!-- Salle des fêtes -->
                <div class="bg-white rounded-xl shadow-md border border-gray-100 overflow-hidden">
                    <img src="https://placehold.co/600x300/EAE0D5/7B2C2D?text=Salle+des+fêtes" alt="Salle des fêtes" class="w-full h-48 object-cover">
                    <div class="p-6">
                        <h4 class="font-bold text-xl text-gray-800 mb-2">Salle des Fêtes</h4>
                        <p class="text-gray-600 text-sm mb-4">Parfaite pour vos grands événements, mariages, banquets. Elle peut être séparée en deux.</p>
                        <div class="flex flex-wrap gap-2 mb-4">
                            <span class="px-2 py-1 bg-red-50 text-alsace-red text-xs font-bold rounded">Petite salle</span>
                            <span class="px-2 py-1 bg-red-50 text-alsace-red text-xs font-bold rounded">Grande salle</span>
                            <span class="px-2 py-1 bg-red-50 text-alsace-red text-xs font-bold rounded">Salle entière</span>
                        </div>
                    </div>
                </div>

                <!-- Clubhouse Kutzenhausen -->
                <div class="bg-white rounded-xl shadow-md border border-gray-100 overflow-hidden">
                    <img src="https://placehold.co/600x300/EAE0D5/7B2C2D?text=Clubhouse+Kutzenhausen" alt="Clubhouse Kutz" class="w-full h-48 object-cover">
                    <div class="p-6">
                        <h4 class="font-bold text-xl text-gray-800 mb-2">Clubhouse de Kutzenhausen</h4>
                        <p class="text-gray-600 text-sm mb-4">Idéal pour des réunions de famille, anniversaires ou associations sportives.</p>
                        <span class="px-2 py-1 bg-red-50 text-alsace-red text-xs font-bold rounded">Salle entière</span>
                    </div>
                </div>

                <!-- Clubhouse Oberkutzenhausen -->
                <div class="bg-white rounded-xl shadow-md border border-gray-100 overflow-hidden">
                    <img src="https://placehold.co/600x300/EAE0D5/7B2C2D?text=Clubhouse+Oberkutzenhausen" alt="Clubhouse Oberkutz" class="w-full h-48 object-cover">
                    <div class="p-6">
                        <h4 class="font-bold text-xl text-gray-800 mb-2">Clubhouse d'Oberkutzenhausen</h4>
                        <p class="text-gray-600 text-sm mb-4">Une salle conviviale située au cœur d'Oberkutzenhausen pour vos festivités.</p>
                        <span class="px-2 py-1 bg-red-50 text-alsace-red text-xs font-bold rounded">Salle entière</span>
                    </div>
                </div>

            </div>

            <!-- FORMULAIRE DE RESERVATION -->
            <div class="h-fit sticky top-32">
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
                    <div class="bg-[#5c1a1b] p-6">
                        <h3 class="text-xl font-bold text-white flex items-center">
                            <i data-lucide="edit-3" class="w-6 h-6 mr-2"></i> Demande de réservation
                        </h3>
                    </div>
                    
                    <form action="" method="POST" class="p-6 md:p-8 space-y-6">
                        
                        <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">Salle souhaitée *</label>
                                <select name="hall_name" id="hall_name" required class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                                    <option value="">-- Choisir une salle --</option>
                                    <option value="Salle des fêtes">Salle des fêtes</option>
                                    <option value="Clubhouse Kutzenhausen">Clubhouse Kutzenhausen</option>
                                    <option value="Clubhouse Oberkutzenhausen">Clubhouse Oberkutzenhausen</option>
                                </select>
                            </div>
                            
                            <div id="option_container" class="opacity-50 pointer-events-none transition-opacity">
                                <label class="block text-sm font-bold text-gray-700 mb-2">Option de la salle</label>
                                <select name="booking_option" id="booking_option" class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]" disabled>
                                    <option value="Petite salle">Petite salle</option>
                                    <option value="Grande salle">Grande salle</option>
                                    <option value="Salle entière">Salle entière (les deux)</option>
                                </select>
                            </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 *</label>
                                <input type="date" name="start_date" required class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                            </div>
                            <div>
                                <label class="block text-sm font-bold text-gray-700 mb-2">Date de fin *</label>
                                <input type="date" name="end_date" required class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                            </div>
                        </div>

                        <hr class="border-gray-200">

                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Nom et Prénom (ou Association) *</label>
                            <input type="text" name="user_name" required class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                        </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">Email *</label>
                                <input type="email" name="user_email" required class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                            </div>
                            <div>
                                <label class="block text-sm font-bold text-gray-700 mb-2">Téléphone *</label>
                                <input type="tel" name="user_phone" required class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]">
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Motif de la réservation / Message additionnel</label>
                            <textarea name="message" rows="3" class="w-full border border-gray-300 rounded-md p-3 outline-none focus:border-[#7b2c2d]" placeholder="Mariage, fête associative..."></textarea>
                        </div>

                        <button type="submit" name="book_hall" class="w-full bg-[#7b2c2d] text-white font-bold py-3 px-4 rounded-md hover:bg-[#5c1a1b] transition shadow-md flex justify-center items-center">
                            Envoyer la demande
                        </button>
                        
                        <p class="text-xs text-gray-500 text-center mt-4">
                            Ceci est une demande de pré-réservation. La mairie vous recontactera pour la confirmation définitive et l'établissement du contrat de location.
                        </p>

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

        </div>

    </div>
</main>

<script>
    if(typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
    
    // Activer/Désactiver l'option "Petite/Grande salle" selon le choix
    const hallSelect = document.getElementById('hall_name');
    const optionSelect = document.getElementById('booking_option');
    const optionContainer = document.getElementById('option_container');
    
    hallSelect.addEventListener('change', function() {
        if (this.value === 'Salle des fêtes') {
            optionSelect.disabled = false;
            optionContainer.classList.remove('opacity-50', 'pointer-events-none');
        } else {
            optionSelect.disabled = true;
            optionContainer.classList.add('opacity-50', 'pointer-events-none');
            // Réinitialiser la valeur
            optionSelect.value = 'Salle entière';
        }
    });

    // Initialiser le calendrier public
    document.addEventListener('DOMContentLoaded', function() {
        var calendarEl = document.getElementById('public-calendar');
        if (calendarEl) {
            var calendar = new FullCalendar.Calendar(calendarEl, {
                initialView: 'dayGridMonth',
                locale: 'fr',
                height: 'auto',
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: '' // Just the month view for public
                },
                events: <?php echo json_encode($public_events); ?>,
                eventDisplay: 'block'
            });
            calendar.render();
        }
    });
</script>

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