<?php
// Démarrer la session
session_start();

// Vérifie si l'utilisateur est connecté
$isAdminLoggedIn = isset($_SESSION['user_id']);

// Inclusion de la configuration
include 'config.php';

$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Erreur de connexion : " . $conn->connect_error);
}
$numEtape = isset($_GET['numEtape']) && $_GET['numEtape'] !== '' ? intval($_GET['numEtape']) : null;
$dateEtape = isset($_GET['dateEtape']) && $_GET['dateEtape'] !== '' ? $_GET['dateEtape'] : null;
$nomVille = isset($_GET['nomVille']) && $_GET['nomVille'] !== '' ? $_GET['nomVille'] : null;
$nomPays = isset($_GET['nomPays']) && $_GET['nomPays'] !== '' ? $_GET['nomPays'] : null;
$distanceMin = isset($_GET['distanceMin']) && $_GET['distanceMin'] !== '' ? floatval($_GET['distanceMin']) : null;
$distanceMax = isset($_GET['distanceMax']) && $_GET['distanceMax'] !== '' ? floatval($_GET['distanceMax']) : null;
$triTemps = isset($_GET['triTemps']) && $_GET['triTemps'] !== '' ? $_GET['triTemps'] : null;
$typeEtape = isset($_GET['typeEtape']) && $_GET['typeEtape'] !== '' ? $_GET['typeEtape'] : null;

$sql = "
    SELECT
        e.numEtape,
        e.dateEtape,
        e.distance,
        v1.nomVille AS villeDepart,
        v2.nomVille AS villeArrivee,
        p.nomPays,
        te.nomTypeEtape,
        MIN(CAST(pe.temps AS TIME)) AS tempsPlusRapide,
        MAX(CAST(pe.temps AS TIME)) AS tempsPlusLent
    FROM Etape e
    INNER JOIN Ville v1 ON e.numVille = v1.numVille
    INNER JOIN Ville v2 ON e.numVille_1 = v2.numVille
    INNER JOIN Pays p ON v1.codePays = p.codePays
    INNER JOIN TypeEtape te ON e.idTypeEtape = te.idTypeEtape
    LEFT JOIN Performance pe ON e.numEtape = pe.numEtape
";

$whereClauses = [];
if ($numEtape) {
    $whereClauses[] = "e.numEtape = $numEtape";
}
if ($dateEtape) {
    $whereClauses[] = "e.dateEtape = '$dateEtape'";
}
if ($nomVille) {
    $nomVille = $conn->real_escape_string($nomVille);
    $whereClauses[] = "(v1.nomVille LIKE '%$nomVille%' OR v2.nomVille LIKE '%$nomVille%')";
}
if ($nomPays) {
    $nomPays = $conn->real_escape_string($nomPays);
    $whereClauses[] = "p.nomPays LIKE '%$nomPays%'";
}
if ($distanceMin) {
    $whereClauses[] = "e.distance >= $distanceMin";
}
if ($distanceMax) {
    $whereClauses[] = "e.distance <= $distanceMax";
}
if ($typeEtape) {
    $typeEtape = $conn->real_escape_string($typeEtape);
    $whereClauses[] = "te.nomTypeEtape = '$typeEtape'";
}

if (count($whereClauses) > 0) {
    $sql .= " WHERE " . implode(" AND ", $whereClauses);
}

$orderByClause = " ORDER BY e.dateEtape ASC";
if ($triTemps === 'plusRapide') {
    $orderByClause = " ORDER BY tempsPlusRapide ASC";
} elseif ($triTemps === 'moinsRapide') {
    $orderByClause = " ORDER BY tempsPlusRapide DESC";
}
$sql .= " GROUP BY
            e.numEtape, e.dateEtape, e.distance, v1.nomVille, v2.nomVille, p.nomPays, te.nomTypeEtape
          $orderByClause;";

$result = $conn->query($sql);

$typeEtapeOptions = $conn->query("SELECT DISTINCT nomTypeEtape FROM TypeEtape");
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Liste des Étapes</title>

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="sidebar">
        <img src="logo.png" alt="Logo" class="logo">
        <a href="Index.php" class="material-icons icon">home</a>
        <a href="Coureur.php" class="material-icons icon active">directions_bike</a>
        <a href="Etape.php" class="material-icons icon">terrain</a>
        <a href="Team.php" class="material-icons icon">groups</a>
    </div>
    <div class="main">
    <h1>Étapes</h1>
    <div class="cards">
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
        </div>
    <form method="get" action="Etape.php">
        <label for="numEtape">Numéro de l'étape :</label>
        <input type="number" id="numEtape" name="numEtape" min="1" placeholder="Filtrer par numéro d'étape">
        <br><br>
        <label for="dateEtape">Date de l'étape :</label>
        <input type="date" id="dateEtape" name="dateEtape">
        <br><br>
        <label for="nomVille">Nom de la ville (départ ou arrivée) :</label>
        <input type="text" id="nomVille" name="nomVille" placeholder="Filtrer par nom de ville">
        <br><br>
        <label for="nomPays">Nom du pays :</label>
        <input type="text" id="nomPays" name="nomPays" placeholder="Filtrer par nom du pays">
        <br><br>
        <label for="distanceMin">Distance minimale :</label>
        <input type="number" id="distanceMin" name="distanceMin" step="0.01" placeholder="Min (km)">
        <br><br>
        <label for="distanceMax">Distance maximale :</label>
        <input type="number" id="distanceMax" name="distanceMax" step="0.01" placeholder="Max (km)">
        <br><br>
        <label for="typeEtape">Type d'étape :</label>
        <select id="typeEtape" name="typeEtape">
            <option value="">-- Sélectionner --</option>
            <?php while ($type = $typeEtapeOptions->fetch_assoc()): ?>
                <option value="<?=htmlspecialchars($type['nomTypeEtape'])?>"><?=htmlspecialchars($type['nomTypeEtape'])?></option>
            <?php endwhile;?>
        </select>
        <br><br>
        <label for="triTemps">Trier par temps :</label>
        <select id="triTemps" name="triTemps">
            <option value="">-- Sélectionner --</option>
            <option value="plusRapide">Temps le plus rapide en premier</option>
            <option value="moinsRapide">Temps le moins rapide en premier</option>
        </select>
        <br><br>
        <button type="submit">Filtrer</button>
        <a href="Etape.php"><button type="button">Réinitialiser</button></a>
    </form>
    <br>
    <table border="1">
        <thead>
            <tr>
                <th>Numéro de l'Étape</th>
                <th>Date</th>
                <th>Distance</th>
                <th>Ville Départ</th>
                <th>Ville Arrivée</th>
                <th>Pays</th>
                <th>Type d'Étape</th>
                <th>Temps le plus rapide</th>
                <th>Temps le plus lent</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result->num_rows > 0): ?>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?=htmlspecialchars($row['numEtape'])?></td>
                        <td><?=htmlspecialchars($row['dateEtape'])?></td>
                        <td><?=htmlspecialchars($row['distance'])?> km</td>
                        <td><?=htmlspecialchars($row['villeDepart'])?></td>
                        <td><?=htmlspecialchars($row['villeArrivee'])?></td>
                        <td><?=htmlspecialchars($row['nomPays'])?></td>
                        <td><?=htmlspecialchars($row['nomTypeEtape'])?></td>
                        <td><?=htmlspecialchars($row['tempsPlusRapide'])?></td>
                        <td><?=htmlspecialchars($row['tempsPlusLent'])?></td>
                    </tr>
                <?php endwhile;?>
            <?php else: ?>
                <tr>
                    <td colspan="9">Aucune donnée trouvée.</td>
                </tr>
            <?php endif;?>
        </tbody>
    </table>
                <br>
    <div class="cards">
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
        </div>


        <br>
        <br>
        
</div>
</body>
</html>
<style>
    body {
    margin: 0;
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
}

.sidebar {
    position: fixed;
    width: 148px;
    height: 100%;
    background-color: #f8e4a6;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 20px;
}

.sidebar .logo {
    width: 40px;
    height: 40px;
    margin-bottom: 100px;
}

.sidebar .icon {
    font-size: 36px;
    margin: 20px 0;
    color: #333;
    cursor: pointer;
    position: relative;
    text-decoration: none;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.sidebar .active {
    background-color: #fff;
    border-radius: 15%;
    color: #000;
    padding: 0;
    width: 70px;
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.main {
    margin-left: 148px;
    padding: 20px;
}

.header {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
}

.cards {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
}

.card {
    flex: 1;
    height: 150px;
    background-color: #ccc;
    border-radius: 10px;
}

.filter {
    background-color: #b8a99c;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    margin-bottom: 20px;
    cursor: pointer;
}

.table-container {
    background-color: #eaeff3;
    padding: 20px;
    border-radius: 10px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

table th, table td {
    text-align: left;
    padding: 10px;
    border-bottom: 1px solid #ddd;
}

table th {
    font-weight: bold;
}

</style>
<?php
$conn->close();
?>
<script>
        const icons = document.querySelectorAll('.sidebar .icon');

        icons.forEach(icon => {
            icon.addEventListener('click', () => {
                // Supprimer la classe active de tous les icônes
                icons.forEach(i => i.classList.remove('active'));

                // Ajouter la classe active à l'icône cliquée
                icon.classList.add('active');
            });
        });
    </script>