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

// --- Handle Add/Edit/Delete Council Members ---
if (isset($_POST['add_member'])) {
    $name = $_POST['name'];
    $role = $_POST['role'];
    $list_order = (int)$_POST['list_order'];
    $photo = '';
    
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
        $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
        $photo = 'uploads/' . uniqid() . '.' . $ext;
        move_uploaded_file($_FILES['photo']['tmp_name'], '../' . $photo);
        $photo = '../' . $photo; // store path correctly relative to frontend
    } else {
        $photo = $_POST['photo_url'] ?? '';
    }

    $stmt = $pdo->prepare("INSERT INTO council_members (name, role, photo, list_order) VALUES (?, ?, ?, ?)");
    $stmt->execute([$name, $role, $photo, $list_order]);
    header("Location: conseil.php");
    exit;
}

if (isset($_GET['del_member'])) {
    $stmt = $pdo->prepare("DELETE FROM council_members WHERE id = ?");
    $stmt->execute([$_GET['del_member']]);
    header("Location: conseil.php");
    exit;
}

// --- Handle Add/Edit/Delete Commissions ---
if (isset($_POST['add_commission'])) {
    $name = $_POST['name'];
    $members_arr = $_POST['member_ids'] ?? [];
    $members = implode(', ', $members_arr);
    $list_order = (int)$_POST['list_order'];

    $stmt = $pdo->prepare("INSERT INTO commissions (name, president, members, list_order) VALUES (?, '', ?, ?)");
    $stmt->execute([$name, $members, $list_order]);
    header("Location: conseil.php");
    exit;
}

if (isset($_GET['del_com'])) {
    $stmt = $pdo->prepare("DELETE FROM commissions WHERE id = ?");
    $stmt->execute([$_GET['del_com']]);
    header("Location: conseil.php");
    exit;
}

$members = $pdo->query("SELECT * FROM council_members ORDER BY list_order ASC")->fetchAll();
$commissions = $pdo->query("SELECT * FROM commissions ORDER BY list_order ASC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Conseil Municipal - 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 du Conseil Municipal</h1>
        </header>

        <div class="flex-1 overflow-auto p-8 space-y-8">
            <!-- SECTION MEMBRES -->
            <div class="bg-white rounded-xl shadow p-6">
                <h2 class="text-xl font-bold mb-4">Membres du Conseil</h2>
                <form action="" method="POST" enctype="multipart/form-data" class="flex gap-4 mb-6 p-4 bg-gray-50 rounded">
                    <input type="text" name="name" placeholder="Nom Prénom" class="border p-2 rounded w-1/4" required>
                    <input type="text" name="role" placeholder="Rôle (Ex: Maire)" class="border p-2 rounded w-1/4" required>
                    <input type="text" name="photo_url" placeholder="URL photo ou fichier ->" class="border p-2 rounded w-1/4">
                    <input type="file" name="photo" class="w-1/4">
                    <input type="number" name="list_order" placeholder="Ordre" value="0" class="border p-2 rounded w-20">
                    <button type="submit" name="add_member" class="bg-[#7b2c2d] text-white px-4 py-2 rounded">Ajouter</button>
                </form>
                
                <table class="w-full text-left">
                    <tr class="border-b"><th class="py-2">Nom</th><th>Rôle</th><th>Ordre</th><th>Actions</th></tr>
                    <?php foreach($members as $m): ?>
                    <tr class="border-b">
                        <td class="py-2"><?php echo htmlspecialchars($m['name']); ?></td>
                        <td><?php echo htmlspecialchars($m['role']); ?></td>
                        <td><?php echo $m['list_order']; ?></td>
                        <td><a href="?del_member=<?php echo $m['id']; ?>" class="text-red-600 hover:underline">Supprimer</a></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
            </div>

            <!-- SECTION COMMISSIONS -->
            <div class="bg-white rounded-xl shadow p-6">
                <h2 class="text-xl font-bold mb-4">Commissions et Délégations</h2>
                <form action="" method="POST" class="mb-6 p-4 bg-gray-50 rounded">
                    <div class="flex gap-4 mb-4">
                        <input type="text" name="name" placeholder="Nom de la commission ou délégation" class="border p-2 rounded flex-1" required>
                        <input type="number" name="list_order" placeholder="Ordre" value="0" class="border p-2 rounded w-20">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-bold text-gray-700 mb-2">Membres associés (Cochez les élus) :</label>
                        <div class="grid grid-cols-2 md:grid-cols-3 gap-2 bg-white p-3 border rounded max-h-40 overflow-y-auto">
                            <?php foreach($members as $m): ?>
                            <label class="flex items-center space-x-2 text-sm cursor-pointer">
                                <input type="checkbox" name="member_ids[]" value="<?php echo htmlspecialchars($m['name']); ?>" class="rounded text-[#7b2c2d] focus:ring-[#7b2c2d]">
                                <span><?php echo htmlspecialchars($m['name']); ?></span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <button type="submit" name="add_commission" class="bg-[#7b2c2d] text-white px-4 py-2 rounded">Ajouter la commission</button>
                </form>
                
                <table class="w-full text-left">
                    <tr class="border-b"><th class="py-2">Nom</th><th>Membres</th><th>Ordre</th><th>Actions</th></tr>
                    <?php foreach($commissions as $c): ?>
                    <tr class="border-b hover:bg-gray-50">
                        <td class="py-2 font-medium w-1/3"><?php echo htmlspecialchars($c['name']); ?></td>
                        <td class="text-sm text-gray-600"><?php echo htmlspecialchars($c['members']); ?></td>
                        <td><?php echo $c['list_order']; ?></td>
                        <td><a href="?del_com=<?php echo $c['id']; ?>" class="text-red-600 hover:underline">Supprimer</a></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
            </div>
        </div>
    </main>
    <script>lucide.createIcons();</script>
</body>
</html>
