<?php
session_start();
require_once 'config/database.php';

if (!isset($_SESSION['asso_id'])) {
    header("Location: asso-login.php");
    exit;
}

$asso_id = $_SESSION['asso_id'];
$message = '';

// Mettre à jour les infos de l'association (dont mdp)
if (isset($_POST['update_asso'])) {
    $name = $_POST['name'];
    $president = $_POST['president'];
    $address = $_POST['address'];
    $email = $_POST['email'];
    $website = $_POST['website'];
    $facebook = $_POST['facebook'];
    $description = $_POST['description'];
    
    $stmt = $pdo->prepare("UPDATE associations SET name = ?, president = ?, address = ?, email = ?, website = ?, facebook = ?, description = ? WHERE id = ?");
    $stmt->execute([$name, $president, $address, $email, $website, $facebook, $description, $asso_id]);
    
    if (!empty($_POST['new_password'])) {
        $new_pass = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE associations SET password_hash = ? WHERE id = ?");
        $stmt->execute([$new_pass, $asso_id]);
    }
    
    $message = "Informations mises à jour.";
}

// Ajouter une manifestation
if (isset($_POST['add_event'])) {
    $title = $_POST['title'];
    $desc = $_POST['description'];
    $date = $_POST['event_date'];
    $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
    $time = !empty($_POST['start_time']) ? $_POST['start_time'] : null;
    $end_time = !empty($_POST['end_time']) ? $_POST['end_time'] : null;
    $loc = $_POST['location'];
    
    $stmt = $pdo->prepare("INSERT INTO association_events (association_id, title, description, event_date, end_date, start_time, end_time, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$asso_id, $title, $desc, $date, $end_date, $time, $end_time, $loc]);
    $message = "Manifestation ajoutée à l'agenda.";

    // Notification Admin
    $stmt_notif = $pdo->prepare("SELECT value FROM site_settings WHERE `key` = 'notify_asso_event'");
    $stmt_notif->execute();
    if ($stmt_notif->fetchColumn() == '1') {
        require_once 'includes/mailer.php';
        $notif_body = "L'association '{$asso['name']}' a ajouté une nouvelle manifestation :\n\n";
        $notif_body .= "Titre : $title\n";
        $notif_body .= "Date : $date\n";
        $notif_body .= "Lieu : $loc\n";
        send_site_notification($pdo, "Nouvel événement association", $notif_body);
    }
}

// Ajouter une actualité
if (isset($_POST['add_article'])) {
    $title = $_POST['title'];
    $content = $_POST['content'];
    $excerpt = $_POST['excerpt'] ?: substr(strip_tags($content), 0, 150) . '...';
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title))) . '-' . uniqid();
    
    // Upload image
    $image_name = null;
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) {
            $image_name = uniqid() . '.' . $ext;
            if (!is_dir('uploads')) mkdir('uploads', 0777, true);
            move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/' . $image_name);
        }
    }
    
    $stmt = $pdo->prepare("INSERT INTO articles (title, slug, content, excerpt, image, association_id, is_published) VALUES (?, ?, ?, ?, ?, ?, 1)");
    $stmt->execute([$title, $slug, $content, $excerpt, $image_name, $asso_id]);
    $message = "Actualité publiée sur la page d'accueil.";

    // Notification Admin
    $stmt_notif = $pdo->prepare("SELECT value FROM site_settings WHERE `key` = 'notify_asso_article'");
    $stmt_notif->execute();
    if ($stmt_notif->fetchColumn() == '1') {
        require_once 'includes/mailer.php';
        $notif_body = "L'association '{$asso['name']}' a publié une nouvelle actualité :\n\n";
        $notif_body .= "Titre : $title\n";
        $notif_body .= "Résumé : $excerpt\n";
        send_site_notification($pdo, "Nouvelle actualité association", $notif_body);
    }
}

// Supprimer une manifestation
if (isset($_GET['delete_event'])) {
    $event_id = (int)$_GET['delete_event'];
    $stmt = $pdo->prepare("DELETE FROM association_events WHERE id = ? AND association_id = ?");
    $stmt->execute([$event_id, $asso_id]);
    header("Location: asso-admin.php");
    exit;
}

// Supprimer une actualité
if (isset($_GET['delete_article'])) {
    $art_id = (int)$_GET['delete_article'];
    $stmt = $pdo->prepare("DELETE FROM articles WHERE id = ? AND association_id = ?");
    $stmt->execute([$art_id, $asso_id]);
    header("Location: asso-admin.php");
    exit;
}

// Récupérer les infos de l'asso
$stmt = $pdo->prepare("SELECT * FROM associations WHERE id = ?");
$stmt->execute([$asso_id]);
$asso = $stmt->fetch();

// Récupérer les manifestations
$stmt = $pdo->prepare("SELECT * FROM association_events WHERE association_id = ? ORDER BY event_date ASC");
$stmt->execute([$asso_id]);
$events = $stmt->fetchAll();

// Récupérer les actualités
$stmt = $pdo->prepare("SELECT * FROM articles WHERE association_id = ? ORDER BY created_at DESC");
$stmt->execute([$asso_id]);
$articles = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Espace Association - <?php echo htmlspecialchars($asso['name']); ?></title>
    <script src="js/tailwind.min.js"></script>
    <script src="js/lucide.min.js"></script>
</head>
<body class="bg-gray-100 min-h-screen font-sans">
    
    <header class="bg-[#5c1a1b] text-white shadow-lg sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-6 h-20 flex items-center justify-between">
            <h1 class="text-xl font-serif font-bold tracking-wide">Association : <?php echo htmlspecialchars($asso['name']); ?></h1>
            <div class="flex items-center space-x-6">
                <a href="index.php" class="text-sm font-medium hover:text-alsace-cream transition flex items-center">
                    <i data-lucide="home" class="w-4 h-4 mr-1"></i> Voir le site
                </a>
                <a href="asso-logout.php" class="bg-white/10 hover:bg-white/20 px-4 py-2 rounded-lg text-sm font-bold transition flex items-center border border-white/20">
                    <i data-lucide="log-out" class="w-4 h-4 mr-2"></i> Déconnexion
                </a>
            </div>
        </div>
    </header>

    <main class="max-w-7xl mx-auto px-6 py-10 space-y-10">
        
        <?php if($message): ?>
            <div class="p-4 bg-green-100 text-green-700 rounded-xl font-bold shadow-sm flex items-center">
                <i data-lucide="check-circle" class="w-5 h-5 mr-2"></i> <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-10">
            
            <!-- Colonne Gauche: Infos Association -->
            <div class="lg:col-span-1 space-y-8">
                <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
                    <h2 class="text-xl font-bold mb-6 text-gray-800 flex items-center">
                        <i data-lucide="user-edit" class="w-6 h-6 mr-2 text-[#7b2c2d]"></i> Vos Informations
                    </h2>
                    <form action="" method="POST" class="space-y-4">
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Nom</label>
                            <input type="text" name="name" value="<?php echo htmlspecialchars($asso['name']); ?>" class="w-full border border-gray-200 rounded-lg p-3 text-sm focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Président</label>
                            <input type="text" name="president" value="<?php echo htmlspecialchars($asso['president']); ?>" class="w-full border border-gray-200 rounded-lg p-3 text-sm focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Adresse</label>
                            <textarea name="address" rows="2" class="w-full border border-gray-200 rounded-lg p-3 text-sm focus:border-[#7b2c2d] outline-none"><?php echo htmlspecialchars($asso['address']); ?></textarea>
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Email public</label>
                            <input type="email" name="email" value="<?php echo htmlspecialchars($asso['email']); ?>" class="w-full border border-gray-200 rounded-lg p-3 text-sm focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Site Web</label>
                            <input type="url" name="website" value="<?php echo htmlspecialchars($asso['website']); ?>" class="w-full border border-gray-200 rounded-lg p-3 text-sm focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Facebook</label>
                            <input type="url" name="facebook" value="<?php echo htmlspecialchars($asso['facebook']); ?>" class="w-full border border-gray-200 rounded-lg p-3 text-sm focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Description / Activités</label>
                            <textarea name="description" rows="3" class="w-full border border-gray-200 rounded-lg p-3 text-sm focus:border-[#7b2c2d] outline-none"><?php echo htmlspecialchars($asso['description']); ?></textarea>
                        </div>
                        <div class="pt-4 border-t border-gray-100">
                            <label class="block text-xs font-bold text-red-700 uppercase mb-1">Nouveau mot de passe (si changement)</label>
                            <input type="password" name="new_password" class="w-full border border-gray-200 rounded-lg p-3 text-sm focus:border-[#7b2c2d] outline-none">
                        </div>
                        <button type="submit" name="update_asso" class="w-full bg-[#7b2c2d] text-white font-bold py-3 rounded-lg hover:bg-[#5c1a1b] transition shadow-md">
                            Mettre à jour mes infos
                        </button>
                    </form>
                </div>
            </div>

            <!-- Colonne Droite: Agenda -->
            <div class="lg:col-span-2 space-y-8">
                <!-- Form manifestation -->
                <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
                    <h2 class="text-xl font-bold mb-6 text-gray-800 flex items-center">
                        <i data-lucide="plus-circle" class="w-6 h-6 mr-2 text-green-600"></i> Ajouter une manifestation à l'agenda
                    </h2>
                    <form action="" method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="md:col-span-2">
                            <label class="block text-sm font-bold text-gray-700 mb-2">Titre de l'événement *</label>
                            <input type="text" name="title" required placeholder="Ex: Marché aux puces" class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-green-600 focus:ring-1 focus:ring-green-600 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Date de début *</label>
                            <input type="date" name="event_date" required class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-green-600 focus:ring-1 focus:ring-green-600 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Date de fin (Optionnel)</label>
                            <input type="date" name="end_date" class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-green-600 focus:ring-1 focus:ring-green-600 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Heure de début (Optionnel)</label>
                            <input type="time" name="start_time" class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-green-600 focus:ring-1 focus:ring-green-600 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Heure de fin (Optionnel)</label>
                            <input type="time" name="end_time" class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-green-600 focus:ring-1 focus:ring-green-600 transition">
                        </div>
                        <div class="md:col-span-2">
                            <label class="block text-sm font-bold text-gray-700 mb-2">Lieu</label>
                            <input type="text" name="location" placeholder="Ex: Salle des fêtes" class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-green-600 focus:ring-1 focus:ring-green-600 transition">
                        </div>
                        <div class="md:col-span-2">
                            <label class="block text-sm font-bold text-gray-700 mb-2">Description / Détails</label>
                            <textarea name="description" rows="3" class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-green-600 focus:ring-1 focus:ring-green-600 transition"></textarea>
                        </div>
                        <div class="md:col-span-2 pt-2">
                            <button type="submit" name="add_event" class="w-full bg-green-600 text-white font-bold py-4 rounded-lg hover:bg-green-700 transition shadow-lg transform active:scale-95">
                                Publier sur l'agenda communal
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Liste manifestations -->
                <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                    <div class="p-6 bg-gray-50 border-b">
                        <h2 class="text-xl font-bold text-gray-800 flex items-center">
                            <i data-lucide="calendar" class="w-6 h-6 mr-2 text-[#7b2c2d]"></i> Vos Manifestations publiées
                        </h2>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left">
                            <thead class="bg-gray-50/50">
                                <tr>
                                    <th class="p-6 text-sm font-bold text-gray-500 uppercase">Date</th>
                                    <th class="p-6 text-sm font-bold text-gray-500 uppercase">Titre</th>
                                    <th class="p-6 text-sm font-bold text-gray-500 uppercase">Lieu</th>
                                    <th class="p-6 text-sm font-bold text-gray-500 uppercase text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php foreach($events as $e): ?>
                                <tr class="hover:bg-gray-50/80 transition">
                                    <td class="p-6 text-gray-700">
                                        <?php if($e['end_date'] && $e['end_date'] !== $e['event_date']): ?>
                                            <span class="font-bold block">Du <?php echo date('d/m/Y', strtotime($e['event_date'])); ?></span>
                                            <span class="font-bold block">Au <?php echo date('d/m/Y', strtotime($e['end_date'])); ?></span>
                                        <?php else: ?>
                                            <span class="font-bold block"><?php echo date('d/m/Y', strtotime($e['event_date'])); ?></span>
                                        <?php endif; ?>
                                        
                                        <?php if($e['start_time']): ?>
                                            <span class="text-sm text-gray-500 block mt-1"><i data-lucide="clock" class="w-3 h-3 inline mr-1"></i><?php echo date('H:i', strtotime($e['start_time'])); ?><?php echo $e['end_time'] ? ' - ' . date('H:i', strtotime($e['end_time'])) : ''; ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-6">
                                        <div class="font-bold text-gray-900"><?php echo htmlspecialchars($e['title']); ?></div>
                                        <div class="text-xs text-gray-500 mt-1"><?php echo htmlspecialchars(substr($e['description'], 0, 50)); ?>...</div>
                                    </td>
                                    <td class="p-6 text-gray-600 text-sm italic"><?php echo htmlspecialchars($e['location']); ?></td>
                                    <td class="p-6 text-right">
                                        <a href="?delete_event=<?php echo $e['id']; ?>" class="inline-flex items-center text-red-600 hover:text-red-800 font-bold bg-red-50 hover:bg-red-100 px-4 py-2 rounded-lg transition" onclick="return confirm('Supprimer cet événement de l agenda ?')">
                                            <i data-lucide="trash-2" class="w-4 h-4 mr-1"></i> Supprimer
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if(empty($events)): ?>
                                <tr>
                                    <td colspan="4" class="p-10 text-center text-gray-400 italic font-medium">Aucune manifestation programmée.</td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- SECTION ACTUALITES -->
                <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
                    <h2 class="text-xl font-bold mb-6 text-gray-800 flex items-center">
                        <i data-lucide="newspaper" class="w-6 h-6 mr-2 text-blue-600"></i> Publier une actualité
                    </h2>
                    <form action="" method="POST" enctype="multipart/form-data" class="space-y-6">
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Titre de l'actu *</label>
                            <input type="text" name="title" required class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-blue-600 focus:ring-1 focus:ring-blue-600 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Image d'illustration (Optionnel)</label>
                            <input type="file" name="image" accept="image/*" class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Résumé court (visible sur l'accueil)</label>
                            <input type="text" name="excerpt" placeholder="Max 150 caractères..." class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-blue-600 focus:ring-1 focus:ring-blue-600 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Contenu de l'actualité *</label>
                            <textarea name="content" rows="6" required class="w-full border border-gray-200 rounded-lg p-3 outline-none focus:border-blue-600 focus:ring-1 focus:ring-blue-600 transition"></textarea>
                        </div>
                        <button type="submit" name="add_article" class="w-full bg-blue-600 text-white font-bold py-4 rounded-lg hover:bg-blue-700 transition shadow-lg transform active:scale-95">
                            Publier l'actualité
                        </button>
                    </form>
                </div>

                <!-- Liste actualités -->
                <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                    <div class="p-6 bg-gray-50 border-b">
                        <h2 class="text-xl font-bold text-gray-800 flex items-center">
                            <i data-lucide="list" class="w-6 h-6 mr-2 text-blue-600"></i> Vos actualités publiées
                        </h2>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left">
                            <thead class="bg-gray-50/50">
                                <tr>
                                    <th class="p-6 text-sm font-bold text-gray-500 uppercase">Date</th>
                                    <th class="p-6 text-sm font-bold text-gray-500 uppercase">Titre</th>
                                    <th class="p-6 text-sm font-bold text-gray-500 uppercase text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php foreach($articles as $art): ?>
                                <tr class="hover:bg-gray-50/80 transition">
                                    <td class="p-6 text-gray-500 text-sm"><?php echo date('d/m/Y', strtotime($art['created_at'])); ?></td>
                                    <td class="p-6 font-bold text-gray-900"><?php echo htmlspecialchars($art['title']); ?></td>
                                    <td class="p-6 text-right">
                                        <a href="?delete_article=<?php echo $art['id']; ?>" class="inline-flex items-center text-red-600 hover:text-red-800 font-bold bg-red-50 hover:bg-red-100 px-4 py-2 rounded-lg transition" onclick="return confirm('Supprimer cette actualité ?')">
                                            <i data-lucide="trash-2" class="w-4 h-4 mr-1"></i> Supprimer
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if(empty($articles)): ?>
                                <tr>
                                    <td colspan="3" class="p-10 text-center text-gray-400 italic font-medium">Aucune actualité publiée.</td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </main>
    <script>lucide.createIcons();</script>
</body>
</html>
