<?php
$pageTitle = $pageTitle ?? 'Rapport d\'Événements';
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> - StayManager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="<?= getBaseUrl() ?>/assets/css/dashboard.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <?php include __DIR__ . '/../../includes/header_dynamic.php'; ?>

    <div class="container-fluid">
        <!-- En-tête de la page -->
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="page-title">
                        <i class="fas fa-calendar-alt text-primary"></i>
                        <?= $pageTitle ?>
                    </h1>
                    <p class="page-subtitle text-muted">
                        Analyse détaillée des événements et réservations de salles
                    </p>
                </div>
                <div class="col-md-4 text-end">
                    <div class="btn-group me-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="exportToCSV()">
                            <i class="fas fa-download me-1"></i>Exporter CSV
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="printReport()">
                            <i class="fas fa-print me-1"></i>Imprimer
                        </button>
                    </div>
                    <a href="dashboard.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Retour au tableau de bord
                    </a>
                </div>
            </div>
        </div>

                <!-- Filtres -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-filter me-2"></i>Filtres et Options
                        </h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" action="" class="row g-3">
                            <input type="hidden" name="report" value="events">
                            
                            <div class="col-md-3">
                                <label for="date_from" class="form-label">Date de début</label>
                                <input type="date" class="form-control" id="date_from" name="date_from" 
                                       value="<?= htmlspecialchars($filters['date_from']) ?>">
                            </div>
                            
                            <div class="col-md-3">
                                <label for="date_to" class="form-label">Date de fin</label>
                                <input type="date" class="form-control" id="date_to" name="date_to" 
                                       value="<?= htmlspecialchars($filters['date_to']) ?>">
                            </div>
                            
                            <div class="col-md-2">
                                <label for="period" class="form-label">Période</label>
                                <select class="form-select" id="period" name="period">
                                    <option value="daily" <?= $filters['period'] === 'daily' ? 'selected' : '' ?>>Journalier</option>
                                    <option value="monthly" <?= $filters['period'] === 'monthly' ? 'selected' : '' ?>>Mensuel</option>
                                    <option value="yearly" <?= $filters['period'] === 'yearly' ? 'selected' : '' ?>>Annuel</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label for="chart_type" class="form-label">Type de graphique</label>
                                <select class="form-select" id="chart_type" name="chart_type">
                                    <option value="line" <?= $filters['chart_type'] === 'line' ? 'selected' : '' ?>>Ligne</option>
                                    <option value="bar" <?= $filters['chart_type'] === 'bar' ? 'selected' : '' ?>>Barres</option>
                                    <option value="pie" <?= $filters['chart_type'] === 'pie' ? 'selected' : '' ?>>Secteurs</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-grid">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search me-1"></i>Filtrer
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Statistiques générales -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h6 class="card-title">Total Réservations</h6>
                                        <h3 class="mb-0"><?= number_format($eventsStats['total_bookings'] ?? 0) ?></h3>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-calendar-check fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h6 class="card-title">Revenus Totaux</h6>
                                        <h3 class="mb-0"><?= number_format($eventsStats['total_revenue'] ?? 0, 0, ',', ' ') ?> FCFA</h3>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-money-bill-wave fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h6 class="card-title">Moyenne par Réservation</h6>
                                        <h3 class="mb-0"><?= number_format($eventsStats['avg_booking_amount'] ?? 0, 0, ',', ' ') ?> FCFA</h3>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-chart-line fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h6 class="card-title">Clients Uniques</h6>
                                        <h3 class="mb-0"><?= number_format($eventsStats['unique_clients'] ?? 0) ?></h3>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-users fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Graphiques -->
                <div class="row mb-4">
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="fas fa-chart-line me-2"></i>Évolution des Réservations
                                </h5>
                            </div>
                            <div class="card-body">
                                <canvas id="eventsChart" height="100"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="fas fa-chart-pie me-2"></i>Répartition par Salle
                                </h5>
                            </div>
                            <div class="card-body">
                                <canvas id="roomsChart" height="200"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Top Salles -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="fas fa-trophy me-2"></i>Top Salles d'Événements
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Salle</th>
                                                <th>Réservations</th>
                                                <th>Revenus</th>
                                                <th>Moyenne</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($topRooms as $room): ?>
                                            <tr>
                                                <td>
                                                    <strong><?= htmlspecialchars($room['room_name']) ?></strong>
                                                    <br><small class="text-muted"><?= $room['capacity'] ?> personnes</small>
                                                </td>
                                                <td><?= $room['bookings_count'] ?></td>
                                                <td><?= number_format($room['total_revenue'], 0, ',', ' ') ?> FCFA</td>
                                                <td><?= number_format($room['avg_revenue'], 0, ',', ' ') ?> FCFA</td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="fas fa-chart-bar me-2"></i>Types d'Événements
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Type</th>
                                                <th>Réservations</th>
                                                <th>Revenus</th>
                                                <th>Moyenne</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($eventTypeStats as $type): ?>
                                            <tr>
                                                <td>
                                                    <span class="badge bg-primary">
                                                        <?= ucfirst(str_replace('_', ' ', $type['event_type'])) ?>
                                                    </span>
                                                </td>
                                                <td><?= $type['bookings_count'] ?></td>
                                                <td><?= number_format($type['total_revenue'], 0, ',', ' ') ?> FCFA</td>
                                                <td><?= number_format($type['avg_revenue'], 0, ',', ' ') ?> FCFA</td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Graphique des événements
        const eventsCtx = document.getElementById('eventsChart').getContext('2d');
        const eventsChart = new Chart(eventsCtx, {
            type: '<?= $filters['chart_type'] === 'pie' ? 'doughnut' : $filters['chart_type'] ?>',
            data: {
                labels: <?= json_encode($eventsData['labels']) ?>,
                datasets: [{
                    label: 'Réservations',
                    data: <?= json_encode($eventsData['bookings']) ?>,
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 2
                }, {
                    label: 'Revenus (FCFA)',
                    data: <?= json_encode($eventsData['revenue']) ?>,
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 2,
                    yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        grid: {
                            drawOnChartArea: false,
                        },
                    }
                }
            }
        });

        // Graphique des salles
        const roomsCtx = document.getElementById('roomsChart').getContext('2d');
        const roomsChart = new Chart(roomsCtx, {
            type: 'doughnut',
            data: {
                labels: <?= json_encode(array_column($topRooms, 'room_name')) ?>,
                datasets: [{
                    data: <?= json_encode(array_column($topRooms, 'total_revenue')) ?>,
                    backgroundColor: [
                        '#FF6384',
                        '#36A2EB',
                        '#FFCE56',
                        '#4BC0C0',
                        '#9966FF',
                        '#FF9F40'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });

        // Fonctions utilitaires
        function exportToCSV() {
            const url = new URL(window.location);
            url.searchParams.set('export', 'csv');
            window.open(url.toString(), '_blank');
        }

        function printReport() {
            window.print();
        }
    </script>
    
    <?php include __DIR__ . '/../../includes/footer.php'; ?>
</body>
</html>
