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

$message = '';
$edit_asso = null;

// Gérer l'édition (chargement des données)
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM associations WHERE id = ?");
    $stmt->execute([$id]);
    $edit_asso = $stmt->fetch();
}

// Ajouter ou Modifier une association
if (isset($_POST['save_asso'])) {
    $name = $_POST['name'];
    $username = $_POST['username'];
    $president = $_POST['president'] ?? '';
    $address = $_POST['address'] ?? '';
    $email = $_POST['email'] ?? '';
    $website = $_POST['website'] ?? '';
    $facebook = $_POST['facebook'] ?? '';
    $description = $_POST['description'] ?? '';
    $id = $_POST['id'] ?? null;

    if ($id) {
        // Update
        $sql = "UPDATE associations SET name = ?, username = ?, president = ?, address = ?, email = ?, website = ?, facebook = ?, description = ? WHERE id = ?";
        $params = [$name, $username, $president, $address, $email, $website, $facebook, $description, $id];
        
        if (!empty($_POST['password'])) {
            $sql = "UPDATE associations SET name = ?, username = ?, president = ?, address = ?, email = ?, website = ?, facebook = ?, description = ?, password_hash = ? WHERE id = ?";
            $params = [$name, $username, $president, $address, $email, $website, $facebook, $description, password_hash($_POST['password'], PASSWORD_DEFAULT), $id];
        }
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $message = "Association mise à jour avec succès.";
    } else {
        // Insert
        $password = password_hash($_POST['password'] ?: 'kutzen67', PASSWORD_DEFAULT);
        try {
            $stmt = $pdo->prepare("INSERT INTO associations (name, username, password_hash, president, address, email, website, facebook, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $username, $password, $president, $address, $email, $website, $facebook, $description]);
            $message = "Association ajoutée avec succès.";
        } catch (PDOException $e) {
            $message = "Erreur : " . $e->getMessage();
        }
    }
    // Recharger pour vider le mode edit ou voir les changements
    if (!$id) { header("Location: associations.php?msg=" . urlencode($message)); exit; }
}

// Supprimer une association
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM associations WHERE id = ?");
    $stmt->execute([$id]);
    header("Location: associations.php");
    exit;
}

if (isset($_GET['msg'])) $message = $_GET['msg'];

$assos = $pdo->query("SELECT * FROM associations ORDER BY name ASC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Gestion des Associations - Admin</title>
    <script src="../js/tailwind.min.js"></script>
    <script src="../js/lucide.min.js"></script>
</head>
<body class="bg-gray-50 flex h-screen font-sans text-gray-800">
    
    <?php include 'includes/sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-screen overflow-hidden">
        <header class="h-20 bg-white shadow-sm flex items-center justify-between px-8 flex-shrink-0">
            <h1 class="text-2xl font-bold text-gray-800">Gestion des Associations</h1>
            <?php if($edit_asso): ?>
                <a href="associations.php" class="text-alsace-red hover:underline font-bold flex items-center">
                    <i data-lucide="plus-circle" class="w-5 h-5 mr-2"></i> Mode Ajout
                </a>
            <?php endif; ?>
        </header>

        <div class="flex-1 overflow-auto p-8 space-y-8">
            <?php if($message): ?>
                <div class="p-4 bg-blue-100 text-blue-700 rounded-lg shadow-sm border border-blue-200"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>

            <div class="bg-white rounded-xl shadow p-6 border border-gray-100">
                <div class="flex justify-between items-center mb-6 border-b pb-4 cursor-pointer" onclick="document.getElementById('asso-form').classList.toggle('hidden'); document.getElementById('toggle-icon').classList.toggle('rotate-180');">
                    <h2 class="text-xl font-bold text-gray-800">
                        <?php echo $edit_asso ? 'Modifier l\'association : ' . htmlspecialchars($edit_asso['name']) : 'Ajouter une association'; ?>
                    </h2>
                    <i data-lucide="chevron-down" id="toggle-icon" class="w-6 h-6 transform transition-transform <?php echo $edit_asso ? 'rotate-180' : ''; ?>"></i>
                </div>
                <form id="asso-form" action="associations.php" method="POST" class="space-y-6 <?php echo $edit_asso ? '' : 'hidden'; ?>">
                    <?php if($edit_asso): ?>
                        <input type="hidden" name="id" value="<?php echo $edit_asso['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Nom de l'association *</label>
                            <input type="text" name="name" value="<?php echo $edit_asso ? htmlspecialchars($edit_asso['name']) : ''; ?>" required class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Identifiant de connexion *</label>
                            <input type="text" name="username" value="<?php echo $edit_asso ? htmlspecialchars($edit_asso['username']) : ''; ?>" required class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Mot de passe <?php echo $edit_asso ? '(laisser vide pour ne pas changer)' : '*'; ?></label>
                            <input type="password" name="password" <?php echo $edit_asso ? '' : 'required'; ?> class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Président</label>
                            <input type="text" name="president" value="<?php echo $edit_asso ? htmlspecialchars($edit_asso['president']) : ''; ?>" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Email public</label>
                            <input type="email" name="email" value="<?php echo $edit_asso ? htmlspecialchars($edit_asso['email']) : ''; ?>" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Site Web</label>
                            <input type="url" name="website" value="<?php echo $edit_asso ? htmlspecialchars($edit_asso['website']) : ''; ?>" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-bold text-gray-700 mb-2">Facebook</label>
                            <input type="url" name="facebook" value="<?php echo $edit_asso ? htmlspecialchars($edit_asso['facebook']) : ''; ?>" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none">
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">Adresse</label>
                        <textarea name="address" rows="2" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none"><?php echo $edit_asso ? htmlspecialchars($edit_asso['address']) : ''; ?></textarea>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">Description / Activités</label>
                        <textarea name="description" rows="3" class="w-full border p-3 rounded-lg focus:border-[#7b2c2d] outline-none"><?php echo $edit_asso ? htmlspecialchars($edit_asso['description']) : ''; ?></textarea>
                    </div>

                    <button type="submit" name="save_asso" class="bg-[#7b2c2d] text-white px-8 py-3 rounded-lg font-bold hover:bg-[#5c1a1b] transition shadow-md">
                        <?php echo $edit_asso ? 'Enregistrer les modifications' : 'Créer l\'association'; ?>
                    </button>
                </form>
            </div>

            <div class="bg-white rounded-xl shadow border border-gray-100 overflow-hidden">
                <table class="w-full text-left">
                    <thead class="bg-gray-50 border-b">
                        <tr>
                            <th class="p-4 font-bold text-gray-700">Nom</th>
                            <th class="p-4 font-bold text-gray-700">Identifiant</th>
                            <th class="p-4 font-bold text-gray-700">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        <?php foreach($assos as $a): ?>
                        <tr class="hover:bg-gray-50 transition <?php echo ($edit_asso && $edit_asso['id'] == $a['id']) ? 'bg-red-50' : ''; ?>">
                            <td class="p-4 font-medium"><?php echo htmlspecialchars($a['name']); ?></td>
                            <td class="p-4 text-gray-600"><?php echo htmlspecialchars($a['username']); ?></td>
                            <td class="p-4 flex items-center space-x-4">
                                <a href="?edit=<?php echo $a['id']; ?>" class="text-[#7b2c2d] hover:text-black font-bold flex items-center">
                                    <i data-lucide="edit" class="w-4 h-4 mr-1"></i> Modifier
                                </a>
                                <a href="?delete=<?php echo $a['id']; ?>" class="text-red-600 hover:text-red-800 font-bold flex items-center" onclick="return confirm('Supprimer ce compte ?')">
                                    <i data-lucide="trash-2" class="w-4 h-4 mr-1"></i> Supprimer
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
    <script>lucide.createIcons();</script>
</body>
</html>
