<?php
/**
 * Manage group members - add/remove members from a group
 */

$stmt = $pdo->prepare('SELECT * FROM `groups` WHERE id = ?');
$stmt->execute([$id]);
$group = $stmt->fetch();
if (!$group) {
    header('Location: ' . BASE_PATH . '/groups');
    exit;
}

// Add member
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_member'])) {
    $member_id = (int)($_POST['member_id'] ?? 0);
    if ($member_id) {
        $pdo->prepare('INSERT IGNORE INTO group_members (group_id, member_id) VALUES (?, ?)')
            ->execute([$id, $member_id]);
    }
    header('Location: ' . BASE_PATH . '/groups/members/' . $id . '?toast=' . urlencode('Group membership updated.'));
    exit;
}

// Remove member
if (isset($_GET['remove'])) {
    $member_id = (int)$_GET['remove'];
    $pdo->prepare('DELETE FROM group_members WHERE group_id = ? AND member_id = ?')
        ->execute([$id, $member_id]);
    header('Location: ' . BASE_PATH . '/groups/members/' . $id . '?toast=' . urlencode('Group membership updated.'));
    exit;
}

// Current members
$members = $pdo->prepare("
    SELECT m.id, m.first_name, m.last_name, gm.role, gm.joined_at
    FROM group_members gm
    JOIN members m ON m.id = gm.member_id
    WHERE gm.group_id = ?
    ORDER BY m.last_name, m.first_name
");
$members->execute([$id]);
$members = $members->fetchAll();

// All members for dropdown (excluding already in group and deceased members)
$memberIds = array_column($members, 'id');
$available = $pdo->query("SELECT id, first_name, last_name FROM members WHERE (status != 'deceased' OR status IS NULL) AND (date_of_death IS NULL) ORDER BY last_name, first_name")->fetchAll();
$available = array_filter($available, function ($m) use ($memberIds) {
    return !in_array($m['id'], $memberIds);
});

$pageTitle = 'Manage Members: ' . $group['name'];
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1>Manage Members: <?= htmlspecialchars($group['name']) ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/groups">Back to Groups</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>


<div class="card">
    <h2>Add Member</h2>
    <form method="post" style="display: flex; gap: 0.5rem; align-items: flex-end; flex-wrap: wrap;">
        <div class="form-group" style="margin-bottom: 0;">
            <label for="member_id">Select member</label>
            <select id="member_id" name="member_id" style="min-width: 200px;">
                <option value="">-- Select --</option>
                <?php foreach ($available as $m): ?>
                    <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['first_name'] . ' ' . $m['last_name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" name="add_member" class="btn">Add to Group</button>
    </form>
</div>

<div class="card">
    <h2>Current Members (<?= count($members) ?>)</h2>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Role</th>
                    <th>Joined</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($members as $m): ?>
                <tr>
                    <td><?= htmlspecialchars($m['first_name'] . ' ' . $m['last_name']) ?></td>
                    <td><?= htmlspecialchars($m['role'] ?? '-') ?></td>
                    <td><?= $m['joined_at'] ? date('M j, Y', strtotime($m['joined_at'])) : '-' ?></td>
                    <td>
                        <a href="?remove=<?= $m['id'] ?>" data-confirm="Remove this member from the group?">Remove</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if (empty($members)): ?>
    <p>No members in this group yet. Add members using the form above.</p>
<?php endif; ?>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
