<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Événements - StayManager</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #2563eb;
            --secondary-color: #64748b;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
            --dark-color: #1e293b;
            --light-color: #f8fafc;
            --sidebar-width: 280px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--light-color);
            overflow-x: hidden;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            width: var(--sidebar-width);
            background: linear-gradient(180deg, var(--dark-color) 0%, #334155 100%);
            color: white;
            z-index: 1000;
            transition: transform 0.3s ease;
            box-shadow: 4px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar.collapsed {
            transform: translateX(-100%);
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            text-align: center;
        }

        .sidebar-header h3 {
            color: white;
            font-weight: 700;
            margin: 0;
        }

        .sidebar-header p {
            color: rgba(255, 255, 255, 0.7);
            margin: 5px 0 0 0;
            font-size: 0.9rem;
        }

        .sidebar-nav {
            padding: 20px 0;
        }

        .nav-item {
            margin-bottom: 5px;
        }

        .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            display: flex;
            align-items: center;
            text-decoration: none;
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
        }

        .nav-link:hover {
            color: white;
            background: rgba(255, 255, 255, 0.1);
            border-left-color: var(--primary-color);
        }

        .nav-link.active {
            color: white;
            background: rgba(37, 99, 235, 0.2);
            border-left-color: var(--primary-color);
        }

        .nav-link i {
            margin-right: 12px;
            width: 20px;
            text-align: center;
        }

        .sidebar-footer {
            position: absolute;
            bottom: 0;
            width: 100%;
            padding: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .user-info {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            font-weight: 600;
        }

        .user-details h6 {
            margin: 0;
            font-size: 0.9rem;
        }

        .user-details small {
            color: rgba(255, 255, 255, 0.7);
        }

        /* Main Content */
        .main-content {
            margin-left: var(--sidebar-width);
            min-height: 100vh;
            transition: margin-left 0.3s ease;
        }

        .main-content.expanded {
            margin-left: 0;
        }

        .top-bar {
            background: white;
            padding: 15px 30px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .sidebar-toggle {
            background: none;
            border: none;
            font-size: 1.5rem;
            color: var(--secondary-color);
            cursor: pointer;
            padding: 5px;
            border-radius: 5px;
            transition: all 0.3s ease;
        }

        .sidebar-toggle:hover {
            background: var(--light-color);
            color: var(--primary-color);
        }

        .page-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--dark-color);
            margin: 0;
        }

        .top-bar-actions {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        /* Content */
        .content {
            padding: 30px;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: linear-gradient(90deg, var(--primary-color), var(--success-color));
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .stat-header {
            display: flex;
            justify-content: between;
            align-items: center;
            margin-bottom: 15px;
        }

        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
        }

        .stat-icon.primary { background: linear-gradient(135deg, var(--primary-color), #1d4ed8); }
        .stat-icon.success { background: linear-gradient(135deg, var(--success-color), #059669); }
        .stat-icon.warning { background: linear-gradient(135deg, var(--warning-color), #d97706); }
        .stat-icon.danger { background: linear-gradient(135deg, var(--danger-color), #dc2626); }

        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--dark-color);
            margin-bottom: 5px;
        }

        .stat-label {
            color: var(--secondary-color);
            font-size: 0.9rem;
            font-weight: 500;
        }

        /* Tabs */
        .nav-tabs {
            border-bottom: 2px solid #e2e8f0;
            margin-bottom: 30px;
        }

        .nav-tabs .nav-link {
            border: none;
            color: var(--secondary-color);
            font-weight: 500;
            padding: 15px 25px;
            border-radius: 0;
            position: relative;
        }

        .nav-tabs .nav-link:hover {
            color: var(--primary-color);
            background: none;
            border-left: none;
        }

        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            background: none;
            border-left: none;
        }

        .nav-tabs .nav-link.active::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 100%;
            height: 2px;
            background: var(--primary-color);
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.show {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <h3><i class="bi bi-building"></i> StayManager</h3>
            <p>Gestion hôtelière</p>
        </div>

        <nav class="sidebar-nav">
            <div class="nav-item">
                <a href="dashboard.php" class="nav-link">
                    <i class="bi bi-speedometer2"></i>
                    Dashboard
                </a>
            </div>
            <div class="nav-item">
                <a href="reservations.php" class="nav-link">
                    <i class="bi bi-calendar-check"></i>
                    Réservations
                </a>
            </div>
            <div class="nav-item">
                <a href="rooms.php" class="nav-link">
                    <i class="bi bi-house-door"></i>
                    Chambres
                </a>
            </div>
            <div class="nav-item">
                <a href="clients.php" class="nav-link">
                    <i class="bi bi-people"></i>
                    Clients
                </a>
            </div>
            <div class="nav-item">
                <a href="payments.php" class="nav-link">
                    <i class="bi bi-credit-card"></i>
                    Paiements
                </a>
            </div>
            <div class="nav-item">
                <a href="events.php" class="nav-link active">
                    <i class="bi bi-calendar-event"></i>
                    Événements
                </a>
            </div>
            <div class="nav-item">
                <a href="restaurant.php" class="nav-link">
                    <i class="bi bi-cup-hot"></i>
                    Restaurant
                </a>
            </div>
            <div class="nav-item">
                <a href="inventory.php" class="nav-link">
                    <i class="bi bi-box-seam"></i>
                    Stock
                </a>
            </div>
            <div class="nav-item">
                <a href="staff.php" class="nav-link">
                    <i class="bi bi-person-badge"></i>
                    Personnel
                </a>
            </div>
            <div class="nav-item">
                <a href="maintenance.php" class="nav-link">
                    <i class="bi bi-tools"></i>
                    Maintenance
                </a>
            </div>
            <div class="nav-item">
                <a href="reports.php" class="nav-link">
                    <i class="bi bi-graph-up"></i>
                    Rapports
                </a>
            </div>
            <div class="nav-item">
                <a href="settings.php" class="nav-link">
                    <i class="bi bi-gear"></i>
                    Paramètres
                </a>
            </div>
        </nav>

        <div class="sidebar-footer">
            <div class="user-info">
                <div class="user-avatar">
                    <?php echo strtoupper(substr($_SESSION['user_name'] ?? 'U', 0, 1)); ?>
                </div>
                <div class="user-details">
                    <h6><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Utilisateur'); ?></h6>
                    <small><?php echo ucfirst($_SESSION['user_role'] ?? 'Utilisateur'); ?></small>
                </div>
            </div>
            <a href="logout.php" class="btn btn-outline-light btn-sm w-100">
                <i class="bi bi-box-arrow-right me-2"></i>Déconnexion
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content" id="mainContent">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="d-flex align-items-center">
                <button class="sidebar-toggle me-3" onclick="toggleSidebar()">
                    <i class="bi bi-list"></i>
                </button>
                <h1 class="page-title">Gestion des Événements</h1>
            </div>

            <div class="top-bar-actions">
                <div class="dropdown">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-person-circle me-2"></i>
                        <?php echo htmlspecialchars($_SESSION['username'] ?? 'Utilisateur'); ?>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="profile.php">
                            <i class="bi bi-person me-2"></i>Profil
                        </a></li>
                        <li><a class="dropdown-item" href="change-password.php">
                            <i class="bi bi-key me-2"></i>Changer mot de passe
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="logout.php">
                            <i class="bi bi-box-arrow-right me-2"></i>Déconnexion
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Content -->
        <div class="content">
            <!-- Statistics Cards -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-header">
                        <div class="stat-icon primary">
                            <i class="bi bi-building"></i>
                        </div>
                    </div>
                    <div class="stat-value"><?php echo $roomStats['total'] ?? 0; ?></div>
                    <div class="stat-label">Salles d'événements</div>
                </div>

                <div class="stat-card">
                    <div class="stat-header">
                        <div class="stat-icon success">
                            <i class="bi bi-check-circle"></i>
                        </div>
                    </div>
                    <div class="stat-value"><?php echo $roomStats['active'] ?? 0; ?></div>
                    <div class="stat-label">Salles actives</div>
                </div>

                <div class="stat-card">
                    <div class="stat-header">
                        <div class="stat-icon warning">
                            <i class="bi bi-calendar-event"></i>
                        </div>
                    </div>
                    <div class="stat-value"><?php echo $bookingStats['total'] ?? 0; ?></div>
                    <div class="stat-label">Réservations totales</div>
                </div>

                <div class="stat-card">
                    <div class="stat-header">
                        <div class="stat-icon danger">
                            <i class="bi bi-currency-dollar"></i>
                        </div>
                    </div>
                    <div class="stat-value">₣ <?php echo number_format($bookingStats['total_revenue'] ?? 0, 0, ',', ' '); ?></div>
                    <div class="stat-label">Chiffre d'affaires</div>
                </div>
            </div>

                         <!-- Tabs -->
             <ul class="nav nav-tabs" id="eventsTabs" role="tablist">
                 <li class="nav-item" role="presentation">
                     <button class="nav-link <?php echo $activeTab === 'bookings' ? 'active' : ''; ?>" 
                             id="bookings-tab" 
                             data-bs-toggle="tab" 
                             data-bs-target="#bookings" 
                             type="button" 
                             role="tab"
                             onclick="loadTab('bookings')">
                         <i class="bi bi-calendar-check me-2"></i>
                         Réservations d'événements
                     </button>
                 </li>
                 <li class="nav-item" role="presentation">
                     <button class="nav-link <?php echo $activeTab === 'rooms' ? 'active' : ''; ?>" 
                             id="rooms-tab" 
                             data-bs-toggle="tab" 
                             data-bs-target="#rooms" 
                             type="button" 
                             role="tab"
                             onclick="loadTab('rooms')">
                         <i class="bi bi-building me-2"></i>
                         Salles d'événements
                     </button>
                 </li>
                 <li class="nav-item" role="presentation">
                     <button class="nav-link <?php echo $activeTab === 'schedule' ? 'active' : ''; ?>" 
                             id="schedule-tab" 
                             data-bs-toggle="tab" 
                             data-bs-target="#schedule" 
                             type="button" 
                             role="tab"
                             onclick="loadTab('schedule')">
                         <i class="bi bi-calendar-week me-2"></i>
                         Planning de la semaine
                     </button>
                 </li>
             </ul>

            <!-- Tab Content -->
            <div class="tab-content" id="eventsTabContent">
                <div class="tab-pane fade <?php echo $activeTab === 'bookings' ? 'show active' : ''; ?>" 
                     id="bookings" 
                     role="tabpanel" 
                     aria-labelledby="bookings-tab">
                    <div id="bookingsContent">
                        <!-- Le contenu sera chargé dynamiquement -->
                    </div>
                </div>
                                 <div class="tab-pane fade <?php echo $activeTab === 'rooms' ? 'show active' : ''; ?>" 
                      id="rooms" 
                      role="tabpanel" 
                      aria-labelledby="rooms-tab">
                     <div id="roomsContent">
                         <!-- Le contenu sera chargé dynamiquement -->
                     </div>
                 </div>
                 <div class="tab-pane fade <?php echo $activeTab === 'schedule' ? 'show active' : ''; ?>" 
                      id="schedule" 
                      role="tabpanel" 
                      aria-labelledby="schedule-tab">
                     <div id="scheduleContent">
                         <!-- Le contenu sera chargé dynamiquement -->
                     </div>
                 </div>
             </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Sidebar toggle
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('mainContent');
            
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('expanded');
        }

        // Load tab content
        function loadTab(tab, params = '') {
            let contentDiv, url;
            
            if (tab === 'bookings') {
                contentDiv = 'bookingsContent';
                url = 'event_bookings.php';
            } else if (tab === 'rooms') {
                contentDiv = 'roomsContent';
                url = 'event_rooms.php';
            } else if (tab === 'schedule') {
                contentDiv = 'scheduleContent';
                url = 'event_bookings.php?action=get_weekly_schedule';
                // Pour le planning, on charge directement le JSON
                loadWeeklySchedule();
                return;
            }
            
            // Add parameters if provided
            if (params) {
                url += '?' + params;
            }
            
            console.log('Loading tab:', tab, 'URL:', url);
            
            // Show loading
            document.getElementById(contentDiv).innerHTML = '<div class="text-center p-5"><div class="spinner-border text-primary" role="status"></div><p class="mt-3">Chargement...</p></div>';
            
            // Load content via AJAX
            fetch(url)
                .then(response => {
                    console.log('Response status:', response.status);
                    return response.text();
                })
                .then(html => {
                    console.log('Content loaded for tab:', tab, 'Length:', html.length);
                    document.getElementById(contentDiv).innerHTML = html;
                    // Re-attach event listeners after content is loaded
                    setTimeout(() => {
                        console.log('Attaching listeners for tab:', tab);
                        attachSearchFormListeners(tab);
                    }, 100);
                })
                .catch(error => {
                    console.error('Error loading tab:', tab, error);
                    document.getElementById(contentDiv).innerHTML = '<div class="alert alert-danger">Erreur lors du chargement</div>';
                });
        }

        // Handle search form submission
        function attachSearchFormListeners(tab) {
            const searchForm = document.getElementById('searchForm');
            console.log('Attaching listeners for tab:', tab, 'Form found:', !!searchForm);
            
            if (searchForm) {
                // Remove any existing event listeners by cloning the form
                const newForm = searchForm.cloneNode(true);
                searchForm.parentNode.replaceChild(newForm, searchForm);
                
                // Add new event listener to the new form
                newForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    console.log('Form submitted for tab:', tab);
                    
                    const formData = new FormData(newForm);
                    const params = new URLSearchParams(formData);
                    
                    // Remove the action parameter as it's not needed for the model
                    params.delete('action');
                    
                    console.log('Loading tab with params:', params.toString());
                    loadTab(tab, params.toString());
                });
                
                // Also prevent default on the form itself
                newForm.onsubmit = function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                };
            }
        }

        // Reset search form
        function resetSearch() {
            const searchForm = document.getElementById('searchForm');
            console.log('Resetting search form, form found:', !!searchForm);
            
            if (searchForm) {
                searchForm.reset();
                // Determine current tab and reload without parameters
                const activeTabElement = document.querySelector('.nav-tabs .nav-link.active');
                console.log('Active tab element:', activeTabElement);
                
                if (activeTabElement) {
                    const activeTab = activeTabElement.getAttribute('id').replace('-tab', '');
                    console.log('Loading tab without params:', activeTab);
                    loadTab(activeTab);
                }
            }
        }

        // Load specific page
        function loadPage(page) {
            const activeTabElement = document.querySelector('.nav-tabs .nav-link.active');
            if (!activeTabElement) {
                console.error('No active tab found');
                return;
            }
            
            const activeTab = activeTabElement.getAttribute('id').replace('-tab', '');
            
            // Ne pas charger de page pour le planning
            if (activeTab === 'schedule') {
                return;
            }
            
            const searchForm = document.getElementById('searchForm');
            let params = 'page=' + page;
            
            if (searchForm) {
                const formData = new FormData(searchForm);
                const urlParams = new URLSearchParams(formData);
                urlParams.delete('action');
                urlParams.set('page', page);
                params = urlParams.toString();
            }
            
            console.log('Loading page', page, 'for tab', activeTab, 'with params:', params);
            loadTab(activeTab, params);
        }

        // Load weekly schedule
        function loadWeeklySchedule() {
            const scheduleContent = document.getElementById('scheduleContent');
            scheduleContent.innerHTML = '<div class="text-center p-5"><div class="spinner-border text-primary" role="status"></div><p class="mt-3">Chargement du planning...</p></div>';

            fetch('event_bookings.php?action=get_weekly_schedule')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayWeeklySchedule(data.bookings, data.week_start, data.week_end);
                } else {
                    scheduleContent.innerHTML = '<div class="alert alert-danger">Erreur lors du chargement du planning</div>';
                }
            })
            .catch(error => {
                console.error('Error loading schedule:', error);
                scheduleContent.innerHTML = '<div class="alert alert-danger">Erreur lors du chargement du planning</div>';
            });
        }

        function displayWeeklySchedule(bookings, weekStart, weekEnd) {
            const scheduleContent = document.getElementById('scheduleContent');
            
            if (!bookings || bookings.length === 0) {
                scheduleContent.innerHTML = '<div class="text-center py-5"><i class="bi bi-calendar-week display-1 text-muted"></i><h4 class="mt-3 text-muted">Aucune réservation cette semaine</h4></div>';
                return;
            }

            // Grouper les réservations par jour
            const bookingsByDay = {};
            bookings.forEach(booking => {
                const date = booking.event_date;
                if (!bookingsByDay[date]) {
                    bookingsByDay[date] = [];
                }
                bookingsByDay[date].push(booking);
            });

            let html = '<div class="card"><div class="card-header"><h5 class="mb-0"><i class="bi bi-calendar-week"></i> Planning de la semaine</h5></div><div class="card-body">';
            html += '<div class="row">';
            
            // Générer les jours de la semaine
            const startDate = new Date(weekStart);
            const endDate = new Date(weekEnd);
            
            for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
                const dateStr = d.toISOString().split('T')[0];
                const dayName = d.toLocaleDateString('fr-FR', { weekday: 'long' });
                const dayNumber = d.getDate();
                const monthName = d.toLocaleDateString('fr-FR', { month: 'long' });
                
                html += '<div class="col-lg-3 col-md-4 col-sm-6 mb-3">';
                html += `<div class="border rounded p-3 ${d.getDay() === 0 || d.getDay() === 6 ? 'bg-light' : ''}">`;
                html += `<h6 class="mb-2"><strong>${dayName} ${dayNumber} ${monthName}</strong></h6>`;
                
                if (bookingsByDay[dateStr]) {
                    bookingsByDay[dateStr].forEach(booking => {
                        const statusClass = booking.status === 'confirmed' ? 'success' : 
                                          booking.status === 'pending' ? 'warning' : 'secondary';
                        html += `<div class="small mb-2 p-2 bg-${statusClass} text-white rounded">`;
                        html += `<strong>${booking.room_name}</strong><br>`;
                        html += `${booking.start_time} - ${booking.end_time}<br>`;
                        html += `<small>${booking.event_type}</small><br>`;
                        html += `<small>Client: ${booking.first_name} ${booking.last_name}</small>`;
                        html += '</div>';
                    });
                } else {
                    html += '<div class="text-muted small">Aucune réservation</div>';
                }
                
                html += '</div></div>';
            }
            
            html += '</div></div></div>';
            scheduleContent.innerHTML = html;
        }

        // Load initial content
        document.addEventListener('DOMContentLoaded', function() {
            const activeTab = '<?php echo $activeTab; ?>';
            if (activeTab) {
                loadTab(activeTab);
            }
        });

        // Handle window resize
        window.addEventListener('resize', function() {
            if (window.innerWidth <= 768) {
                document.getElementById('sidebar').classList.add('collapsed');
                document.getElementById('mainContent').classList.add('expanded');
            }
        });
    </script>
</body>
</html>
