<?php
// rapport.php
require_once '../../src/includes/config.php';

// Vérifier l'authentification
if (!isset($_SESSION['gestionnaire_id'])) {
    header('Location: login.php');
    exit;
}

$role = $_SESSION['role'];
$service_id = $_SESSION['service_id'];

// 🔐 Services autorisés pour le filtre
$services_autorises = ($role === 'admin') ? [1, 2] : [$service_id];
$placeholders_services = str_repeat('?,', count($services_autorises) - 1) . '?';

// Vérifier si DomPDF est disponible via Composer
$dompdfAvailable = false;
if (file_exists('../../vendor/autoload.php')) {
    require_once '../../vendor/autoload.php';
    $dompdfAvailable = true;
}

// Traitement de la génération du PDF
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generer_pdf'])) {
    if (!$dompdfAvailable) {
        $_SESSION['error'] = "DompDF n'est pas installé. Veuillez l'installer avec: composer require dompdf/dompdf";
        header('Location: rapport.php');
        exit;
    }
    
    $type_rapport = $_POST['type_rapport'] ?? 'general';
    $date_debut = $_POST['date_debut'] ?? date('Y-m-01');
    $date_fin = $_POST['date_fin'] ?? date('Y-m-d');
    $format = $_POST['format'] ?? 'A4';
    
    // Récupérer les données selon le type de rapport
    $donnees = genererDonneesRapport($type_rapport, $date_debut, $date_fin, $pdo, $services_autorises);
    
    // Générer le PDF
    genererPDF($donnees, $type_rapport, $date_debut, $date_fin, $format);
    exit;
}

// Fonction pour générer les données du rapport
function genererDonneesRapport($type, $debut, $fin, $pdo, $services_autorises) {
    $placeholders = str_repeat('?,', count($services_autorises) - 1) . '?';
    $params = array_merge([$debut, $fin], $services_autorises);
    
    $donnees = [
        'titre' => '',
        'colonnes' => [],
        'lignes' => [],
        'statistiques' => []
    ];
    
    switch($type) {
        case 'gestionnaires':
            $donnees['titre'] = 'Rapport des Gestionnaires';
            
            $stmt = $pdo->prepare("
                SELECT g.id, g.nom_complet, g.email, g.role, g.actif, g.date_creation,
                       s.nom_service as service
                FROM gestionnaires g
                LEFT JOIN services s ON g.service_id = s.id
                WHERE g.date_creation BETWEEN ? AND ?
                ORDER BY g.date_creation DESC
            ");
            $stmt->execute([$debut, $fin]);
            $donnees['lignes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $donnees['colonnes'] = ['ID', 'Nom Complet', 'Email', 'Rôle', 'Actif', 'Date Création', 'Service'];
            
            // Statistiques
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM gestionnaires WHERE date_creation BETWEEN ? AND ?");
            $stmt->execute([$debut, $fin]);
            $total = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as actifs FROM gestionnaires WHERE actif = 1 AND date_creation BETWEEN ? AND ?");
            $stmt->execute([$debut, $fin]);
            $actifs = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as admins FROM gestionnaires WHERE role = 'admin' AND date_creation BETWEEN ? AND ?");
            $stmt->execute([$debut, $fin]);
            $admins = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $donnees['statistiques'] = [
                'Total gestionnaires' => $total['total'],
                'Gestionnaires actifs' => $actifs['actifs'],
                'Administrateurs' => $admins['admins'],
                'Période' => date('d/m/Y', strtotime($debut)) . ' - ' . date('d/m/Y', strtotime($fin))
            ];
            break;
            
        case 'dossiers':
            $donnees['titre'] = 'Rapport des Dossiers';
            
            $stmt = $pdo->prepare("
                SELECT d.id, d.numero_dossier, d.titre, d.description, d.mode_depot,
                       d.nom_auteur, d.matricule_auteur, d.service_auteur, d.lieu,
                       td.libelle as type_dossier,
                       ts.libelle as type_situation,
                       s.nom_service as service_cible,
                       st.libelle as statut,
                       d.date_creation, d.date_maj, d.auteur_notifie
                FROM dossiers d
                LEFT JOIN types_dossier td ON d.type_id = td.id
                LEFT JOIN types_situation ts ON d.type_situation_id = ts.id
                LEFT JOIN services s ON d.service_cible_id = s.id
                LEFT JOIN statuts st ON d.statut_id = st.id
                WHERE d.date_creation BETWEEN ? AND ? AND d.service_cible_id IN ($placeholders)
                ORDER BY d.date_creation DESC
            ");
            $stmt->execute($params);
            $donnees['lignes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $donnees['colonnes'] = ['ID', 'N° Dossier', 'Titre', 'Description', 'Mode Dépôt', 'Nom Auteur', 'Matricule', 'Service Auteur', 'Lieu', 'Type', 'Type Situation', 'Service Cible', 'Statut', 'Date Création', 'Date MAJ', 'Auteur Notifié'];
            
            // Statistiques
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM dossiers WHERE date_creation BETWEEN ? AND ? AND service_cible_id IN ($placeholders)");
            $stmt->execute($params);
            $total = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as anonymes FROM dossiers WHERE mode_depot = 'anonyme' AND date_creation BETWEEN ? AND ? AND service_cible_id IN ($placeholders)");
            $stmt->execute($params);
            $anonymes = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as confidentiels FROM dossiers WHERE mode_depot = 'confidentiel' AND date_creation BETWEEN ? AND ? AND service_cible_id IN ($placeholders)");
            $stmt->execute($params);
            $confidentiels = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Par type
            $stmt = $pdo->prepare("
                SELECT td.libelle, COUNT(*) as count 
                FROM dossiers d 
                JOIN types_dossier td ON d.type_id = td.id 
                WHERE d.date_creation BETWEEN ? AND ? AND d.service_cible_id IN ($placeholders)
                GROUP BY td.libelle
            ");
            $stmt->execute($params);
            $par_type = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $types_text = "";
            foreach ($par_type as $type_row) {
                $types_text .= $type_row['libelle'] . ": " . $type_row['count'] . " | ";
            }
            
            $donnees['statistiques'] = [
                'Total dossiers' => $total['total'],
                'Dépôts anonymes' => $anonymes['anonymes'],
                'Dépôts confidentiels' => $confidentiels['confidentiels'],
                'Répartition par type' => rtrim($types_text, ' | '),
                'Période' => date('d/m/Y', strtotime($debut)) . ' - ' . date('d/m/Y', strtotime($fin))
            ];
            break;
            
        case 'services':
            $donnees['titre'] = 'Rapport des Services';
            
            $stmt = $pdo->prepare("
                SELECT s.id, s.nom_service, s.email_alerte, s.description,
                       COUNT(DISTINCT g.id) as nb_gestionnaires,
                       COUNT(DISTINCT d.id) as nb_dossiers
                FROM services s
                LEFT JOIN gestionnaires g ON s.id = g.service_id
                LEFT JOIN dossiers d ON s.id = d.service_cible_id
                GROUP BY s.id
                ORDER BY s.id
            ");
            $stmt->execute();
            $donnees['lignes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $donnees['colonnes'] = ['ID', 'Nom Service', 'Email Alerte', 'Description', 'Nb Gestionnaires', 'Nb Dossiers'];
            
            // Statistiques
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM services");
            $stmt->execute();
            $total = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(DISTINCT service_cible_id) as services_avec_dossiers FROM dossiers WHERE date_creation BETWEEN ? AND ?");
            $stmt->execute([$debut, $fin]);
            $avec_dossiers = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $donnees['statistiques'] = [
                'Total services' => $total['total'],
                'Services avec dossiers' => $avec_dossiers['services_avec_dossiers'],
                'Période' => date('d/m/Y', strtotime($debut)) . ' - ' . date('d/m/Y', strtotime($fin))
            ];
            break;
            
        case 'types_situation':
            $donnees['titre'] = 'Rapport des Types de Situation';
            
            $stmt = $pdo->prepare("
                SELECT ts.id, ts.libelle, ts.code, ts.dossier_type_id, ts.actif, ts.created_at, ts.updated_at,
                       td.libelle as type_dossier
                FROM types_situation ts
                LEFT JOIN types_dossier td ON ts.dossier_type_id = td.id
                ORDER BY ts.dossier_type_id, ts.libelle
            ");
            $stmt->execute();
            $donnees['lignes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $donnees['colonnes'] = ['ID', 'Libellé', 'Code', 'Type Dossier ID', 'Type Dossier', 'Actif', 'Créé le', 'Mis à jour le'];
            
            // Statistiques
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM types_situation");
            $stmt->execute();
            $total = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as actifs FROM types_situation WHERE actif = 1");
            $stmt->execute();
            $actifs = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $donnees['statistiques'] = [
                'Total types de situation' => $total['total'],
                'Types actifs' => $actifs['actifs'],
                'Période' => date('d/m/Y', strtotime($debut)) . ' - ' . date('d/m/Y', strtotime($fin))
            ];
            break;
            
        default:
            $donnees['titre'] = 'Rapport Général CI-ENERGIES';
            $donnees['colonnes'] = ['Métrique', 'Valeur'];
            
            // Statistiques générales
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM gestionnaires");
            $stmt->execute();
            $total_gestionnaires = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM dossiers");
            $stmt->execute();
            $total_dossiers = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM services");
            $stmt->execute();
            $total_services = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM pieces_jointes");
            $stmt->execute();
            $total_pieces = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM types_situation");
            $stmt->execute();
            $total_types_situation = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Dossiers par statut
            $stmt = $pdo->prepare("
                SELECT st.libelle, COUNT(*) as count 
                FROM dossiers d 
                JOIN statuts st ON d.statut_id = st.id 
                GROUP BY st.libelle
            ");
            $stmt->execute();
            $dossiers_par_statut = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $statuts_text = "";
            foreach ($dossiers_par_statut as $statut) {
                $statuts_text .= $statut['libelle'] . ": " . $statut['count'] . " | ";
            }
            
            // Dossiers par type
            $stmt = $pdo->prepare("
                SELECT td.libelle, COUNT(*) as count 
                FROM dossiers d 
                JOIN types_dossier td ON d.type_id = td.id 
                GROUP BY td.libelle
            ");
            $stmt->execute();
            $dossiers_par_type = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $types_text = "";
            foreach ($dossiers_par_type as $type_row) {
                $types_text .= $type_row['libelle'] . ": " . $type_row['count'] . " | ";
            }
            
            $donnees['lignes'] = [
                ['Métrique' => 'Total Gestionnaires', 'Valeur' => $total_gestionnaires['total']],
                ['Métrique' => 'Total Dossiers', 'Valeur' => $total_dossiers['total']],
                ['Métrique' => 'Total Services', 'Valeur' => $total_services['total']],
                ['Métrique' => 'Total Pièces Jointes', 'Valeur' => $total_pieces['total']],
                ['Métrique' => 'Total Types de Situation', 'Valeur' => $total_types_situation['total']],
                ['Métrique' => 'Dossiers par Type', 'Valeur' => rtrim($types_text, ' | ')],
                ['Métrique' => 'Dossiers par Statut', 'Valeur' => rtrim($statuts_text, ' | ')],
                ['Métrique' => 'Date du rapport', 'Valeur' => date('d/m/Y H:i')],
                ['Métrique' => 'Généré par', 'Valeur' => $_SESSION['nom_complet']]
            ];
            break;
    }
    
    return $donnees;
}

// Fonction pour générer le PDF (reste identique)
function genererPDF($donnees, $type_rapport, $date_debut, $date_fin, $format) {
    try {
        $dompdf = new Dompdf\Dompdf();
        
        // Configurer les options
        $dompdf->set_option('isRemoteEnabled', true);
        $dompdf->set_option('isHtml5ParserEnabled', true);
        $dompdf->set_option('defaultFont', 'Helvetica');
        
        $html = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>' . htmlspecialchars($donnees['titre']) . '</title>
            <style>
                body { font-family: Helvetica, Arial, sans-serif; margin: 20px; color: #333; }
                .header { text-align: center; margin-bottom: 30px; border-bottom: 2px solid #2E7D32; padding-bottom: 10px; }
                .title { color: #2E7D32; font-size: 24px; margin: 0; }
                .subtitle { color: #666; font-size: 14px; margin: 5px 0; }
                .info-box { background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0; }
                .statistics { display: flex; justify-content: space-between; flex-wrap: wrap; margin: 20px 0; }
                .stat-item { background: #e8f5e8; padding: 10px 15px; border-radius: 5px; margin: 5px; flex: 1; min-width: 150px; text-align: center; }
                table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 12px; }
                th { background: #2E7D32; color: white; padding: 8px; text-align: left; font-size: 11px; }
                td { padding: 6px; border-bottom: 1px solid #ddd; font-size: 11px; }
                tr:nth-child(even) { background: #f9f9f9; }
                .footer { margin-top: 30px; text-align: center; color: #666; font-size: 10px; border-top: 1px solid #ddd; padding-top: 10px; }
                .logo { text-align: center; margin-bottom: 20px; }
            </style>
        </head>
        <body>
            <div class="logo">
                <h2 style="color: #2E7D32; margin: 0;">CI-ENERGIES</h2>
                <p style="color: #666; margin: 5px 0;">Système d\'Intégrité - Rapports Administratifs</p>
            </div>
            
            <div class="header">
                <h1 class="title">' . htmlspecialchars($donnees['titre']) . '</h1>
                <p class="subtitle">Période : ' . date('d/m/Y', strtotime($date_debut)) . ' - ' . date('d/m/Y', strtotime($date_fin)) . '</p>
                <p class="subtitle">Généré le : ' . date('d/m/Y à H:i') . '</p>
            </div>';
        
        // Ajouter les statistiques si disponibles
        if (!empty($donnees['statistiques'])) {
            $html .= '<div class="statistics">';
            foreach ($donnees['statistiques'] as $label => $valeur) {
                $html .= '<div class="stat-item">
                    <strong>' . htmlspecialchars($label) . '</strong><br>
                    <span style="font-size: 16px; color: #2E7D32;">' . htmlspecialchars($valeur) . '</span>
                </div>';
            }
            $html .= '</div>';
        }
        
        // Ajouter le tableau de données
        if (!empty($donnees['lignes']) && !empty($donnees['colonnes'])) {
            $html .= '<table>
                <thead>
                    <tr>';
            foreach ($donnees['colonnes'] as $colonne) {
                $html .= '<th>' . htmlspecialchars($colonne) . '</th>';
            }
            $html .= '</tr>
                </thead>
                <tbody>';
            
            foreach ($donnees['lignes'] as $ligne) {
                $html .= '<tr>';
                foreach ($ligne as $cellule) {
                    // Formater les valeurs booléennes
                    if ($cellule === true || $cellule === 1) $cellule = 'Oui';
                    if ($cellule === false || $cellule === 0) $cellule = 'Non';
                    $html .= '<td>' . htmlspecialchars($cellule) . '</td>';
                }
                $html .= '</tr>';
            }
            
            $html .= '</tbody>
            </table>';
        }
        
        $html .= '
            <div class="footer">
                <p>Rapport généré automatiquement par le système d\'intégrité CI-ENERGIES</p>
                <p>© ' . date('Y') . ' CI-ENERGIES - Tous droits réservés - Document confidentiel</p>
            </div>
        </body>
        </html>';
        
        $dompdf->loadHtml($html);
        $dompdf->setPaper($format, 'portrait');
        $dompdf->render();
        
        // Générer un nom de fichier
        $filename = 'rapport_' . $type_rapport . '_' . date('Y-m-d') . '.pdf';
        
        // Output du PDF
        $dompdf->stream($filename, ['Attachment' => true]);
        
    } catch (Exception $e) {
        die("Erreur lors de la génération du PDF : " . $e->getMessage() . 
            "<br><br>Veuillez vérifier que DomPDF est correctement installé via Composer.");
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Génération de Rapports | CI-ENERGIES</title>
    
    <!-- Bootstrap 5.3.3 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Icônes Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    
    <style>
        .report-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 25px rgba(0,0,0,0.1);
            border: none;
        }
        .form-label {
            font-weight: 600;
            color: #2E7D32;
        }
        .btn-generate {
            background: linear-gradient(135deg, #2E7D32, #4CAF50);
            border: none;
            padding: 12px 30px;
            font-weight: 600;
        }
        .preview-box {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 2rem;
            text-align: center;
        }
    </style>
</head>
<body>
    <?php include 'admin_header.php'; ?>
    
    <div class="container-fluid p-4">
        <!-- En-tête de page -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-1">
                    <i class="bi bi-file-earmark-pdf text-primary me-2"></i>
                    Génération de Rapports
                </h1>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item"><a href="dashboard.php">Tableau de bord</a></li>
                        <li class="breadcrumb-item active">Rapports PDF</li>
                    </ol>
                </nav>
            </div>
            <div>
                <span class="badge bg-success">PDF</span>
            </div>
        </div>

        <?php if (!$dompdfAvailable): ?>
        <div class="alert alert-warning mb-4">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <h6 class="alert-heading mb-1">DompDF non installé</h6>
                    <p class="mb-0">Pour générer des PDF, veuillez installer DomPDF via Composer :</p>
                    <code class="d-inline-block mt-1 p-2 bg-dark text-white rounded">composer require dompdf/dompdf</code>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="row g-4">
            <div class="col-lg-8">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-bottom">
                        <h5 class="card-title mb-0">
                            <i class="bi bi-gear me-2"></i>
                            Paramètres du Rapport
                        </h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" id="reportForm">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label for="type_rapport" class="form-label fw-semibold">Type de rapport</label>
                                    <select class="form-select" id="type_rapport" name="type_rapport" required>
                                        <option value="general">Rapport Général</option>
                                        <option value="gestionnaires">Rapport Gestionnaires</option>
                                        <option value="dossiers">Rapport Dossiers</option>
                                        <option value="services">Rapport Services</option>
                                        <option value="types_situation">Rapport Types de Situation</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-3">
                                    <label for="date_debut" class="form-label fw-semibold">Date de début</label>
                                    <input type="date" class="form-control" id="date_debut" name="date_debut" 
                                           value="<?= date('Y-m-01') ?>" required>
                                </div>
                                
                                <div class="col-md-3">
                                    <label for="date_fin" class="form-label fw-semibold">Date de fin</label>
                                    <input type="date" class="form-control" id="date_fin" name="date_fin" 
                                           value="<?= date('Y-m-d') ?>" required>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="format" class="form-label fw-semibold">Format de page</label>
                                    <select class="form-select" id="format" name="format">
                                        <option value="A4">A4 (Standard)</option>
                                        <option value="A3">A3 (Grand format)</option>
                                        <option value="letter">Letter (US)</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="mt-4 pt-3 border-top">
                                <button type="submit" name="generer_pdf" class="btn btn-primary" <?= !$dompdfAvailable ? 'disabled' : '' ?>>
                                    <i class="bi bi-file-earmark-pdf me-2"></i>
                                    <?= $dompdfAvailable ? 'Générer le PDF' : 'DompDF non installé' ?>
                                </button>
                                <a href="dashboard.php" class="btn btn-secondary">Annuler</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-bottom">
                        <h5 class="card-title mb-0">
                            <i class="bi bi-info-circle me-2"></i>
                            Informations
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="preview-box mb-4">
                            <i class="bi bi-file-earmark-pdf display-4 text-muted mb-3"></i>
                            <h6>Aperçu du PDF</h6>
                            <p class="text-muted small">
                                Le rapport sera généré au format PDF avec mise en forme professionnelle.
                            </p>
                        </div>
                        
                        <div class="alert alert-info">
                            <h6 class="alert-heading">Types de rapports disponibles</h6>
                            <ul class="small mb-0">
                                <li><strong>Général</strong> : Statistiques globales du système</li>
                                <li><strong>Gestionnaires</strong> : Liste des utilisateurs administrateurs</li>
                                <li><strong>Dossiers</strong> : Alertes et signalements reçus</li>
                                <li><strong>Services</strong> : Unités organisationnelles</li>
                                <li><strong>Types de Situation</strong> : Catégories de signalements</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include 'admin_footer.php'; ?>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Validation des dates
        document.getElementById('reportForm').addEventListener('submit', function(e) {
            const dateDebut = new Date(document.getElementById('date_debut').value);
            const dateFin = new Date(document.getElementById('date_fin').value);
            
            if (dateDebut > dateFin) {
                e.preventDefault();
                alert('La date de début ne peut pas être après la date de fin.');
                return false;
            }
        });
        
        // Mettre à jour la date de fin max à aujourd'hui
        document.getElementById('date_fin').max = new Date().toISOString().split('T')[0];
    </script>
</body>
</html>