<?php
session_start();
include 'includes/auth.php';
include 'includes/db.php';
include 'includes/header.php';

// Fetch all unique group_ids
$groups_result = mysqli_query($conn, "SELECT DISTINCT group_id FROM family_links ORDER BY group_id DESC");

echo "<h2>Family Membership Groups</h2>";

if (mysqli_num_rows($groups_result) == 0) {
    echo "<div class='alert alert-info'>No family memberships found.</div>";
} else {
    while ($group = mysqli_fetch_assoc($groups_result)) {
        $group_id = (int)$group['group_id'];
        $members_result = mysqli_query($conn, "
            SELECT m.* FROM family_links fl
            JOIN members m ON m.id = fl.member_id
            WHERE fl.group_id = $group_id
            ORDER BY m.surname, m.first_name
        ");

        echo "<div class='card mb-4'>";
        echo "<div class='card-header bg-primary text-white'>Family Group #$group_id</div>";
        echo "<div class='card-body'><div class='row'>";

        while ($member = mysqli_fetch_assoc($members_result)) {
            echo "<div class='col-md-4 mb-3'>";
            echo "<div class='border p-2'>";
            echo "<strong>" . htmlspecialchars($member['first_name'] . ' ' . $member['surname']) . "</strong><br>";
            echo "Phone: " . htmlspecialchars($member['phone']) . "<br>";
            echo "Membership: " . htmlspecialchars($member['membership_type']) . "<br>";
            echo "<a href='edit_member.php?id=" . $member['id'] . "' class='btn btn-sm btn-outline-primary mt-2'>Edit</a>";
            echo "</div></div>";
        }

        echo "</div></div></div>";
    }
}

include 'includes/footer.php';
