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

// ==========================================
// 0. ROBOT DE NETTOYAGE (INFOS LÉGALES ET ACTUALITÉS)
// ==========================================
try {
    // 0.1 Création de la colonne d'expiration pour les actualités si elle n'existe pas
    $pdo->exec("ALTER TABLE news ADD COLUMN date_fin DATE NULL AFTER date_creation");
} catch (Exception $e) { }

try {
    // Nettoyage des Infos Légales
    $stmt_clean = $pdo->query("SELECT id, fichiers_joints FROM infos_legales WHERE date_fin IS NOT NULL AND date_fin < DATE_SUB(CURDATE(), INTERVAL 1 DAY)");
    while ($row = $stmt_clean->fetch()) {
        if (!empty($row['fichiers_joints'])) {
            foreach (explode(',', $row['fichiers_joints']) as $file) {
                $path = 'datas/infos_legales/' . $file;
                if (file_exists($path)) @unlink($path);
            }
        }
        $pdo->prepare("DELETE FROM infos_legales WHERE id = ?")->execute([$row['id']]);
    }

    // Nettoyage des Actualités (News)
    $stmt_clean_news = $pdo->query("SELECT id, images FROM news WHERE date_fin IS NOT NULL AND date_fin < CURDATE()");
    while ($row = $stmt_clean_news->fetch()) {
        if (!empty($row['images'])) {
            foreach (explode(',', $row['images']) as $file) {
                $path = 'images/news/' . $file;
                if (file_exists($path)) @unlink($path);
            }
        }
        $pdo->prepare("DELETE FROM news WHERE id = ?")->execute([$row['id']]);
    }
} catch (Exception $e) { /* Ignorer au 1er lancement */ }

// Fonction pour uploader et convertir en WebP (Fichiers Légaux)
function traiterFichiersLegaux($files) {
    $noms_fichiers = [];
    $dest_dir = 'datas/infos_legales/';
    if (!is_dir($dest_dir)) @mkdir($dest_dir, 0755, true);

    if (isset($files['name']) && is_array($files['name'])) {
        for ($i = 0; $i < count($files['name']); $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $tmp_name = $files['tmp_name'][$i];
                $name = basename($files['name'][$i]);
                $size = $files['size'][$i];
                $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

                if ($size > 5242880) continue; 

                $safe_name = preg_replace('/[^a-zA-Z0-9_-]/', '', pathinfo($name, PATHINFO_FILENAME));
                $new_name = uniqid() . '_' . substr($safe_name, 0, 20);
                
                if ($ext === 'pdf') {
                    $new_name .= '.pdf';
                    if (move_uploaded_file($tmp_name, $dest_dir . $new_name)) $noms_fichiers[] = $new_name;
                } elseif (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) {
                    $new_name .= '.webp';
                    $dest_path = $dest_dir . $new_name;
                    if ($ext === 'webp') {
                        if(move_uploaded_file($tmp_name, $dest_path)) $noms_fichiers[] = $new_name;
                    } else {
                        if (function_exists('imagecreatefromjpeg')) {
                            $img = ($ext === 'png') ? @imagecreatefrompng($tmp_name) : @imagecreatefromjpeg($tmp_name);
                            if ($img) {
                                if ($ext === 'png') { imagepalettetotruecolor($img); imagealphablending($img, true); imagesavealpha($img, true); }
                                imagewebp($img, $dest_path, 80);
                                imagedestroy($img);
                                $noms_fichiers[] = $new_name;
                            }
                        }
                    }
                }
            }
        }
    }
    return implode(',', $noms_fichiers);
}

// Fonction pour uploader et convertir en WebP (Actualités)
function traiterImagesWebp($files) {
    $noms_fichiers = [];
    $dest_dir = 'images/news/';
    if (!is_dir($dest_dir)) @mkdir($dest_dir, 0755, true);

    if (isset($files['name']) && is_array($files['name'])) {
        for ($i = 0; $i < count($files['name']); $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $tmp_name = $files['tmp_name'][$i];
                $name = basename($files['name'][$i]);
                $size = $files['size'][$i];
                $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

                if ($size > 5242880) continue; 
                $allowed_ext = ['jpg', 'jpeg', 'png', 'webp'];
                if (!in_array($ext, $allowed_ext)) continue;

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

                if ($ext === 'webp') {
                    if(move_uploaded_file($tmp_name, $dest_path)) $noms_fichiers[] = $new_name;
                } else {
                    if (function_exists('imagecreatefromjpeg')) {
                        $img = ($ext === 'png') ? @imagecreatefrompng($tmp_name) : @imagecreatefromjpeg($tmp_name);
                        if ($img) {
                            if ($ext === 'png') { 
                                imagepalettetotruecolor($img); 
                                imagealphablending($img, true); 
                                imagesavealpha($img, true); 
                            }
                            imagewebp($img, $dest_path, 80);
                            imagedestroy($img);
                            $noms_fichiers[] = $new_name;
                        }
                    }
                }
            }
        }
    }
    return implode(',', $noms_fichiers);
}

// ==========================================
// 1. GESTION DES ACTUALITÉS (TRAITEMENTS POST)
// ==========================================
if (isLogged() && isset($_POST['add_news'])) {
    $titre = trim($_POST['news_title'] ?? ''); 
    $contenu = trim($_POST['news_content'] ?? '');
    $date_fin = !empty($_POST['news_fin']) ? $_POST['news_fin'] : null;
    $images_str = (!empty($_FILES['news_images']['name'][0]) && function_exists('traiterImagesWebp')) ? traiterImagesWebp($_FILES['news_images']) : '';
    
    if (!empty($titre)) {
        $pdo->prepare("INSERT INTO news (titre, contenu, auteur_id, images, date_fin) VALUES (?, ?, ?, ?, ?)")->execute([$titre, $contenu, $_SESSION['user_id'], $images_str, $date_fin]);
    }
}

if (isLogged() && isset($_POST['edit_news_id'])) {
    $id = (int)$_POST['edit_news_id'];
    $titre = trim($_POST['edit_news_title']);
    $contenu = trim($_POST['edit_news_content']);
    $date_fin = !empty($_POST['edit_news_fin']) ? $_POST['edit_news_fin'] : null;

    if (!empty($_FILES['edit_news_images']['name'][0])) {
        // Supprimer les anciennes images
        $old_images = $pdo->query("SELECT images FROM news WHERE id = $id")->fetchColumn();
        if (!empty($old_images)) {
            foreach(explode(',', $old_images) as $img) {
                $path = 'images/news/' . $img;
                if (file_exists($path)) @unlink($path);
            }
        }
        // Uploader les nouvelles
        $images_str = traiterImagesWebp($_FILES['edit_news_images']);
        $pdo->prepare("UPDATE news SET titre = ?, contenu = ?, date_fin = ?, images = ? WHERE id = ?")->execute([$titre, $contenu, $date_fin, $images_str, $id]);
    } else {
        $pdo->prepare("UPDATE news SET titre = ?, contenu = ?, date_fin = ? WHERE id = ?")->execute([$titre, $contenu, $date_fin, $id]);
    }
}

if (isLogged() && isset($_POST['delete_news_id'])) {
    $id = (int)$_POST['delete_news_id'];
    
    // Supprimer les images physiques
    $old_images = $pdo->query("SELECT images FROM news WHERE id = $id")->fetchColumn();
    if (!empty($old_images)) {
        foreach(explode(',', $old_images) as $img) {
            $path = 'images/news/' . $img;
            if (file_exists($path)) @unlink($path);
        }
    }
    $pdo->prepare("DELETE FROM news WHERE id = ?")->execute([$id]);
}

// ==========================================
// 2. GESTION DES INFOS LÉGALES (TRAITEMENTS POST)
// ==========================================
if (isLogged() && isset($_POST['add_legal_type'])) { $pdo->prepare("INSERT INTO type_infos_legales (nom_type) VALUES (?)")->execute([trim($_POST['new_type_name'])]); }
if (isLogged() && isset($_POST['edit_legal_type_id'])) { $pdo->prepare("UPDATE type_infos_legales SET nom_type = ? WHERE id = ?")->execute([trim($_POST['edit_type_name']), (int)$_POST['edit_legal_type_id']]); }
if (isLogged() && isset($_POST['delete_legal_type_id'])) { $pdo->prepare("DELETE FROM type_infos_legales WHERE id = ?")->execute([(int)$_POST['delete_legal_type_id']]); }

if (isLogged() && isset($_POST['add_legal'])) {
    $fichiers_str = !empty($_FILES['legal_files']['name'][0]) ? traiterFichiersLegaux($_FILES['legal_files']) : '';
    $d_debut = !empty($_POST['legal_debut']) ? $_POST['legal_debut'] : date('Y-m-d');
    $pdo->prepare("INSERT INTO infos_legales (titre, contenu, type_publication, auteur_id, date_debut, date_fin, fichiers_joints) VALUES (?, ?, ?, ?, ?, ?, ?)")->execute([trim($_POST['legal_title']), trim($_POST['legal_content']), trim($_POST['legal_type']), $_SESSION['user_id'], $d_debut, !empty($_POST['legal_fin']) ? $_POST['legal_fin'] : null, $fichiers_str]);
}

if (isLogged() && isset($_POST['edit_legal_id'])) {
    $id = (int)$_POST['edit_legal_id'];
    $fichiers_str = '';
    if (!empty($_FILES['edit_legal_files']['name'][0])) {
        $anciens = $pdo->query("SELECT fichiers_joints FROM infos_legales WHERE id = $id")->fetchColumn();
        $fichiers_str = !empty($anciens) ? $anciens . ',' . traiterFichiersLegaux($_FILES['edit_legal_files']) : traiterFichiersLegaux($_FILES['edit_legal_files']);
        $pdo->prepare("UPDATE infos_legales SET titre = ?, contenu = ?, type_publication = ?, date_debut = ?, date_fin = ?, fichiers_joints = ? WHERE id = ?")->execute([trim($_POST['edit_legal_title']), trim($_POST['edit_legal_content']), trim($_POST['edit_legal_type']), $_POST['edit_legal_debut'], !empty($_POST['edit_legal_fin']) ? $_POST['edit_legal_fin'] : null, $fichiers_str, $id]);
    } else {
        $pdo->prepare("UPDATE infos_legales SET titre = ?, contenu = ?, type_publication = ?, date_debut = ?, date_fin = ? WHERE id = ?")->execute([trim($_POST['edit_legal_title']), trim($_POST['edit_legal_content']), trim($_POST['edit_legal_type']), $_POST['edit_legal_debut'], !empty($_POST['edit_legal_fin']) ? $_POST['edit_legal_fin'] : null, $id]);
    }
}
if (isLogged() && isset($_POST['delete_legal_id'])) { $pdo->prepare("DELETE FROM infos_legales WHERE id = ?")->execute([(int)$_POST['delete_legal_id']]); }

// ==========================================
// 3. GESTION DU BLOG (TRAITEMENTS POST)
// ==========================================
if (isLogged() && isset($_POST['send_blog'])) { $pdo->prepare("INSERT INTO blog_messages (utilisateur_id, message) VALUES (?, ?)")->execute([$_SESSION['user_id'], trim($_POST['blog_msg'])]); }
if (isLogged() && isset($_POST['edit_post_id'])) { $pdo->prepare("UPDATE blog_messages SET message = ? WHERE id = ?")->execute([trim($_POST['edit_post_content']), (int)$_POST['edit_post_id']]); }
if (isLogged() && isset($_POST['delete_post_id'])) { $pdo->prepare("DELETE FROM blog_messages WHERE id = ?")->execute([(int)$_POST['delete_post_id']]); }
if (isLogged() && isset($_POST['send_comment'])) { $pdo->prepare("INSERT INTO blog_commentaires (message_id, utilisateur_id, commentaire) VALUES (?, ?, ?)")->execute([(int)$_POST['msg_id'], $_SESSION['user_id'], trim($_POST['comment_text'])]); }

// --- RÉCUPÉRATION GLOBALE DES DONNÉES ---
try {
    $all_news = $pdo->query("SELECT n.*, u.nom as auteur_nom FROM news n LEFT JOIN utilisateurs u ON n.auteur_id = u.id ORDER BY date_creation DESC")->fetchAll();
    
    $is_admin_legal = (isLogged() && (hasRole('Administrateur') || hasRole('Editeur') || hasRole('Maire')));
    $req_legal = $is_admin_legal ? "SELECT l.*, u.nom as auteur_nom FROM infos_legales l LEFT JOIN utilisateurs u ON l.auteur_id = u.id ORDER BY l.date_debut DESC, l.id DESC" : "SELECT l.*, u.nom as auteur_nom FROM infos_legales l LEFT JOIN utilisateurs u ON l.auteur_id = u.id WHERE l.date_debut <= CURDATE() ORDER BY l.date_debut DESC, l.id DESC";
    $all_legales = $pdo->query($req_legal)->fetchAll();
    
    $all_types = $pdo->query("SELECT * FROM type_infos_legales ORDER BY nom_type ASC")->fetchAll();
} catch (Exception $e) { 
    $all_news = []; $all_legales = []; $all_types = []; 
}

$blog_messages = [];
if (isLogged()) {
    try {
        $blog_messages = $pdo->query("SELECT b.*, u.nom FROM blog_messages b JOIN utilisateurs u ON b.utilisateur_id = u.id ORDER BY b.date_creation DESC")->fetchAll();
        foreach ($blog_messages as &$msg) {
            $stmtCom = $pdo->prepare("SELECT c.*, u.nom FROM blog_commentaires c JOIN utilisateurs u ON c.utilisateur_id = u.id WHERE c.message_id = ? ORDER BY c.date_creation ASC");
            $stmtCom->execute([$msg['id']]);
            $msg['commentaires'] = $stmtCom->fetchAll();
        }
    } catch (Exception $e) { }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Saint Vaast en Chaussée - Accueil</title>
    <link rel="stylesheet" href="css/global.css">
    <style>
        .tabs-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .tabs-container { width: 100%; overflow: hidden; }
        .tabs { display: flex; gap: 10px; margin: 0; padding: 0; }
        .tab-btn { background-color: #f0f0f0; border: 1px solid #ddd; padding: 10px 20px; cursor: pointer; border-radius: 8px; font-weight: bold; color: #555; transition: 0.3s; white-space: nowrap; }
        .tab-btn:hover { background-color: #e0e0e0; }
        .tab-btn.active { background-color: var(--nature-vert, #4a7c44); color: white; border-color: var(--nature-vert, #4a7c44); }
        .user-badge { margin-top: 15px; background: #fff; padding: 5px 15px; border-radius: 20px; font-size: 0.9em; color: #555; box-shadow: 0 2px 5px rgba(0,0,0,0.05); white-space: nowrap; }

        @media (max-width: 768px) {
            .tabs-header { flex-direction: column; align-items: flex-start; gap: 15px;}
            .tabs-container { -webkit-mask-image: linear-gradient(to right, transparent 0%, black 10%, black 90%, transparent 100%); mask-image: linear-gradient(to right, transparent 0%, black 10%, black 90%, transparent 100%); padding: 5px 0; }
            .tabs { overflow-x: auto; flex-wrap: nowrap; scroll-behavior: smooth; -webkit-overflow-scrolling: touch; padding: 0 15%; scrollbar-width: none; -ms-overflow-style: none; }
            .tabs::-webkit-scrollbar { display: none; }
            .tab-btn { flex: 0 0 auto; }
        }

        .legal-badge { display: inline-block; background-color: #e1ede0; color: var(--nature-vert); padding: 5px 12px; border-radius: 12px; font-size: 0.85em; font-weight: bold; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.5px; border: 1px solid #c8e6c9; }
        .legal-badge.future { background-color: #fffde7; color: #f57f17; border-color: #fbc02d; }
        .modal-content select, .modal-content input[type="date"], .modal-content input[type="file"], .modal-content input[type="text"], .modal-content textarea { width: 100%; padding: 12px; margin: 5px 0 15px 0; border: 2px solid var(--nature-clair); border-radius: 15px; box-sizing: border-box; font-family: inherit; background-color: white; }
        .file-link { display: inline-flex; align-items: center; gap: 8px; background: #fdfbf7; padding: 10px 15px; border-radius: 12px; border: 1px solid #eee; text-decoration: none; color: #333; font-weight: 500; transition: 0.3s; margin-right: 10px; margin-top: 10px; }
        .file-link:hover { background: #e1ede0; border-color: var(--nature-vert); color: var(--nature-vert); }
        .type-list { margin-top: 20px; max-height: 250px; overflow-y: auto; }
        .type-item { display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom: 1px solid #eee; }
        .btn-small { padding: 4px 10px; font-size: 0.8em; border-radius: 8px; border: none; cursor: pointer; color: white; font-weight: bold; }
        .btn-small-edit { background: #607d8b; }
        .btn-small-del { background: #e74c3c; }
        .form-grid-dates { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
    </style>
</head>
<body>
<div class="site-container">
    <img src="images/banniere.png" alt="Bannière" class="banner-img" style="width: 100%;">
    <nav><?php include 'includes/menu.php'; ?></nav>

    <main class="main-wrapper">
        <div class="tabs-header">
            <div class="tabs-container">
                <div class="tabs">
                    <button class="tab-btn active" onclick="openTab(event, 'news')">Actualités</button>
                    <button class="tab-btn" onclick="openTab(event, 'legal')">Infos Légales</button>
                    <?php if(isLogged() && $_SESSION['est_valide'] == 1): ?>
                        <button class="tab-btn" onclick="openTab(event, 'blog')">Le Blog des Habitants</button>
                    <?php endif; ?>
                </div>
            </div>
            
            <?php if(isset($_SESSION['nom'])): ?>
                <span class="user-badge" style="white-space: nowrap; margin-top: 10px;">
                    Bonjour, <?php echo htmlspecialchars(trim(($_SESSION['prenom'] ?? '') . ' ' . $_SESSION['nom']), ENT_QUOTES, 'UTF-8'); ?>
                </span>
            <?php endif; ?>
        </div>

        <div class="content-scroll">
            <div id="news" class="tab-content active">
                <?php include 'onglets/actualites.php'; ?>
            </div>
            <div id="legal" class="tab-content" style="display:none;">
                <?php include 'onglets/infos_legales.php'; ?>
            </div>
            <?php if(isLogged() && $_SESSION['est_valide'] == 1): ?>
            <div id="blog" class="tab-content" style="display:none;">
                <?php include 'onglets/blog.php'; ?>
            </div>
            <?php endif; ?>
        </div>
    </main>
</div>

<div id="lightbox" class="lightbox-modal" onclick="closeLightbox()">
    <span class="lightbox-close">&times;</span>
    <img id="lightbox-img" class="lightbox-img" src="">
</div>

<script>
    function openTab(evt, tabName) {
        document.querySelectorAll(".tab-content").forEach(t => t.style.display = "none");
        document.querySelectorAll(".tab-btn").forEach(b => b.classList.remove("active"));
        document.getElementById(tabName).style.display = "block";
        evt.currentTarget.classList.add("active");

        if(window.innerWidth <= 768) {
            const tabsContainer = document.querySelector('.tabs');
            const btnClicked = evt.currentTarget;
            const scrollLeft = btnClicked.offsetLeft - (tabsContainer.offsetWidth / 2) + (btnClicked.offsetWidth / 2);
            tabsContainer.scrollTo({ left: scrollLeft, behavior: 'smooth' });
        }
    }

    // MODIFICATION ICI : On ajoute 'dateFin' pour la modal des Actualités
    function openEditNewsModal(id, titre, dateFin) {
        document.getElementById('edit_news_id').value = id;
        document.getElementById('edit_news_title').value = titre;
        document.getElementById('edit_news_fin').value = dateFin || '';
        document.getElementById('edit_news_content').value = document.getElementById('news_content_' + id).innerText;
        document.getElementById('editNewsModal').style.display = 'flex';
    }

    function openEditLegalModal(id, titre, type, date_debut, date_fin) {
        document.getElementById('edit_legal_id').value = id;
        document.getElementById('edit_legal_title').value = titre;
        document.getElementById('edit_legal_type').value = type;
        document.getElementById('edit_legal_debut').value = date_debut;
        document.getElementById('edit_legal_fin').value = date_fin;
        document.getElementById('edit_legal_content').value = document.getElementById('legal_content_' + id).innerText;
        document.getElementById('editLegalModal').style.display = 'flex';
    }

    function openEditTypeModal(id, nom) {
        document.getElementById('edit_type_id').value = id;
        document.getElementById('edit_type_name').value = nom;
        document.getElementById('editTypeModal').style.display = 'flex';
    }

    function openEditBlogModal(id) {
        document.getElementById('edit_post_id').value = id;
        document.getElementById('edit_post_content').value = document.getElementById('blog_content_' + id).innerText;
        document.getElementById('editBlogModal').style.display = 'flex';
    }

    function closeModal(modalId) { document.getElementById(modalId).style.display = 'none'; }
    function openLightbox(imgSrc) { document.getElementById("lightbox-img").src = imgSrc; document.getElementById("lightbox").style.display = "flex"; }
    function closeLightbox() { document.getElementById("lightbox").style.display = "none"; }

    window.onclick = function(event) {
        if (event.target.classList.contains('modal') || event.target.classList.contains('lightbox-modal')) {
            event.target.style.display = "none";
        }
    }
</script>
</body>
</html>