<?php
require_once 'connexion/auth.php'; 

$debug_message = ""; 

// ==========================================
// 1. MISE À JOUR DE LA BASE DE DONNÉES
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS info_poubelles (
        id INT PRIMARY KEY,
        type_bac VARCHAR(50) NOT NULL,
        jour_collecte TEXT,
        texte_dessus TEXT,
        texte_dessous TEXT,
        image VARCHAR(255) DEFAULT 'default.jpg'
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $colonnes_a_ajouter = [
        'regle_recurrence' => "VARCHAR(50) DEFAULT NULL",
        'dates_annulees' => "TEXT DEFAULT NULL",
        'image' => "VARCHAR(255) DEFAULT 'default.jpg'",
        'image2' => "VARCHAR(255) DEFAULT 'default.jpg'"
    ];

    foreach ($colonnes_a_ajouter as $nom_colonne => $type_colonne) {
        try {
            $pdo->exec("ALTER TABLE info_poubelles ADD COLUMN $nom_colonne $type_colonne");
        } catch (PDOException $e) { /* Si la colonne existe, on passe */ }
    }

    $check = $pdo->query("SELECT COUNT(*) FROM info_poubelles")->fetchColumn();
    if ($check < 5) {
        $default_data = [
            [1, 'Ordures Ménagères', '', 'Déchets non recyclables...', 'Sortir les sacs la veille.', 'default.jpg', 'default.jpg'],
            [2, 'Tri Sélectif', '', 'Emballages, plastiques, métaux...', 'En vrac dans le bac jaune.', 'default.jpg', 'default.jpg'],
            [3, 'Encombrants', '', 'Meubles, matelas, ferraille...', 'Dépôt la veille au soir uniquement.', 'default.jpg', 'default.jpg'],
            [4, 'Déchets Verts', '', 'Tontes, feuilles, petits branchages...', 'Utilisez des sacs biodégradables ou bacs ouverts.', 'default.jpg', 'default.jpg'],
            [5, 'Apports Volontaires', '', 'Verre, Papier, Carton', 'Points de collecte : Rue du Stade et Parking Mairie.', 'default.jpg', 'default.jpg']
        ];
        foreach ($default_data as $row) {
            $stmt = $pdo->prepare("INSERT IGNORE INTO info_poubelles (id, type_bac, jour_collecte, texte_dessus, texte_dessous, image, image2) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute($row);
        }
    }

    $pdo->exec("UPDATE info_poubelles SET regle_recurrence = 'friday_all' WHERE id IN (1)"); 
    $pdo->exec("UPDATE info_poubelles SET regle_recurrence = 'wed_even' WHERE id = 2"); 
    $pdo->exec("UPDATE info_poubelles SET regle_recurrence = NULL WHERE id IN (3, 4, 5)"); 
} catch (PDOException $e) {
    $debug_message .= "<b>Erreur BDD au démarrage :</b> " . $e->getMessage() . "<br>";
}

// ==========================================
// 2. GESTION DES IMAGES
// ==========================================
$dossier_images_dechets = 'images/dechets/';

function traiterImageDechets($file, $dossier) {
    if ($file['error'] !== UPLOAD_ERR_OK) return false;
    
    if (!is_dir($dossier)) { 
        if (!@mkdir($dossier, 0755, true)) return false;
    }

    $tmp_name = $file['tmp_name'];
    $name = basename($file['name']);
    $size = $file['size'];
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    
    if ($size > 10485760) return false;

    $allowed_ext = ['jpg', 'jpeg', 'png', 'webp'];
    if (!in_array($ext, $allowed_ext)) return false;

    $safe_name = preg_replace('/[^a-zA-Z0-9_-]/', '', pathinfo($name, PATHINFO_FILENAME));
    $new_name = uniqid() . '_' . substr($safe_name, 0, 20) . '.' . $ext; 
    $dest_path = $dossier . $new_name;

    if (move_uploaded_file($tmp_name, $dest_path)) {
        return $new_name;
    }
    return false;
}

// ==========================================
// 3. MOTEUR CALENDRIER & JOURS FÉRIÉS (ÉVOLUTION 1ER JUIN)
// ==========================================
function getJoursFeries($year) {
    if (function_exists('easter_date')) {
        $easterDate  = easter_date($year);
    } else {
        $base = new DateTime("$year-03-21");
        $days = easter_days($year);
        $easterDate = $base->add(new DateInterval("P{$days}D"))->getTimestamp();
    }
    
    $easterDay   = date('j', $easterDate);
    $easterMonth = date('n', $easterDate);
    $easterYear  = date('Y', $easterDate);

    return [
        "$year-01-01", "$year-05-01", "$year-05-08", "$year-07-14", "$year-08-15",
        "$year-11-01", "$year-11-11", "$year-12-25",
        date('Y-m-d', mktime(0, 0, 0, $easterMonth, $easterDay + 1, $easterYear)), 
        date('Y-m-d', mktime(0, 0, 0, $easterMonth, $easterDay + 39, $easterYear)), 
        date('Y-m-d', mktime(0, 0, 0, $easterMonth, $easterDay + 50, $easterYear)), 
    ];
}

function getActualCollectionDateOld($baseDateStr) {
    $shift = 0;
    $timestamp = strtotime($baseDateStr);
    $dayOfWeek = date('N', $timestamp); 
    $feries = getJoursFeries(date('Y', $timestamp));
    
    for ($i = 1; $i <= $dayOfWeek; $i++) {
        $offset = $i - $dayOfWeek;
        $checkDate = date('Y-m-d', strtotime("$offset days", $timestamp));
        if (in_array($checkDate, $feries)) {
            $shift++; 
        }
    }
    
    if ($shift > 0) {
        return date('Y-m-d', strtotime("+$shift days", $timestamp));
    }
    return $baseDateStr;
}

function getActualCollectionDateNew($baseDateStr) {
    $timestamp = strtotime($baseDateStr);
    $year = date('Y', $timestamp);
    $feries_restreints = ["$year-01-01", "$year-05-01", "$year-12-25"];
    
    // Vérifier si un de ces 3 jours tombe le Lundi ou Mardi de cette semaine
    $monday = date('Y-m-d', strtotime('monday this week', $timestamp));
    $tuesday = date('Y-m-d', strtotime('tuesday this week', $timestamp));
    
    if (in_array($monday, $feries_restreints) || in_array($tuesday, $feries_restreints)) {
        return date('Y-m-d', strtotime($baseDateStr . ' +1 day'));
    }
    return $baseDateStr;
}

function getDynamicDates($rule, $count = 4) {
    $dates = [];
    $current = strtotime('-3 days'); 
    $today = date('Y-m-d');
    $date_bascule = '2026-06-01';
    $limit = 0;
    
    while (count($dates) < $count && $limit < 100) {
        $limit++;
        $dateStr = date('Y-m-d', $current);
        $dayOfWeek = date('w', $current); 
        $weekNum = date('W', $current); 
        
        $isMatch = false;
        $shiftedDate = $dateStr;
        $is_new_rule = ($dateStr >= $date_bascule);

        if (!$is_new_rule) {
            // --- ANCIENNES RÈGLES ---
            if ($rule === 'friday_all' && $dayOfWeek == 5) $isMatch = true; 
            if ($rule === 'wed_even' && $dayOfWeek == 3 && $weekNum % 2 == 0) $isMatch = true; 
            if ($isMatch) $shiftedDate = getActualCollectionDateOld($dateStr);
        } else {
            // --- NOUVELLES RÈGLES ---
            if ($rule === 'friday_all' && $dayOfWeek == 2) $isMatch = true; // OM Mardi
            if ($rule === 'wed_even' && $dayOfWeek == 2 && $weekNum % 2 != 0) $isMatch = true; // Tri Mardi IMPAIR
            if ($isMatch) $shiftedDate = getActualCollectionDateNew($dateStr);
        }

        if ($isMatch && $shiftedDate >= $today) {
            $dates[] = ['date' => $shiftedDate, 'shifted' => ($shiftedDate !== $dateStr), 'is_new_rule' => $is_new_rule];
        }
        $current = strtotime('+1 day', $current);
    }
    return $dates;
}

function getFourthThursdaysOf($year) {
    $dates = [];
    $months = [1, 4, 7, 10]; 
    $today = new DateTime();
    
    foreach ($months as $m) {
        $date = new DateTime("$year-$m-01");
        while ($date->format('N') != 4) { $date->modify('+1 day'); }
        $date->modify('+3 weeks');
        
        if ($date >= $today) { $dates[] = $date->format('Y-m-d'); }
    }
    return $dates;
}

function formatTagToLongDate($dateStr) {
    if (empty(trim($dateStr))) return "";
    $timestamp = strtotime($dateStr);
    $jours = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
    $mois = ['', 'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];
    return $jours[date('w', $timestamp)] . ' ' . date('d', $timestamp) . ' ' . $mois[(int)date('m', $timestamp)] . ' ' . date('Y', $timestamp);
}

$can_edit = isLogged() && (hasRole('Administrateur') || hasRole('Maire') || hasRole('Adjoint') || hasRole('Editeur'));

// ==========================================
// 4. TRAITEMENTS DES ACTIONS ADMIN
// ==========================================
if ($can_edit && isset($_POST['edit_poubelle'])) {
    try {
        $id = (int)$_POST['poubelle_id'];
        $dessus = trim($_POST['texte_dessus']);
        $dessous = trim($_POST['texte_dessous']);
        
        $sql_parts = [];
        $params = [$dessus, $dessous];

        if (!empty($_FILES['image_dechet']['name'])) {
            $uploaded_img = traiterImageDechets($_FILES['image_dechet'], $dossier_images_dechets);
            if ($uploaded_img) {
                $old = $pdo->query("SELECT image FROM info_poubelles WHERE id = $id")->fetchColumn();
                if ($old && $old != 'default.jpg' && file_exists($dossier_images_dechets . $old)) { 
                    @unlink($dossier_images_dechets . $old); 
                }
                $sql_parts[] = "image = ?";
                $params[] = $uploaded_img;
            }
        }

        if (!empty($_FILES['image_dechet2']['name'])) {
            $uploaded_img2 = traiterImageDechets($_FILES['image_dechet2'], $dossier_images_dechets);
            if ($uploaded_img2) {
                $old2 = $pdo->query("SELECT image2 FROM info_poubelles WHERE id = $id")->fetchColumn();
                if ($old2 && $old2 != 'default.jpg' && file_exists($dossier_images_dechets . $old2)) { 
                    @unlink($dossier_images_dechets . $old2); 
                }
                $sql_parts[] = "image2 = ?";
                $params[] = $uploaded_img2;
            }
        }
        
        $image_update_sql = !empty($sql_parts) ? ", " . implode(", ", $sql_parts) : "";
        $params[] = $id;
        
        $stmt = $pdo->prepare("UPDATE info_poubelles SET texte_dessus = ?, texte_dessous = ? $image_update_sql WHERE id = ?");
        $stmt->execute($params);
    } catch (Exception $e) {
        $debug_message .= "<b>Erreur lors de la mise à jour :</b> " . $e->getMessage() . "<br>";
    }
}

if ($can_edit && isset($_POST['btn_toggle_date'])) {
    try {
        $id = (int)$_POST['poubelle_id'];
        $dateToToggle = trim($_POST['toggle_date']);
        
        $stmt = $pdo->prepare("SELECT dates_annulees FROM info_poubelles WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        $annulees = $row['dates_annulees'] ? explode(',', $row['dates_annulees']) : [];
        
        if (in_array($dateToToggle, $annulees)) {
            $annulees = array_diff($annulees, [$dateToToggle]);
        } else {
            $annulees[] = $dateToToggle;
        }
        
        $stmt = $pdo->prepare("UPDATE info_poubelles SET dates_annulees = ? WHERE id = ?");
        $stmt->execute([implode(',', $annulees), $id]);
    } catch (Exception $e) {
        $debug_message .= "<b>Erreur Rayer date :</b> " . $e->getMessage() . "<br>";
    }
}

$poubelles = $pdo->query("SELECT * FROM info_poubelles ORDER BY id ASC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Déchets - Saint Vaast en Chaussée</title>
    <link rel="stylesheet" href="css/global.css">
    <style>
        .dechets-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 20px; }
        .card-poubelle { padding: 25px; border-radius: 20px; text-align: center; border: 2px solid transparent; position: relative; display: flex; flex-direction: column; justify-content: space-between; }
        .card-large { grid-column: span 3; } 
        .card-small { grid-column: span 2; } 

        .dates-list { display: flex; flex-direction: column; gap: 8px; margin: 15px 0; }
        .date-row { background: white; padding: 10px; border-radius: 12px; font-weight: bold; font-size: 1em; box-shadow: 0 2px 4px rgba(0,0,0,0.03); border-left: 5px solid transparent; display: flex; justify-content: space-between; align-items: center; }

        .btn-edit { position: absolute; top: 10px; right: 10px; background: white; border: 1px solid #ddd; padding: 5px 10px; border-radius: 12px; cursor: pointer; font-size: 0.75em; }

        .card-1 { background: #f1f8f1; border-color: #4a7c44; } .card-1 .date-row { border-left-color: #4a7c44; color: #4a7c44; }
        .card-2 { background: #fffde7; border-color: #fbc02d; } .card-2 .date-row { border-left-color: #fbc02d; color: #f57f17; }
        .card-3 { background: #fdfbf7; border-color: #8d6e63; } .card-3 .date-row { border-left-color: #8d6e63; color: #5d4037; }
        .card-4 { background: #f1fcf1; border-color: #8bc34a; } .card-4 .date-row { border-left-color: #8bc34a; color: #689f38; }
        .card-5 { background: #f3f7fd; border-color: #2196f3; }

        .text-top { color:#666; font-size:0.9em; margin-bottom:10px; flex-grow:1; }
        .text-bottom { color:#444; font-weight:500; font-size:0.9em; border-top: 1px solid rgba(0,0,0,0.05); padding-top:15px; margin-top:15px; }

        .canceled span { text-decoration: line-through; opacity: 0.5; }
        .canceled { border-left-color: #dc3545 !important; background: #fdf5f5; color: #dc3545 !important;}
        .btn-rayer { background: #fee; color: #c33; border: 1px solid #fcc; padding: 5px 10px; border-radius: 8px; cursor: pointer; font-size: 0.85em; font-weight: bold; transition: 0.3s; margin-left: 10px; }
        .btn-rayer:hover { background: #fcc; }
        .btn-retablir { background: #e1ede0; color: #28a745; border-color: #c8e6c9; }
        .btn-retablir:hover { background: #c8e6c9; }
        
        .horaire-badge { display: inline-block; background: #eee; color: #555; font-size: 0.8em; padding: 3px 8px; border-radius: 8px; margin-top: 5px; font-weight: normal; }

        /* CAROUSEL FLÈCHES */
        .carousel-btn { position:absolute; top:50%; transform:translateY(-50%); background:#fff; border:1px solid #ccc; border-radius:50%; width:30px; height:30px; cursor:pointer; z-index:10; font-weight:bold; display:flex; align-items:center; justify-content:center; color:#333; transition: 0.3s; }
        .carousel-btn.left { left:-15px; }
        .carousel-btn.right { right:-15px; }
        .carousel-btn:hover { background:#f0f4f0; color:#4a7c44; border-color:#4a7c44; }

        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); align-items: center; justify-content: center; }
        .modal-content { background: white; padding: 30px; border-radius: 25px; width: 95%; max-width: 500px; }
        .modal-content textarea, .modal-content input { width: 100%; padding: 12px; margin: 8px 0; border: 2px solid #f0f4f0; border-radius: 15px; box-sizing: border-box; font-family: inherit; }

        .img-zoom-modal { display: none; position: fixed; z-index: 3000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.8); justify-content: center; align-items: center; }
        .img-zoom-content { max-width: 90%; max-height: 90%; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.3); cursor: zoom-out; }

        @media (max-width: 900px) { .card-large, .card-small { grid-column: span 6; } }
    </style>
</head>
<body>
<div class="site-container">
    <img src="images/banniere.png" alt="Bannière" class="banner-img">
    <nav><?php include 'includes/menu.php'; ?></nav>

    <main class="main-wrapper">
        
        <?php if(!empty($debug_message)): ?>
            <div style="background: #ffebee; border: 2px solid #ef5350; padding: 20px; border-radius: 15px; margin-bottom: 20px; color: #c62828;">
                <h3 style="margin-top: 0; color: #c62828;">⚠️ Rapport système</h3>
                <?php echo $debug_message; ?>
            </div>
        <?php endif; ?>

        <h2 style="text-align:center; color:var(--nature-vert, #4a7c44); margin-top: 0; margin-bottom:30px;">Gestion des déchets</h2>
        
        <div class="dechets-grid">
            <?php foreach($poubelles as $p): 
                $isTop = ($p['id'] <= 2);
                $icons = [1=>'🗑️', 2=>'♻️', 3=>'🛋️', 4=>'🌿', 5=>'🍾'];
                
                $annulees = (isset($p['dates_annulees']) && $p['dates_annulees']) ? explode(',', $p['dates_annulees']) : [];
                $img1 = isset($p['image']) && $p['image'] != 'default.jpg' ? $p['image'] : '';
                $img2 = isset($p['image2']) && $p['image2'] != 'default.jpg' ? $p['image2'] : '';
            ?>
            <div class="card-poubelle card-<?php echo $p['id']; ?> <?php echo $isTop ? 'card-large' : 'card-small'; ?>">
                <?php if($can_edit): ?>
                    <button class="btn-edit" onclick="openModal(<?php echo htmlspecialchars(json_encode($p), ENT_QUOTES, 'UTF-8'); ?>)">✎ Éditer</button>
                <?php endif; ?>
                
                <div>
                    <div style="font-size:2.5em;"><?php echo $icons[$p['id']]; ?></div>
                    <h3 style="margin:10px 0; font-size:1.3em; color: #333; border: none; padding: 0;"><?php echo htmlspecialchars($p['type_bac']); ?></h3>
                </div>
                
                <p class="text-top"><?php echo nl2br(htmlspecialchars($p['texte_dessus'] ?: '')); ?></p>
                
                <div class="dates-list">
                    <?php if ($p['id'] == 3): ?>
                        <?php 
                        $encumbrancesDates = getFourthThursdaysOf(date('Y'));
                        foreach ($encumbrancesDates as $dStr):
                            $isCanceled = in_array($dStr, $annulees);
                        ?>
                            <div class="date-row <?= $isCanceled ? 'canceled' : '' ?>">
                                <span style="text-align: left;"><?= formatTagToLongDate($dStr) ?></span>
                                <?php if($can_edit): ?>
                                    <form method="POST" style="margin: 0;">
                                        <input type="hidden" name="poubelle_id" value="<?= $p['id'] ?>">
                                        <input type="hidden" name="toggle_date" value="<?= $dStr ?>">
                                        <button type="submit" name="btn_toggle_date" class="btn-rayer <?= $isCanceled ? 'btn-retablir' : '' ?>">
                                            <?= $isCanceled ? 'Rétablir' : 'Rayer' ?>
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>

                    <?php elseif ($p['id'] == 4): ?>
                        <div style="margin: 15px auto; text-align: center;">
                            <?php if ($img1): ?>
                                <img src="images/dechets/<?= htmlspecialchars($img1) ?>" alt="Plan" style="max-width: 100%; height: 150px; object-fit: cover; border-radius: 12px; border: 1px solid #ccc; cursor: zoom-in;" onclick="zoomImage(this.src)">
                                <span style="font-size: 0.85em; color: #666; margin-top: 5px; display: block; font-style: italic;">Cliquez sur l'image pour zoomer</span>
                            <?php else: ?>
                                <div style="color: #888; font-style: italic; padding: 20px; background: rgba(0,0,0,0.03); border-radius: 12px;">Aucun plan joint</div>
                            <?php endif; ?>
                        </div>

                    <?php elseif ($p['id'] == 5): ?>
                        <div style="margin: 15px auto; text-align: center; position: relative;">
                            <?php if ($img1 || $img2): ?>
                                <div style="position:relative; width: 100%; max-width: 250px; margin: 0 auto;">
                                    
                                    <?php if ($img1 && $img2): ?>
                                        <button type="button" onclick="toggleCarousel(<?= $p['id'] ?>)" class="carousel-btn left">&#10094;</button>
                                    <?php endif; ?>
                                    
                                    <?php if ($img1): ?>
                                        <img id="img-<?= $p['id'] ?>-1" src="images/dechets/<?= htmlspecialchars($img1) ?>" style="display:block; width:100%; height:150px; object-fit:cover; border-radius:12px; border:1px solid #ccc; cursor:zoom-in;" onclick="zoomImage(this.src)">
                                    <?php endif; ?>
                                    
                                    <?php if ($img2): ?>
                                        <img id="img-<?= $p['id'] ?>-2" src="images/dechets/<?= htmlspecialchars($img2) ?>" style="display:<?= $img1 ? 'none' : 'block' ?>; width:100%; height:150px; object-fit:cover; border-radius:12px; border:1px solid #ccc; cursor:zoom-in;" onclick="zoomImage(this.src)">
                                    <?php endif; ?>

                                    <?php if ($img1 && $img2): ?>
                                        <button type="button" onclick="toggleCarousel(<?= $p['id'] ?>)" class="carousel-btn right">&#10095;</button>
                                    <?php endif; ?>
                                    
                                </div>
                                <span style="font-size: 0.85em; color: #666; margin-top: 5px; display: block; font-style: italic;">Cliquez sur l'image pour zoomer</span>
                            <?php else: ?>
                                <div style="color: #888; font-style: italic; padding: 20px; background: rgba(0,0,0,0.03); border-radius: 12px;">Aucun plan joint</div>
                            <?php endif; ?>
                        </div>

                    <?php elseif (isset($p['regle_recurrence']) && $p['regle_recurrence']): ?>
                        <?php 
                        $dynamicDates = getDynamicDates($p['regle_recurrence'], 4);
                        foreach($dynamicDates as $dd):
                            $dStr = $dd['date'];
                            $isCanceled = in_array($dStr, $annulees);
                            
                            // Définition de l'horaire pour la nouvelle règle
                            $horaire = "";
                            if ($dd['is_new_rule']) {
                                if ($p['id'] == 1) $horaire = "Collecte l'après-midi (jusqu'à 20h)";
                                if ($p['id'] == 2) $horaire = "Collecte le matin";
                            }
                        ?>
                            <div class="date-row <?= $isCanceled ? 'canceled' : '' ?>">
                                <span style="text-align: left; line-height: 1.3;">
                                    <?= formatTagToLongDate($dStr) ?>
                                    <?php if($dd['shifted']): ?><br><small style="color:#e67e22; font-size: 0.8em;">(Décalé suite à un jour férié)</small><?php endif; ?>
                                    <?php if($horaire): ?><br><span class="horaire-badge">🕒 <?= $horaire ?></span><?php endif; ?>
                                </span>
                                <?php if($can_edit): ?>
                                    <form method="POST" style="margin: 0;">
                                        <input type="hidden" name="poubelle_id" value="<?= $p['id'] ?>">
                                        <input type="hidden" name="toggle_date" value="<?= $dStr ?>">
                                        <button type="submit" name="btn_toggle_date" class="btn-rayer <?= $isCanceled ? 'btn-retablir' : '' ?>">
                                            <?= $isCanceled ? 'Rétablir' : 'Rayer' ?>
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <p class="text-bottom"><?php echo nl2br(htmlspecialchars($p['texte_dessous'] ?: '')); ?></p>
            </div>
            <?php endforeach; ?>
        </div>
    </main>
</div>

<div id="editModal" class="modal">
    <div class="modal-content">
        <h3 id="mt" style="margin-top:0; color:var(--nature-vert, #4a7c44);">Modifier</h3>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="poubelle_id" id="mid">
            
            <label id="lbl_dessus" style="font-weight: bold;">Description :</label>
            <textarea name="texte_dessus" id="md" rows="3"></textarea>

            <label id="lbl_dessous" style="margin-top:10px; display:block; font-weight: bold;">Consignes :</label>
            <textarea name="texte_dessous" id="ms" rows="3"></textarea>

            <div id="image_section_1" style="margin-top: 15px; display: none;">
                <label id="lbl_img_1" style="font-weight: bold;">Plan ou image :</label>
                <input type="file" name="image_dechet" accept="image/png, image/jpeg, image/jpg, image/webp" capture="environment">
            </div>

            <div id="image_section_2" style="margin-top: 10px; display: none;">
                <label style="font-weight: bold;">Plan 2ème Point de collecte :</label>
                <input type="file" name="image_dechet2" accept="image/png, image/jpeg, image/jpg, image/webp" capture="environment">
            </div>
            
            <button type="submit" name="edit_poubelle" style="background:var(--nature-vert, #4a7c44); color:white; border:none; padding:12px; width:100%; border-radius:20px; font-weight:bold; cursor:pointer; margin-top:15px;">Enregistrer</button>
            <button type="button" onclick="closeModal()" style="background:#999; color:white; border:none; padding:10px; width:100%; border-radius:20px; margin-top:10px; cursor:pointer;">Annuler</button>
        </form>
    </div>
</div>

<div id="imageZoomModal" class="img-zoom-modal" onclick="closeZoom()">
    <img id="zoomedImg" class="img-zoom-content">
</div>

<script>
    function openModal(data) {
        document.getElementById('mid').value = data.id;
        document.getElementById('md').value = data.texte_dessus;
        document.getElementById('ms').value = data.texte_dessous;
        
        const imgSec1 = document.getElementById('image_section_1');
        const imgSec2 = document.getElementById('image_section_2');
        const lbl1 = document.getElementById('lbl_img_1');

        if (data.id == 4) {
            imgSec1.style.display = 'block';
            lbl1.innerText = "Plan de la benne :";
            imgSec2.style.display = 'none';
        } else if (data.id == 5) {
            imgSec1.style.display = 'block';
            lbl1.innerText = "Plan Point de collecte 1 :";
            imgSec2.style.display = 'block';
        } else {
            imgSec1.style.display = 'none';
            imgSec2.style.display = 'none';
        }

        document.getElementById('editModal').style.display = 'flex';
    }

    function closeModal() { document.getElementById('editModal').style.display = 'none'; }
    window.onclick = function(e) { if(e.target.id == 'editModal') closeModal(); }

    function zoomImage(src) {
        document.getElementById('zoomedImg').src = src;
        document.getElementById('imageZoomModal').style.display = 'flex';
    }

    function closeZoom() {
        document.getElementById('imageZoomModal').style.display = 'none';
    }

    function toggleCarousel(id) {
        const img1 = document.getElementById('img-' + id + '-1');
        const img2 = document.getElementById('img-' + id + '-2');
        if (img1 && img2) {
            if (img1.style.display === 'none') {
                img1.style.display = 'block';
                img2.style.display = 'none';
            } else {
                img1.style.display = 'none';
                img2.style.display = 'block';
            }
        }
    }
</script>
</body>
</html>