<?php
/**
 * ============================================================================
 * groups/view_enhanced.php - Complete Facebook-Style Group View
 * Features: Post CRUD, Media Upload, Comments, Reactions
 * ============================================================================
 */

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');
$isPending = ($group['membership_status'] === 'pending');
$isAdmin = in_array($group['role'], ['admin', 'moderator']);

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

// Check which posts user has liked
foreach ($posts as &$post) {
    $post['user_has_liked'] = $groupClass->hasLikedPost($post['id'], $userId);
}

$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);
}

.media-preview {
    max-height: 500px;
    overflow: hidden;
    border-radius: 8px;
}

.media-grid {
    display: grid;
    gap: 5px;
}

.media-grid.grid-1 { grid-template-columns: 1fr; }
.media-grid.grid-2 { grid-template-columns: repeat(2, 1fr); }
.media-grid.grid-3 { grid-template-columns: repeat(3, 1fr); }
.media-grid.grid-4 { grid-template-columns: repeat(2, 1fr); }

.media-item {
    position: relative;
    overflow: hidden;
    border-radius: 8px;
    cursor: pointer;
}

.media-item img {
    width: 100%;
    height: 250px;
    object-fit: cover;
}

.media-item.grid-4:nth-child(1),
.media-item.grid-4:nth-child(2) {
    height: 250px;
}

.upload-preview {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-top: 10px;
}

.upload-preview-item {
    position: relative;
    width: 100px;
    height: 100px;
    border-radius: 8px;
    overflow: hidden;
}

.upload-preview-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.upload-preview-item .remove-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    background: rgba(0,0,0,0.7);
    color: white;
    border: none;
    border-radius: 50%;
    width: 25px;
    height: 25px;
    cursor: pointer;
}

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

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

.sticky-sidebar {
    position: sticky;
    top: 20px;
}

.modal-media {
    max-width: 100%;
    max-height: 80vh;
}
</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>
                    <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): ?>
                    <div class="btn-group">
                        <button class="btn btn-outline-secondary" onclick="window.location.href='<?php echo APP_URL; ?>/groups/members.php?id=<?php echo $groupId; ?>'">
                            <i class="bi bi-people"></i> View Members
                        </button>
                        <button class="btn btn-outline-danger" onclick="leaveGroup(<?php echo $groupId; ?>, this)">
                            <i class="bi bi-box-arrow-right"></i> Leave
                        </button>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <?php if ($isMember): ?>
                <!-- Create Post Form -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form id="createPostForm" enctype="multipart/form-data">
                            <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" 
                                          id="postContent"
                                          rows="3" 
                                          placeholder="What's on your mind?"></textarea>
                            </div>
                            
                            <!-- Media Upload Preview -->
                            <div id="uploadPreview" class="upload-preview d-none"></div>
                            
                            <div class="d-flex justify-content-between align-items-center mt-2">
                                <div class="btn-group">
                                    <label class="btn btn-sm btn-outline-success mb-0" for="imageUpload">
                                        <i class="bi bi-image"></i> Photo
                                    </label>
                                    <input type="file" 
                                           id="imageUpload" 
                                           name="images[]" 
                                           accept="image/*" 
                                           multiple 
                                           class="d-none" 
                                           onchange="previewImages(this)">
                                    
                                    <label class="btn btn-sm btn-outline-danger mb-0" for="videoUpload">
                                        <i class="bi bi-camera-video"></i> Video
                                    </label>
                                    <input type="file" 
                                           id="videoUpload" 
                                           name="video" 
                                           accept="video/*" 
                                           class="d-none"
                                           onchange="previewVideo(this)">
                                </div>
                                <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']); ?>
                                                <?php if ($post['updated_at'] && $post['updated_at'] != $post['created_at']): ?>
                                                    <span class="text-muted"> · Edited</span>
                                                <?php endif; ?>
                                            </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 ($post['user_id'] == $userId): ?>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="editPost(<?php echo $post['id']; ?>); return false;">
                                                            <i class="bi bi-pencil"></i> Edit Post
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                                <?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 id="post-content-<?php echo $post['id']; ?>"><?php echo nl2br(htmlspecialchars($post['content'])); ?></p>
                                    
                                    <?php if ($post['media_urls']): ?>
                                        <?php 
                                        $mediaUrls = json_decode($post['media_urls'], true);
                                        $mediaCount = count($mediaUrls);
                                        $gridClass = $mediaCount == 1 ? 'grid-1' : ($mediaCount == 2 ? 'grid-2' : ($mediaCount == 3 ? 'grid-3' : 'grid-4'));
                                        ?>
                                        <div class="media-grid <?php echo $gridClass; ?>">
                                            <?php foreach ($mediaUrls as $index => $url): ?>
                                                <?php if (strpos($url, 'videos/') !== false): ?>
                                                    <div class="media-item">
                                                        <video controls style="width: 100%; max-height: 400px;">
                                                            <source src="<?php echo APP_URL . '/' . htmlspecialchars($url); ?>" type="video/mp4">
                                                        </video>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="media-item" onclick="openMediaModal('<?php echo htmlspecialchars($url); ?>')">
                                                        <img src="<?php echo APP_URL . '/' . htmlspecialchars($url); ?>" alt="Post media">
                                                        <?php if ($mediaCount > 4 && $index == 3): ?>
                                                            <div style="position: absolute; inset: 0; background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center; color: white; font-size: 2rem;">
                                                                +<?php echo $mediaCount - 4; ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php endif; ?>
                                                <?php if ($mediaCount > 4 && $index == 3) break; ?>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <!-- Post Stats -->
                                <div class="border-top pt-2 mb-2">
                                    <div class="d-flex justify-content-between text-muted small">
                                        <span style="cursor: pointer;" onclick="showLikes(<?php echo $post['id']; ?>)">
                                            <i class="bi bi-heart-fill text-danger"></i> 
                                            <span id="likes-count-<?php echo $post['id']; ?>">
                                                <?php echo $post['likes_count']; ?>
                                            </span>
                                        </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 <?php echo $post['user_has_liked'] ? 'btn-primary' : 'btn-outline-primary'; ?> flex-fill" 
                                                id="like-btn-<?php echo $post['id']; ?>"
                                                onclick="likePost(<?php echo $post['id']; ?>, this)">
                                            <i class="bi bi-heart<?php echo $post['user_has_liked'] ? '-fill' : ''; ?>"></i> 
                                            <?php echo $post['user_has_liked'] ? 'Liked' : '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 loaded dynamically -->
                                    </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>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <div class="sticky-sidebar">
                <!-- Stats -->
                <div class="card mb-3 border-0 shadow-sm" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                    <div class="card-body">
                        <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>
                </div>

                <!-- Recent Members -->
                <div class="card mb-3 border-0 shadow-sm">
                    <div class="card-header bg-transparent">
                        <div class="d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">Recent Members</h6>
                            <a href="<?php echo APP_URL; ?>/groups/members.php?id=<?php echo $groupId; ?>" class="small">View all</a>
                        </div>
                    </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>

                <?php if ($isAdmin && !empty($pendingRequests)): ?>
                    <!-- Pending Requests -->
                    <div class="card mb-3 border-0 shadow-sm">
                        <div class="card-header bg-warning text-dark">
                            <h6 class="mb-0">
                                <i class="bi bi-clock"></i> Pending Requests
                                <span class="badge bg-dark"><?php echo count($pendingRequests); ?></span>
                            </h6>
                        </div>
                        <div class="list-group list-group-flush">
                            <?php foreach (array_slice($pendingRequests, 0, 3) as $request): ?>
                                <div class="list-group-item" id="request-<?php echo $request['user_id']; ?>">
                                    <div class="d-flex align-items-center mb-2">
                                        <img src="<?php echo getAvatarUrl($request['profile_picture']); ?>" 
                                             class="rounded-circle me-2" 
                                             width="30" height="30">
                                        <small class="flex-grow-1"><?php echo htmlspecialchars($request['full_name']); ?></small>
                                    </div>
                                    <div class="btn-group btn-group-sm w-100">
                                        <button class="btn btn-success" onclick="approveMember(<?php echo $request['user_id']; ?>, this)">
                                            <i class="bi bi-check"></i>
                                        </button>
                                        <button class="btn btn-danger" onclick="rejectMember(<?php echo $request['user_id']; ?>, this)">
                                            <i class="bi bi-x"></i>
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Edit Post Modal -->
<div class="modal fade" id="editPostModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Post</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editPostForm">
                    <input type="hidden" id="editPostId">
                    <textarea class="form-control" id="editPostContent" rows="5" required></textarea>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveEditPost()">Save Changes</button>
            </div>
        </div>
    </div>
</div>

<!-- Media Modal -->
<div class="modal fade" id="mediaModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content bg-dark">
            <div class="modal-header border-0">
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <img id="modalImage" class="modal-media" src="" alt="Media">
            </div>
        </div>
    </div>
</div>

<!-- Likes Modal -->
<div class="modal fade" id="likesModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Likes</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="likesContent">
                <!-- Likes loaded dynamically -->
            </div>
        </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';
const postApiUrl = '<?php echo APP_URL; ?>/groups/ajax/post-actions.php';
const uploadApiUrl = '<?php echo APP_URL; ?>/groups/ajax/media-upload.php';

let selectedImages = [];
let selectedVideo = null;

// Preview images before upload
function previewImages(input) {
    selectedImages = Array.from(input.files);
    const preview = document.getElementById('uploadPreview');
    preview.innerHTML = '';
    preview.classList.remove('d-none');
    
    selectedImages.forEach((file, index) => {
        const reader = new FileReader();
        reader.onload = function(e) {
            const div = document.createElement('div');
            div.className = 'upload-preview-item';
            div.innerHTML = `
                <img src="${e.target.result}">
                <button type="button" class="remove-btn" onclick="removeImage(${index})">
                    <i class="bi bi-x"></i>
                </button>
            `;
            preview.appendChild(div);
        };
        reader.readAsDataURL(file);
    });
}

function removeImage(index) {
    selectedImages.splice(index, 1);
    const dataTransfer = new DataTransfer();
    selectedImages.forEach(file => dataTransfer.items.add(file));
    document.getElementById('imageUpload').files = dataTransfer.files;
    previewImages(document.getElementById('imageUpload'));
}

function previewVideo(input) {
    if (input.files && input.files[0]) {
        selectedVideo = input.files[0];
        const preview = document.getElementById('uploadPreview');
        preview.innerHTML = `
            <div class="alert alert-info">
                <i class="bi bi-camera-video"></i> Video selected: ${selectedVideo.name}
            </div>
        `;
        preview.classList.remove('d-none');
    }
}

// Create post with media
document.getElementById('createPostForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData();
    formData.append('action', 'create_post_with_media');
    formData.append('group_id', groupId);
    formData.append('content', document.getElementById('postContent').value);
    
    // Add images
    selectedImages.forEach((file, index) => {
        formData.append('images[]', file);
    });
    
    // Add video
    if (selectedVideo) {
        formData.append('video', selectedVideo);
    }
    
    const btn = this.querySelector('button[type="submit"]');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Posting...';
    
    $.ajax({
        url: postApiUrl,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                location.reload();
            } else {
                alert(response.message);
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-send"></i> Post';
            }
        },
        error: function() {
            alert('Upload failed');
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-send"></i> Post';
        }
    });
});

// Edit post
function editPost(postId) {
    $.get(postApiUrl, {
        action: 'get_post',
        post_id: postId
    }, function(response) {
        if (response.success) {
            $('#editPostId').val(postId);
            $('#editPostContent').val(response.post.content);
            $('#editPostModal').modal('show');
        }
    });
}

function saveEditPost() {
    const postId = $('#editPostId').val();
    const content = $('#editPostContent').val();
    
    $.post(postApiUrl, {
        action: 'edit_post',
        group_id: groupId,
        post_id: postId,
        content: content
    }, function(response) {
        if (response.success) {
            $('#post-content-' + postId).html(content.replace(/\n/g, '<br>'));
            $('#editPostModal').modal('hide');
        } else {
            alert(response.message);
        }
    });
}

// Other functions (like, comment, etc.) continue...
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');
                btn.innerHTML = icon.outerHTML + ' Liked';
                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');
                btn.innerHTML = icon.outerHTML + ' Like';
                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);
            const countSpan = document.getElementById('comments-count-' + postId);
            countSpan.textContent = parseInt(countSpan.textContent) + 1;
        }
    }, 'json');
}

function deletePost(postId) {
    if (confirm('Delete this post?')) {
        $.post(apiUrl, {
            action: 'delete_post',
            group_id: groupId,
            post_id: postId
        }, function(response) {
            if (response.success) {
                $('#post-' + postId).fadeOut();
            }
        }, 'json');
    }
}

function togglePin(postId) {
    $.post(apiUrl, {
        action: 'toggle_pin',
        group_id: groupId,
        post_id: postId
    }, function(response) {
        if (response.success) {
            location.reload();
        }
    }, 'json');
}

function openMediaModal(url) {
    $('#modalImage').attr('src', '<?php echo APP_URL; ?>/' + url);
    $('#mediaModal').modal('show');
}

function showLikes(postId) {
    $.get(postApiUrl, {
        action: 'get_post_likes',
        post_id: postId
    }, function(response) {
        if (response.success) {
            const content = $('#likesContent');
            content.empty();
            
            if (response.likes.length === 0) {
                content.html('<p class="text-muted text-center">No likes yet</p>');
            } else {
                response.likes.forEach(like => {
                    content.append(`
                        <div class="d-flex align-items-center mb-2">
                            <img src="${like.profile_picture || '<?php echo APP_URL; ?>/assets/images/default-avatar.png'}" 
                                 class="rounded-circle me-2" width="40" height="40">
                            <div>
                                <strong>${like.full_name}</strong><br>
                                <small class="text-muted">${like.time_ago}</small>
                            </div>
                        </div>
                    `);
                });
            }
            
            $('#likesModal').modal('show');
        }
    });
}

function joinGroup(gId, btn) {
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
    $.post(apiUrl, {action: 'join', group_id: gId}, () => location.reload());
}

function leaveGroup(gId, btn) {
    if (confirm('Leave this group?')) {
        btn.disabled = true;
        $.post(apiUrl, {action: 'leave', group_id: gId}, () => location.reload());
    }
}

function approveMember(memberId, btn) {
    btn.disabled = true;
    $.post(apiUrl, {
        action: 'approve_member',
        group_id: groupId,
        member_id: memberId
    }, function(response) {
        if (response.success) {
            $('#request-' + memberId).fadeOut();
        }
    });
}

function rejectMember(memberId, btn) {
    btn.disabled = true;
    $.post(apiUrl, {
        action: 'reject_member',
        group_id: groupId,
        member_id: memberId
    }, function(response) {
        if (response.success) {
            $('#request-' + memberId).fadeOut();
        }
    });
}
</script>

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