<?php
/**
 * ============================================================================
 * groups/view.php - Complete Group View with All Features
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.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\Group($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');
$isPending = ($group['membership_status'] === 'pending');
$isAdmin = in_array($group['role'], ['admin', 'moderator']);

// Get members and posts
$members = $groupClass->getMembers($groupId);
$posts = $groupClass->getPosts($groupId);
$pendingRequests = $isAdmin ? $groupClass->getPendingRequests($groupId) : [];
$suggestedGroups = $groupClass->getSuggestedGroups($userId, 6);

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

<style>
.group-cover {
    height: 250px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    position: relative;
}

.group-avatar {
    width: 120px;
    height: 120px;
    border: 4px solid white;
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    border-radius: 15px;
    margin-top: -60px;
}

.post-card {
    transition: all 0.3s ease;
    border-left: 3px solid transparent;
}

.post-card.pinned {
    border-left-color: #ffc107;
    background-color: #fffbf0;
}

.post-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.comment-section {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 10px;
}

.comment-item {
    background: white;
    border-radius: 8px;
    padding: 10px;
    margin-bottom: 8px;
}

.role-badge {
    font-size: 0.75rem;
    padding: 3px 8px;
    border-radius: 12px;
}

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

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

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

.suggested-group-card {
    transition: transform 0.2s;
    cursor: pointer;
}

.suggested-group-card:hover {
    transform: translateY(-3px);
}

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

<!-- Group Cover -->
<div class="group-cover">
    <?php if ($group['group_cover']): ?>
        <img src="<?php echo htmlspecialchars($group['group_cover']); ?>" class="w-100 h-100 object-fit-cover" alt="Cover">
    <?php endif; ?>
</div>

<div class="container">
    <!-- Group Header -->
    <div class="bg-white shadow-sm p-4 mb-4">
        <div class="row align-items-end">
            <div class="col-auto">
                <img src="<?php echo getAvatarUrl($group['group_avatar']); ?>" 
                     class="group-avatar" 
                     alt="<?php echo htmlspecialchars($group['group_name']); ?>">
            </div>
            <div class="col">
                <h3 class="mb-1"><?php echo htmlspecialchars($group['group_name']); ?></h3>
                <p class="text-muted mb-2"><?php echo nl2br(htmlspecialchars($group['description'])); ?></p>
                <div class="d-flex flex-wrap gap-2">
                    <span class="badge bg-<?php echo $group['privacy'] === 'public' ? 'success' : 'warning'; ?>">
                        <i class="bi bi-<?php echo $group['privacy'] === 'public' ? 'globe' : 'lock'; ?>"></i>
                        <?php echo ucfirst($group['privacy']); ?>
                    </span>
                    <?php if ($group['category']): ?>
                        <span class="badge bg-primary">
                            <i class="bi bi-tag"></i> <?php echo ucfirst($group['category']); ?>
                        </span>
                    <?php endif; ?>
                    <?php if ($group['location']): ?>
                        <span class="badge bg-secondary">
                            <i class="bi bi-geo-alt"></i> <?php echo htmlspecialchars($group['location']); ?>
                        </span>
                    <?php endif; ?>
                    <span class="badge bg-info">
                        <i class="bi bi-people"></i> <?php echo $group['member_count']; ?> members
                    </span>
                    <span class="badge bg-dark">
                        <i class="bi bi-file-text"></i> <?php echo $group['post_count']; ?> posts
                    </span>
                </div>
            </div>
            <div class="col-auto">
                <?php if (!$isMember && !$isPending): ?>
                    <button class="btn btn-primary" onclick="joinGroup(<?php echo $groupId; ?>, this)">
                        <i class="bi bi-plus-circle"></i> Join Group
                    </button>
                <?php elseif ($isPending): ?>
                    <button class="btn btn-warning" disabled>
                        <i class="bi bi-clock"></i> Pending Approval
                    </button>
                <?php elseif ($isMember): ?>
                    <button class="btn btn-outline-danger" onclick="leaveGroup(<?php echo $groupId; ?>, this)">
                        <i class="bi bi-box-arrow-right"></i> Leave Group
                    </button>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php if ($isPending): ?>
        <div class="alert alert-warning">
            <i class="bi bi-clock"></i> Your request to join this group is pending admin approval.
        </div>
    <?php endif; ?>

    <!-- Tabs -->
    <ul class="nav nav-tabs mb-4" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" data-bs-toggle="tab" href="#posts">
                <i class="bi bi-file-text"></i> Posts
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-bs-toggle="tab" href="#members">
                <i class="bi bi-people"></i> Members (<?php echo count($members); ?>)
            </a>
        </li>
        <?php if ($isAdmin && !empty($pendingRequests)): ?>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="tab" href="#requests">
                    <i class="bi bi-person-check"></i> Requests 
                    <span class="badge bg-warning"><?php echo count($pendingRequests); ?></span>
                </a>
            </li>
        <?php endif; ?>
        <li class="nav-item">
            <a class="nav-link" data-bs-toggle="tab" href="#about">
                <i class="bi bi-info-circle"></i> About
            </a>
        </li>
    </ul>

    <div class="row">
        <div class="col-lg-8">
            <div class="tab-content">
                
                <!-- Posts Tab -->
                <div class="tab-pane fade show active" id="posts">
                    <?php if ($isMember): ?>
                        <!-- Create Post Form -->
                        <div class="card mb-4">
                            <div class="card-body">
                                <form id="createPostForm" onsubmit="createPost(event)">
                                    <div class="d-flex align-items-start gap-2 mb-2">
                                        <img src="<?php echo getAvatarUrl($_SESSION['user']['profile_picture'] ?? null); ?>" 
                                             class="rounded-circle" 
                                             width="40" height="40"
                                             alt="Your avatar">
                                        <textarea class="form-control" 
                                                  name="content" 
                                                  rows="3" 
                                                  placeholder="What's on your mind?"
                                                  required></textarea>
                                    </div>
                                    <div class="d-flex justify-content-end gap-2">
                                        <button type="button" class="btn btn-sm btn-outline-secondary" id="addMediaBtn">
                                            <i class="bi bi-image"></i> Photo
                                        </button>
                                        <button type="submit" class="btn btn-primary btn-sm">
                                            <i class="bi bi-send"></i> Post
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Posts List -->
                    <div id="postsList">
                        <?php if (!empty($posts)): ?>
                            <?php foreach ($posts as $post): ?>
                                <div class="card post-card mb-3 <?php echo $post['is_pinned'] ? 'pinned' : ''; ?>" 
                                     id="post-<?php echo $post['id']; ?>">
                                    <div class="card-body">
                                        <?php if ($post['is_pinned']): ?>
                                            <div class="mb-2">
                                                <small class="text-warning">
                                                    <i class="bi bi-pin-fill"></i> Pinned Post
                                                </small>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <!-- Post Header -->
                                        <div class="d-flex justify-content-between align-items-start mb-3">
                                            <div class="d-flex">
                                                <img src="<?php echo getAvatarUrl($post['profile_picture']); ?>" 
                                                     class="rounded-circle me-2" 
                                                     width="40" height="40"
                                                     alt="<?php echo htmlspecialchars($post['full_name']); ?>">
                                                <div>
                                                    <h6 class="mb-0">
                                                        <a href="<?php echo APP_URL; ?>/profile/view.php?id=<?php echo $post['user_id']; ?>" 
                                                           class="text-dark text-decoration-none">
                                                            <?php echo htmlspecialchars($post['full_name']); ?>
                                                        </a>
                                                    </h6>
                                                    <small class="text-muted">
                                                        <i class="bi bi-clock"></i> <?php echo timeAgo($post['created_at']); ?>
                                                    </small>
                                                </div>
                                            </div>
                                            <?php if ($post['user_id'] == $userId || $isAdmin): ?>
                                                <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 ($isAdmin): ?>
                                                            <li>
                                                                <a class="dropdown-item" 
                                                                   href="#" 
                                                                   onclick="togglePin(<?php echo $post['id']; ?>); return false;">
                                                                    <i class="bi bi-pin"></i> 
                                                                    <?php echo $post['is_pinned'] ? 'Unpin' : 'Pin'; ?> Post
                                                                </a>
                                                            </li>
                                                            <li><hr class="dropdown-divider"></li>
                                                        <?php endif; ?>
                                                        <li>
                                                            <a class="dropdown-item text-danger" 
                                                               href="#" 
                                                               onclick="deletePost(<?php echo $post['id']; ?>); return false;">
                                                                <i class="bi bi-trash"></i> Delete
                                                            </a>
                                                        </li>
                                                    </ul>
                                                </div>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Post Content -->
                                        <div class="mb-3">
                                            <p><?php echo nl2br(htmlspecialchars($post['content'])); ?></p>
                                            <?php if ($post['media_urls']): ?>
                                                <?php $mediaUrls = json_decode($post['media_urls'], true); ?>
                                                <div class="row g-2">
                                                    <?php foreach ($mediaUrls as $url): ?>
                                                        <div class="col-md-6">
                                                            <img src="<?php echo htmlspecialchars($url); ?>" 
                                                                 class="img-fluid rounded" 
                                                                 alt="Post image">
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Post Actions -->
                                        <div class="border-top pt-2 mb-2">
                                            <div class="d-flex justify-content-between text-muted small">
                                                <span>
                                                    <i class="bi bi-heart-fill text-danger"></i> 
                                                    <span id="likes-count-<?php echo $post['id']; ?>">
                                                        <?php echo $post['likes_count']; ?>
                                                    </span> likes
                                                </span>
                                                <span>
                                                    <span id="comments-count-<?php echo $post['id']; ?>">
                                                        <?php echo $post['comments_count']; ?>
                                                    </span> comments
                                                </span>
                                            </div>
                                        </div>

                                        <?php if ($isMember): ?>
                                            <div class="d-flex gap-2 mb-3">
                                                <button class="btn btn-sm btn-outline-primary flex-fill" 
                                                        id="like-btn-<?php echo $post['id']; ?>"
                                                        onclick="likePost(<?php echo $post['id']; ?>, this)">
                                                    <i class="bi bi-heart"></i> Like
                                                </button>
                                                <button class="btn btn-sm btn-outline-secondary flex-fill" 
                                                        onclick="toggleComments(<?php echo $post['id']; ?>)">
                                                    <i class="bi bi-chat"></i> Comment
                                                </button>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Comments Section -->
                                        <div class="comment-section d-none" id="comments-<?php echo $post['id']; ?>">
                                            <div class="mb-2" id="comment-list-<?php echo $post['id']; ?>">
                                                <!-- Comments will be loaded here -->
                                            </div>
                                            <?php if ($isMember): ?>
                                                <form onsubmit="addComment(event, <?php echo $post['id']; ?>)">
                                                    <div class="input-group input-group-sm">
                                                        <input type="text" 
                                                               class="form-control" 
                                                               name="content"
                                                               placeholder="Write a comment..."
                                                               required>
                                                        <button class="btn btn-primary" type="submit">
                                                            <i class="bi bi-send"></i>
                                                        </button>
                                                    </div>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="bi bi-file-text" style="font-size: 4rem; color: #dee2e6;"></i>
                                <h5 class="mt-3">No posts yet</h5>
                                <p class="text-muted">Be the first to post in this group!</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Members Tab -->
                <div class="tab-pane fade" id="members">
                    <div class="row">
                        <?php foreach ($members as $member): ?>
                            <div class="col-md-6 mb-3">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="d-flex">
                                                <img src="<?php echo getAvatarUrl($member['profile_picture']); ?>" 
                                                     class="rounded-circle me-2" 
                                                     width="50" height="50"
                                                     alt="<?php echo htmlspecialchars($member['full_name']); ?>">
                                                <div>
                                                    <h6 class="mb-0">
                                                        <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>
                                                        <?php if ($member['role'] === 'admin'): ?>
                                                            <span class="role-badge role-admin">Admin</span>
                                                        <?php elseif ($member['role'] === 'moderator'): ?>
                                                            <span class="role-badge role-moderator">Moderator</span>
                                                        <?php endif; ?>
                                                    </h6>
                                                    <small class="text-muted">
                                                        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" 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 from Group
                                                            </a>
                                                        </li>
                                                    </ul>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Requests Tab (Admin Only) -->
                <?php if ($isAdmin): ?>
                    <div class="tab-pane fade" id="requests">
                        <?php if (!empty($pendingRequests)): ?>
                            <div class="row" id="requestsList">
                                <?php foreach ($pendingRequests as $request): ?>
                                    <div class="col-md-6 mb-3" id="request-<?php echo $request['user_id']; ?>">
                                        <div class="card">
                                            <div class="card-body">
                                                <div class="d-flex">
                                                    <img src="<?php echo getAvatarUrl($request['profile_picture']); ?>" 
                                                         class="rounded-circle me-2" 
                                                         width="50" height="50"
                                                         alt="<?php echo htmlspecialchars($request['full_name']); ?>">
                                                    <div class="flex-grow-1">
                                                        <h6 class="mb-0">
                                                            <a href="<?php echo APP_URL; ?>/profile/view.php?id=<?php echo $request['user_id']; ?>" 
                                                               class="text-dark text-decoration-none">
                                                                <?php echo htmlspecialchars($request['full_name']); ?>
                                                            </a>
                                                        </h6>
                                                        <small class="text-muted">
                                                            Requested <?php echo timeAgo($request['joined_at']); ?>
                                                        </small>
                                                        <div class="d-flex gap-2 mt-2">
                                                            <button class="btn btn-sm btn-success" 
                                                                    onclick="approveMember(<?php echo $request['user_id']; ?>, this)">
                                                                <i class="bi bi-check-circle"></i> Approve
                                                            </button>
                                                            <button class="btn btn-sm btn-danger" 
                                                                    onclick="rejectMember(<?php echo $request['user_id']; ?>, this)">
                                                                <i class="bi bi-x-circle"></i> Reject
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="bi bi-inbox" style="font-size: 4rem; color: #dee2e6;"></i>
                                <h5 class="mt-3">No pending requests</h5>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <!-- About Tab -->
                <div class="tab-pane fade" id="about">
                    <div class="card">
                        <div class="card-body">
                            <h5>About This Group</h5>
                            <p><?php echo nl2br(htmlspecialchars($group['description'])); ?></p>
                            
                            <?php if ($group['rules']): ?>
                                <h6 class="mt-4">Group Rules</h6>
                                <p><?php echo nl2br(htmlspecialchars($group['rules'])); ?></p>
                            <?php endif; ?>
                            
                            <h6 class="mt-4">Group Info</h6>
                            <ul class="list-unstyled">
                                <li><strong>Privacy:</strong> <?php echo ucfirst($group['privacy']); ?></li>
                                <li><strong>Category:</strong> <?php echo ucfirst($group['category'] ?? 'General'); ?></li>
                                <?php if ($group['location']): ?>
                                    <li><strong>Location:</strong> <?php echo htmlspecialchars($group['location']); ?></li>
                                <?php endif; ?>
                                <li><strong>Created:</strong> <?php echo date('F j, Y', strtotime($group['created_at'])); ?></li>
                                <li><strong>Created by:</strong> 
                                    <a href="<?php echo APP_URL; ?>/profile/view.php?id=<?php echo $group['created_by']; ?>">
                                        <?php echo htmlspecialchars($group['creator_name']); ?>
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <div class="sticky-sidebar">
                <!-- Stats -->
                <div class="stats-card mb-3">
                    <h6><i class="bi bi-graph-up"></i> Group Stats</h6>
                    <div class="row text-center mt-3">
                        <div class="col-6 mb-2">
                            <h4 class="mb-0"><?php echo $group['member_count']; ?></h4>
                            <small>Members</small>
                        </div>
                        <div class="col-6 mb-2">
                            <h4 class="mb-0"><?php echo $group['post_count']; ?></h4>
                            <small>Posts</small>
                        </div>
                    </div>
                </div>

                <!-- Recent Members -->
                <div class="card mb-3">
                    <div class="card-header">
                        <h6 class="mb-0">Recent Members</h6>
                    </div>
                    <div class="list-group list-group-flush">
                        <?php 
                        $recentMembers = array_slice($members, 0, 5);
                        foreach ($recentMembers as $member): 
                        ?>
                            <a href="<?php echo APP_URL; ?>/profile/view.php?id=<?php echo $member['user_id']; ?>" 
                               class="list-group-item list-group-item-action">
                                <div class="d-flex align-items-center">
                                    <img src="<?php echo getAvatarUrl($member['profile_picture']); ?>" 
                                         class="rounded-circle me-2" 
                                         width="30" height="30"
                                         alt="<?php echo htmlspecialchars($member['full_name']); ?>">
                                    <small><?php echo htmlspecialchars($member['full_name']); ?></small>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                    <div class="card-footer text-center">
                        <a href="#members" data-bs-toggle="tab" class="small">View all members</a>
                    </div>
                </div>

                <!-- Suggested Groups -->
                <?php if (!empty($suggestedGroups)): ?>
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">
                                <i class="bi bi-compass"></i> Suggested Groups
                            </h6>
                        </div>
                        <div class="list-group list-group-flush">
                            <?php foreach ($suggestedGroups as $suggested): ?>
                                <div class="list-group-item suggested-group-card"
                                     onclick="window.location.href='<?php echo APP_URL; ?>/groups/view.php?id=<?php echo $suggested['id']; ?>'">
                                    <div class="d-flex align-items-center mb-2">
                                        <img src="<?php echo getAvatarUrl($suggested['group_avatar']); ?>" 
                                             class="rounded me-2" 
                                             width="40" height="40"
                                             alt="<?php echo htmlspecialchars($suggested['group_name']); ?>">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-0 small"><?php echo htmlspecialchars($suggested['group_name']); ?></h6>
                                            <small class="text-muted">
                                                <i class="bi bi-people"></i> <?php echo $suggested['member_count']; ?> members
                                            </small>
                                        </div>
                                    </div>
                                    <button class="btn btn-sm btn-primary w-100" 
                                            onclick="event.stopPropagation(); joinGroup(<?php echo $suggested['id']; ?>, this)">
                                        <i class="bi bi-plus"></i> Join
                                    </button>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="card-footer text-center">
                            <a href="<?php echo APP_URL; ?>/groups/" class="small">Discover more groups</a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Toast Container -->
<div class="position-fixed top-0 end-0 p-3" style="z-index: 11000">
    <div id="groupToast" 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';

function showToast(message, type = 'success') {
    const toastEl = document.getElementById('groupToast');
    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 performAction(action, extraData, btn, successCallback) {
    const originalHTML = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Loading...';
    
    $.post(apiUrl, {
        action: action,
        group_id: groupId,
        ...extraData
    }, function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            if (successCallback) {
                successCallback(response);
            } else {
                setTimeout(() => location.reload(), 1000);
            }
        } else {
            showToast(response.message, 'error');
            btn.disabled = false;
            btn.innerHTML = originalHTML;
        }
    }, 'json').fail(function() {
        showToast('An error occurred', 'error');
        btn.disabled = false;
        btn.innerHTML = originalHTML;
    });
}

function joinGroup(gId, btn) {
    performAction('join', {}, btn);
}

function leaveGroup(gId, btn) {
    if (confirm('Are you sure you want to leave this group?')) {
        performAction('leave', {}, btn);
    }
}

function approveMember(memberId, btn) {
    performAction('approve_member', {member_id: memberId}, btn, function() {
        $('#request-' + memberId).fadeOut();
    });
}

function rejectMember(memberId, btn) {
    performAction('reject_member', {member_id: memberId}, btn, function() {
        $('#request-' + memberId).fadeOut();
    });
}

function removeMember(memberId, memberName) {
    if (confirm('Are you sure you want to remove ' + memberName + ' from this group?')) {
        performAction('remove_member', {member_id: memberId}, 
            document.querySelector(`[onclick*="removeMember(${memberId}"]`));
    }
}

function updateRole(memberId, newRole) {
    const action = newRole === 'moderator' ? 'Make Moderator' : 'Remove Moderator';
    if (confirm('Are you sure you want to ' + action + '?')) {
        performAction('update_role', {member_id: memberId, role: newRole}, 
            document.querySelector(`[onclick*="updateRole(${memberId}"]`));
    }
}

function createPost(event) {
    event.preventDefault();
    const form = event.target;
    const content = form.content.value;
    
    $.post(apiUrl, {
        action: 'create_post',
        group_id: groupId,
        content: content
    }, function(response) {
        if (response.success) {
            showToast('Post created successfully', 'success');
            form.reset();
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(response.message, 'error');
        }
    }, 'json');
}

function deletePost(postId) {
    if (confirm('Are you sure you want to delete this post?')) {
        $.post(apiUrl, {
            action: 'delete_post',
            group_id: groupId,
            post_id: postId
        }, function(response) {
            if (response.success) {
                showToast('Post deleted', 'success');
                $('#post-' + postId).fadeOut();
            } else {
                showToast(response.message, 'error');
            }
        }, 'json');
    }
}

function togglePin(postId) {
    $.post(apiUrl, {
        action: 'toggle_pin',
        group_id: groupId,
        post_id: postId
    }, function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(response.message, 'error');
        }
    }, 'json');
}

function likePost(postId, btn) {
    $.post(apiUrl, {
        action: 'like_post',
        group_id: groupId,
        post_id: postId
    }, function(response) {
        if (response.success) {
            const icon = btn.querySelector('i');
            const countSpan = document.getElementById('likes-count-' + postId);
            
            if (response.action === 'liked') {
                btn.classList.add('btn-primary');
                btn.classList.remove('btn-outline-primary');
                icon.classList.add('bi-heart-fill');
                icon.classList.remove('bi-heart');
                countSpan.textContent = parseInt(countSpan.textContent) + 1;
            } else {
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-outline-primary');
                icon.classList.remove('bi-heart-fill');
                icon.classList.add('bi-heart');
                countSpan.textContent = parseInt(countSpan.textContent) - 1;
            }
        }
    }, 'json');
}

function toggleComments(postId) {
    const commentsSection = $(`#comments-${postId}`);
    commentsSection.toggleClass('d-none');
    
    if (!commentsSection.hasClass('d-none') && !commentsSection.data('loaded')) {
        loadComments(postId);
        commentsSection.data('loaded', true);
    }
}

function loadComments(postId) {
    $.get(apiUrl, {
        action: 'get_comments',
        post_id: postId
    }, function(response) {
        if (response.success && response.comments) {
            const container = $('#comment-list-' + postId);
            container.empty();
            
            response.comments.forEach(comment => {
                const commentHtml = `
                    <div class="comment-item">
                        <div class="d-flex align-items-start gap-2">
                            <img src="${comment.profile_picture || '<?php echo APP_URL; ?>/assets/images/default-avatar.png'}" 
                                 class="rounded-circle" 
                                 width="32" height="32">
                            <div class="flex-grow-1">
                                <strong class="small">${comment.full_name}</strong>
                                <p class="mb-1 small">${comment.content}</p>
                                <small class="text-muted">
                                    <i class="bi bi-clock"></i> ${comment.time_ago}
                                </small>
                            </div>
                        </div>
                    </div>
                `;
                container.append(commentHtml);
            });
        }
    }, 'json');
}

function addComment(event, postId) {
    event.preventDefault();
    const form = event.target;
    const content = form.content.value;
    
    $.post(apiUrl, {
        action: 'comment',
        group_id: groupId,
        post_id: postId,
        content: content
    }, function(response) {
        if (response.success) {
            form.reset();
            loadComments(postId);
            
            // Update comment count
            const countSpan = document.getElementById('comments-count-' + postId);
            countSpan.textContent = parseInt(countSpan.textContent) + 1;
        } else {
            showToast(response.message, 'error');
        }
    }, 'json');
}
</script>

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