<?php
/**
 * ============================================================================
 * groups/members.php - View All Group Members
 * Facebook-style member management
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

// Load Group classes
require_once __DIR__ . '/../classes/Group.php';
require_once __DIR__ . '/../classes/Group_Enhanced.php';

requireLogin();

$userId = getUserId();
$groupId = intval($_GET['id'] ?? 0);

if (!$groupId) {
    redirect('/groups/', 'Group not found', 'error');
}

$database = new Database();
$db = $database->getConnection();
$groupClass = new \App\GroupEnhanced($db);

// Get group details
$group = $groupClass->getDetails($groupId, $userId);

if (!$group) {
    redirect('/groups/', 'Group not found', 'error');
}

// Check user status
$isMember = ($group['membership_status'] === 'active');
$isAdmin = in_array($group['role'], ['admin', 'moderator']);

if (!$isMember) {
    redirect('/groups/view.php?id=' . $groupId, 'You must be a member to view this page', 'error');
}

// Get filter
$filter = $_GET['filter'] ?? 'all';

// Get members based on filter
switch ($filter) {
    case 'admins':
        $sql = "SELECT gm.*, u.full_name, u.profile_picture, u.district_id, u.email
                FROM group_members gm
                JOIN users u ON gm.user_id = u.id
                WHERE gm.group_id = ? AND gm.status = 'active' AND gm.role IN ('admin', 'moderator')
                ORDER BY 
                    CASE gm.role 
                        WHEN 'admin' THEN 1
                        WHEN 'moderator' THEN 2
                    END,
                    gm.joined_at ASC";
        break;
    case 'new':
        $sql = "SELECT gm.*, u.full_name, u.profile_picture, u.district_id, u.email
                FROM group_members gm
                JOIN users u ON gm.user_id = u.id
                WHERE gm.group_id = ? AND gm.status = 'active'
                AND DATE(gm.joined_at) >= DATE_SUB(NOW(), INTERVAL 30 DAY)
                ORDER BY gm.joined_at DESC";
        break;
    default:
        $sql = "SELECT gm.*, u.full_name, u.profile_picture, u.district_id, u.email
                FROM group_members gm
                JOIN users u ON gm.user_id = u.id
                WHERE gm.group_id = ? AND gm.status = 'active'
                ORDER BY 
                    CASE gm.role 
                        WHEN 'admin' THEN 1
                        WHEN 'moderator' THEN 2
                        ELSE 3
                    END,
                    gm.joined_at ASC";
}

$stmt = $db->prepare($sql);
$stmt->execute([$groupId]);
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get member statistics for each member
foreach ($members as &$member) {
    $stats = $groupClass->getMemberStats($groupId, $member['user_id']);
    $member['stats'] = $stats;
}

// Get top contributors
$topContributors = $groupClass->getTopContributors($groupId, 5);

$pageTitle = 'Members - ' . $group['group_name'];
include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
.member-card {
    transition: all 0.3s ease;
    border-radius: 12px;
    overflow: hidden;
}

.member-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 16px rgba(0,0,0,0.1);
}

.member-avatar {
    width: 80px;
    height: 80px;
    border-radius: 12px;
    object-fit: cover;
}

.role-badge {
    font-size: 0.75rem;
    padding: 4px 10px;
    border-radius: 12px;
    font-weight: 600;
}

.role-admin {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.role-moderator {
    background-color: #28a745;
    color: white;
}

.stat-box {
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 8px;
    text-align: center;
}

.filter-tabs {
    background: white;
    border-radius: 12px;
    padding: 10px;
    margin-bottom: 20px;
}

.search-box {
    max-width: 400px;
}

.contributor-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 10px;
}

.sticky-sidebar {
    position: sticky;
    top: 20px;
}
</style>

<div class="container py-4">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-3">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/groups/">Groups</a></li>
            <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/groups/view.php?id=<?php echo $groupId; ?>"><?php echo htmlspecialchars($group['group_name']); ?></a></li>
            <li class="breadcrumb-item active">Members</li>
        </ol>
    </nav>

    <!-- Header -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h3 class="mb-1">
                        <i class="bi bi-people-fill text-primary"></i> Group Members
                    </h3>
                    <p class="text-muted mb-0"><?php echo count($members); ?> active members</p>
                </div>
                <div class="col-md-6">
                    <div class="search-box float-end">
                        <input type="text" 
                               class="form-control" 
                               id="memberSearch" 
                               placeholder="Search members..."
                               autocomplete="off">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-9">
            <!-- Filter Tabs -->
            <div class="filter-tabs">
                <div class="btn-group w-100" role="group">
                    <a href="?id=<?php echo $groupId; ?>&filter=all" 
                       class="btn <?php echo $filter === 'all' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                        <i class="bi bi-people"></i> All Members
                    </a>
                    <a href="?id=<?php echo $groupId; ?>&filter=admins" 
                       class="btn <?php echo $filter === 'admins' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                        <i class="bi bi-shield-check"></i> Admins & Mods
                    </a>
                    <a href="?id=<?php echo $groupId; ?>&filter=new" 
                       class="btn <?php echo $filter === 'new' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                        <i class="bi bi-star"></i> New Members
                    </a>
                </div>
            </div>

            <!-- Members Grid -->
            <div class="row g-3" id="membersGrid">
                <?php foreach ($members as $member): ?>
                    <div class="col-md-6 col-lg-4 member-item" 
                         data-name="<?php echo strtolower(htmlspecialchars($member['full_name'])); ?>">
                        <div class="card member-card h-100 border-0 shadow-sm">
                            <div class="card-body">
                                <div class="d-flex align-items-start mb-3">
                                    <img src="<?php echo getAvatarUrl($member['profile_picture']); ?>" 
                                         class="member-avatar me-3" 
                                         alt="<?php echo htmlspecialchars($member['full_name']); ?>">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1">
                                            <a href="<?php echo APP_URL; ?>/profile/view.php?id=<?php echo $member['user_id']; ?>" 
                                               class="text-dark text-decoration-none">
                                                <?php echo htmlspecialchars($member['full_name']); ?>
                                            </a>
                                        </h6>
                                        <?php if ($member['role'] === 'admin'): ?>
                                            <span class="role-badge role-admin">
                                                <i class="bi bi-shield-fill"></i> Admin
                                            </span>
                                        <?php elseif ($member['role'] === 'moderator'): ?>
                                            <span class="role-badge role-moderator">
                                                <i class="bi bi-shield-check"></i> Moderator
                                            </span>
                                        <?php endif; ?>
                                        <div class="mt-2">
                                            <small class="text-muted">
                                                <i class="bi bi-calendar-check"></i>
                                                Joined <?php echo timeAgo($member['joined_at']); ?>
                                            </small>
                                        </div>
                                    </div>
                                    <?php if ($isAdmin && $member['user_id'] != $userId): ?>
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-link text-dark" data-bs-toggle="dropdown">
                                                <i class="bi bi-three-dots-vertical"></i>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <?php if ($member['role'] === 'member'): ?>
                                                    <li>
                                                        <a class="dropdown-item" 
                                                           href="#" 
                                                           onclick="updateRole(<?php echo $member['user_id']; ?>, 'moderator'); return false;">
                                                            <i class="bi bi-shield-check"></i> Make Moderator
                                                        </a>
                                                    </li>
                                                <?php elseif ($member['role'] === 'moderator'): ?>
                                                    <li>
                                                        <a class="dropdown-item" 
                                                           href="#" 
                                                           onclick="updateRole(<?php echo $member['user_id']; ?>, 'member'); return false;">
                                                            <i class="bi bi-person"></i> Remove Moderator
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                                <li><hr class="dropdown-divider"></li>
                                                <li>
                                                    <a class="dropdown-item text-danger" 
                                                       href="#" 
                                                       onclick="removeMember(<?php echo $member['user_id']; ?>, '<?php echo htmlspecialchars($member['full_name']); ?>'); return false;">
                                                        <i class="bi bi-person-dash"></i> Remove Member
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item text-danger" 
                                                       href="#" 
                                                       onclick="banMember(<?php echo $member['user_id']; ?>, '<?php echo htmlspecialchars($member['full_name']); ?>'); return false;">
                                                        <i class="bi bi-slash-circle"></i> Ban Member
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <!-- Member Stats -->
                                <div class="row g-2 mb-3">
                                    <div class="col-4">
                                        <div class="stat-box">
                                            <div class="fw-bold text-primary"><?php echo $member['stats']['posts_count']; ?></div>
                                            <small class="text-muted">Posts</small>
                                        </div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-box">
                                            <div class="fw-bold text-success"><?php echo $member['stats']['comments_count']; ?></div>
                                            <small class="text-muted">Comments</small>
                                        </div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-box">
                                            <div class="fw-bold text-danger"><?php echo $member['stats']['likes_count']; ?></div>
                                            <small class="text-muted">Likes</small>
                                        </div>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="d-grid gap-2">
                                    <a href="<?php echo APP_URL; ?>/chat/conversation.php?user=<?php echo $member['user_id']; ?>" 
                                       class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-chat-dots"></i> Message
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <?php if (empty($members)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-people" style="font-size: 4rem; color: #dee2e6;"></i>
                    <h5 class="mt-3">No members found</h5>
                    <p class="text-muted">Try adjusting your filters</p>
                </div>
            <?php endif; ?>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-3">
            <div class="sticky-sidebar">
                <!-- Top Contributors -->
                <div class="card border-0 shadow-sm mb-3">
                    <div class="card-header bg-transparent">
                        <h6 class="mb-0">
                            <i class="bi bi-trophy-fill text-warning"></i> Top Contributors
                        </h6>
                    </div>
                    <div class="card-body p-2">
                        <?php foreach ($topContributors as $index => $contributor): ?>
                            <div class="contributor-card">
                                <div class="d-flex align-items-center">
                                    <div class="me-2">
                                        <span class="badge bg-light text-dark rounded-circle" style="width: 30px; height: 30px; line-height: 20px;">
                                            <?php echo $index + 1; ?>
                                        </span>
                                    </div>
                                    <img src="<?php echo getAvatarUrl($contributor['profile_picture']); ?>" 
                                         class="rounded-circle me-2" 
                                         width="40" height="40"
                                         alt="<?php echo htmlspecialchars($contributor['full_name']); ?>">
                                    <div class="flex-grow-1">
                                        <small class="fw-bold d-block"><?php echo htmlspecialchars($contributor['full_name']); ?></small>
                                        <small style="font-size: 0.7rem;">
                                            <?php echo $contributor['post_count']; ?> posts, 
                                            <?php echo $contributor['comment_count']; ?> comments
                                        </small>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Member Stats -->
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-transparent">
                        <h6 class="mb-0">
                            <i class="bi bi-graph-up"></i> Stats
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <div class="d-flex justify-content-between mb-1">
                                <small class="text-muted">Total Members</small>
                                <small class="fw-bold"><?php echo count($members); ?></small>
                            </div>
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-primary" style="width: 100%"></div>
                            </div>
                        </div>

                        <?php
                        $adminCount = count(array_filter($members, function($m) { return $m['role'] === 'admin'; }));
                        $modCount = count(array_filter($members, function($m) { return $m['role'] === 'moderator'; }));
                        ?>

                        <div class="mb-3">
                            <div class="d-flex justify-content-between mb-1">
                                <small class="text-muted">Admins</small>
                                <small class="fw-bold"><?php echo $adminCount; ?></small>
                            </div>
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-success" style="width: <?php echo ($adminCount / count($members)) * 100; ?>%"></div>
                            </div>
                        </div>

                        <div class="mb-0">
                            <div class="d-flex justify-content-between mb-1">
                                <small class="text-muted">Moderators</small>
                                <small class="fw-bold"><?php echo $modCount; ?></small>
                            </div>
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-warning" style="width: <?php echo ($modCount / count($members)) * 100; ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Toast Container -->
<div class="position-fixed top-0 end-0 p-3" style="z-index: 11000">
    <div id="memberToast" class="toast" role="alert">
        <div class="toast-header">
            <strong class="me-auto">Notification</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body" id="toastMessage"></div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const groupId = <?php echo $groupId; ?>;
const apiUrl = '<?php echo APP_URL; ?>/groups/ajax/group-actions.php';

// Search functionality
$('#memberSearch').on('keyup', function() {
    const searchTerm = $(this).val().toLowerCase();
    
    $('.member-item').each(function() {
        const memberName = $(this).data('name');
        if (memberName.includes(searchTerm)) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
});

function showToast(message, type = 'success') {
    const toastEl = document.getElementById('memberToast');
    const toastBody = document.getElementById('toastMessage');
    toastBody.textContent = message;
    
    toastEl.classList.remove('bg-success', 'bg-danger', 'text-white');
    if (type === 'success') {
        toastEl.classList.add('bg-success', 'text-white');
    } else {
        toastEl.classList.add('bg-danger', 'text-white');
    }
    
    const toast = new bootstrap.Toast(toastEl);
    toast.show();
}

function updateRole(memberId, newRole) {
    const action = newRole === 'moderator' ? 'Make Moderator' : 'Remove Moderator';
    
    if (confirm('Are you sure you want to ' + action + '?')) {
        $.post(apiUrl, {
            action: 'update_role',
            group_id: groupId,
            member_id: memberId,
            role: newRole
        }, function(response) {
            if (response.success) {
                showToast(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(response.message, 'error');
            }
        }, 'json');
    }
}

function removeMember(memberId, memberName) {
    if (confirm('Are you sure you want to remove ' + memberName + ' from this group?')) {
        $.post(apiUrl, {
            action: 'remove_member',
            group_id: groupId,
            member_id: memberId
        }, function(response) {
            if (response.success) {
                showToast(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(response.message, 'error');
            }
        }, 'json');
    }
}

function banMember(memberId, memberName) {
    if (confirm('Are you sure you want to BAN ' + memberName + ' from this group? They will not be able to rejoin.')) {
        $.post(apiUrl, {
            action: 'ban_member',
            group_id: groupId,
            member_id: memberId
        }, function(response) {
            if (response.success) {
                showToast(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(response.message, 'error');
            }
        }, 'json');
    }
}
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>