<!-- 
    ============================================================================
    posts/post-card Enhanced Post Card with Source Badges
    ============================================================================
-->
<div class="card border-0 shadow-sm post-card" data-post-id="<?php echo $post['id']; ?>">
    <div class="card-body">
        <!-- Post Header -->
        <div class="post-header">
            <img src="<?php echo getAvatarUrl($post['profile_picture']); ?>" 
                 class="post-avatar"
                 alt="<?php echo htmlspecialchars($post['full_name']); ?>">
            <div class="flex-grow-1">
                <h6 class="mb-0">
                    <a href="<?php echo APP_URL; ?>/friends/profile.php?id=<?php echo $post['user_id']; ?>" 
                       class="text-decoration-none text-dark">
                        <?php echo htmlspecialchars($post['full_name']); ?>
                    </a>
                    
                    <?php if ($post['user_type'] == 'extension_officer'): ?>
                        <span class="post-user-type-badge badge-extension">
                            <i class="bi bi-person-check"></i> Extension Officer
                        </span>
                    <?php elseif ($post['user_type'] == 'buyer'): ?>
                        <span class="post-user-type-badge badge-buyer">
                            <i class="bi bi-cart"></i> Buyer
                        </span>
                    <?php endif; ?>
                    
                    <?php if ($post['post_type'] == 'tip'): ?>
                        <span class="post-user-type-badge badge-tip">
                            <i class="bi bi-lightbulb"></i> Agricultural Tip
                        </span>
                    <?php endif; ?>
                </h6>
                <small class="text-muted">
                    <?php echo timeAgo($post['created_at']); ?>
                    <?php if ($post['visibility'] === 'friends'): ?>
                        <i class="bi bi-people-fill" title="Friends only"></i>
                    <?php elseif ($post['visibility'] === 'private'): ?>
                        <i class="bi bi-lock-fill" title="Only me"></i>
                    <?php else: ?>
                        <i class="bi bi-globe" title="Public"></i>
                    <?php endif; ?>
                </small>
                
                <?php if (isset($post['source_type'])): ?>
                    <div class="post-source-badge">
                        <?php
                        $sourceLabels = [
                            'friend' => '👥 From friend',
                            'friend_of_friend' => '🔗 Friend of friend',
                            'agricultural_tip' => '💡 Agricultural tip',
                            'extension_worker_local' => '📍 Local extension officer',
                            'buyer_local' => '🏪 Local buyer',
                            'district_popular' => '🔥 Trending in your area',
                            'extension_worker_external' => '🌍 Extension officer',
                            'own_post' => '✏️ Your post'
                        ];
                        echo $sourceLabels[$post['source_type']] ?? '';
                        ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <?php if (isset($userId) && $post['user_id'] == $userId): ?>
                <div class="dropdown">
                    <button class="btn btn-link text-muted" data-bs-toggle="dropdown">
                        <i class="bi bi-three-dots"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li>
                            <a class="dropdown-item" href="#" onclick="editPost(<?php echo $post['id']; ?>); return false;">
                                <i class="bi bi-pencil"></i> Edit
                            </a>
                        </li>
                        <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'; ?>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <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="post-content">
            <?php if ($post['is_pinned']): ?>
                <div class="alert alert-info py-1 px-2 small mb-2">
                    <i class="bi bi-pin-fill"></i> Pinned post
                </div>
            <?php endif; ?>
            
            <p class="mb-2"><?php echo nl2br(htmlspecialchars($post['content'])); ?></p>
            
            <?php if ($post['location']): ?>
                <p class="text-muted small mb-2">
                    <i class="bi bi-geo-alt"></i> <?php echo htmlspecialchars($post['location']); ?>
                </p>
            <?php endif; ?>
        </div>
        
        <!-- Post Images -->
        <?php if ($post['media_urls']): ?>
            <?php 
            $images = json_decode($post['media_urls'], true);
            if ($images && is_array($images)):
                $imageCount = count($images);
                $gridClass = $imageCount == 1 ? 'single' : ($imageCount == 2 ? 'double' : 'multiple');
            ?>
                <div class="post-images <?php echo $gridClass; ?>">
                    <?php foreach (array_slice($images, 0, 6) as $index => $image): ?>
                        <div class="position-relative">
                            <img src="<?php echo htmlspecialchars($image); ?>" 
                                 alt="Post image"
                                 onclick="openImageModal(<?php echo $post['id']; ?>, <?php echo $index; ?>)">
                            <?php if ($index == 5 && $imageCount > 6): ?>
                                <div class="position-absolute top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center bg-dark bg-opacity-50 text-white">
                                    <h3>+<?php echo $imageCount - 6; ?></h3>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
        
        <!-- Post Stats -->
        <div class="d-flex justify-content-between align-items-center my-2">
            <div>
                <?php if ($post['like_count'] > 0): ?>
                    <small class="text-muted">
                        <i class="bi bi-heart-fill text-danger"></i> 
                        <?php echo $post['like_count']; ?> <?php echo $post['like_count'] == 1 ? 'like' : 'likes'; ?>
                    </small>
                <?php endif; ?>
            </div>
            <div>
                <?php if ($post['comment_count'] > 0): ?>
                    <small class="text-muted">
                        <a href="#" onclick="toggleComments(<?php echo $post['id']; ?>); return false;" class="text-decoration-none text-muted">
                            <?php echo $post['comment_count']; ?> <?php echo $post['comment_count'] == 1 ? 'comment' : 'comments'; ?>
                        </a>
                    </small>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Post Actions -->
        <div class="post-actions">
            <button class="post-action-btn <?php echo $post['user_liked'] ? 'liked' : ''; ?>" 
                    onclick="toggleLike(<?php echo $post['id']; ?>)"
                    id="likeBtn<?php echo $post['id']; ?>">
                <i class="bi bi-heart<?php echo $post['user_liked'] ? '-fill' : ''; ?>" 
                   id="likeIcon<?php echo $post['id']; ?>"></i> 
                <span id="likeText<?php echo $post['id']; ?>"><?php echo $post['user_liked'] ? 'Liked' : 'Like'; ?></span>
            </button>
            
            <button class="post-action-btn" onclick="toggleComments(<?php echo $post['id']; ?>)">
                <i class="bi bi-chat"></i> Comment
            </button>
            
            <button class="post-action-btn" onclick="sharePost(<?php echo $post['id']; ?>)">
                <i class="bi bi-share"></i> Share
            </button>
        </div>
        
        <!-- Comments Section -->
        <div class="comment-section" id="comments<?php echo $post['id']; ?>" style="display: none;">
            <!-- Comment Input -->
            <div class="d-flex gap-2 mb-3">
                <img src="<?php echo getAvatarUrl($_SESSION['profile_picture']); ?>" 
                     class="comment-avatar"
                     alt="You">
                <div class="flex-grow-1">
                    <input type="text" 
                           class="form-control" 
                           id="commentInput<?php echo $post['id']; ?>"
                           placeholder="Write a comment..."
                           onkeypress="if(event.key === 'Enter') submitComment(<?php echo $post['id']; ?>)">
                </div>
            </div>
            
            <!-- Comments List -->
            <div id="commentsList<?php echo $post['id']; ?>">
                <?php 
                if (isset($postClass)) {
                    $comments = $postClass->getComments($post['id']);
                } else {
                    $database = new Database();
                    $db = $database->getConnection();
                    require_once __DIR__ . '/../classes/Post_Enhanced.php';
                    $postClass = new \App\Post($db);
                    $comments = $postClass->getComments($post['id']);
                }
                
                if (!empty($comments)):
                    foreach ($comments as $comment):
                ?>
                    <div class="comment">
                        <img src="<?php echo getAvatarUrl($comment['profile_picture']); ?>" 
                             class="comment-avatar"
                             alt="<?php echo htmlspecialchars($comment['full_name']); ?>">
                        <div class="flex-grow-1">
                            <div class="comment-content">
                                <div class="comment-author"><?php echo htmlspecialchars($comment['full_name']); ?></div>
                                <div class="comment-text"><?php echo nl2br(htmlspecialchars($comment['content'])); ?></div>
                            </div>
                            <div class="comment-time d-flex gap-3">
                                <?php echo timeAgo($comment['created_at']); ?>
                                <a href="#" class="text-decoration-none text-muted">Like</a>
                                <a href="#" class="text-decoration-none text-muted">Reply</a>
                            </div>
                            
                            <!-- Replies -->
                            <?php if (!empty($comment['replies'])): ?>
                                <div class="ms-4 mt-2">
                                    <?php foreach ($comment['replies'] as $reply): ?>
                                        <div class="comment mb-2">
                                            <img src="<?php echo getAvatarUrl($reply['profile_picture']); ?>" 
                                                 class="comment-avatar"
                                                 alt="<?php echo htmlspecialchars($reply['full_name']); ?>">
                                            <div class="flex-grow-1">
                                                <div class="comment-content">
                                                    <div class="comment-author"><?php echo htmlspecialchars($reply['full_name']); ?></div>
                                                    <div class="comment-text"><?php echo nl2br(htmlspecialchars($reply['content'])); ?></div>
                                                </div>
                                                <div class="comment-time">
                                                    <?php echo timeAgo($reply['created_at']); ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php 
                    endforeach;
                else:
                ?>
                    <p class="text-muted text-center small">No comments yet. Be the first to comment!</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function toggleComments(postId) {
    $(`#comments${postId}`).slideToggle();
}

function toggleLike(postId) {
    const btn = $(`#likeBtn${postId}`);
    const icon = $(`#likeIcon${postId}`);
    const text = $(`#likeText${postId}`);
    
    $.ajax({
        url: '<?php echo APP_URL; ?>/posts/toggle-like.php',
        type: 'POST',
        data: { post_id: postId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                if (response.liked) {
                    btn.addClass('liked');
                    icon.removeClass('bi-heart').addClass('bi-heart-fill');
                    text.text('Liked');
                } else {
                    btn.removeClass('liked');
                    icon.removeClass('bi-heart-fill').addClass('bi-heart');
                    text.text('Like');
                }
            } else {
                alert('Failed to toggle like: ' + (response.error || 'Unknown error'));
            }
        },
        error: function(xhr, status, error) {
            console.error('Error toggling like:', error);
            alert('Error toggling like. Please try again.');
        }
    });
}

function submitComment(postId) {
    const commentInput = $(`#commentInput${postId}`);
    const content = commentInput.val().trim();
    
    if (!content) return;
    
    $.ajax({
        url: '<?php echo APP_URL; ?>/posts/add-comment.php',
        type: 'POST',
        data: {
            post_id: postId,
            content: content
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                location.reload();
            } else {
                alert('Failed to add comment: ' + (response.error || 'Unknown error'));
            }
        },
        error: function(xhr, status, error) {
            console.error('Error adding comment:', error);
            alert('Error adding comment. Please try again.');
        }
    });
}

function deletePost(postId) {
    if (confirm('Are you sure you want to delete this post?')) {
        $.ajax({
            url: '<?php echo APP_URL; ?>/posts/delete.php',
            type: 'POST',
            data: { post_id: postId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $(`.post-card[data-post-id="${postId}"]`).fadeOut(function() {
                        $(this).remove();
                    });
                } else {
                    alert('Failed to delete post: ' + (response.error || 'Unknown error'));
                }
            },
            error: function() {
                alert('Error deleting post. Please try again.');
            }
        });
    }
}

function sharePost(postId) {
    const url = '<?php echo APP_URL; ?>/posts/view.php?id=' + postId;
    if (navigator.share) {
        navigator.share({
            title: 'Check out this post',
            url: url
        }).catch(err => console.log('Error sharing:', err));
    } else {
        const tempInput = document.createElement('input');
        tempInput.value = url;
        document.body.appendChild(tempInput);
        tempInput.select();
        document.execCommand('copy');
        document.body.removeChild(tempInput);
        alert('Link copied to clipboard!');
    }
}

function openImageModal(postId, index) {
    console.log('Opening image', postId, index);
}

function editPost(postId) {
    alert('Edit post functionality - Coming soon!');
}

function togglePin(postId) {
    if (confirm('Toggle pin status for this post?')) {
        $.ajax({
            url: '<?php echo APP_URL; ?>/posts/toggle-pin.php',
            type: 'POST',
            data: { post_id: postId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Failed to toggle pin: ' + (response.error || 'Unknown error'));
                }
            },
            error: function() {
                alert('Error toggling pin. Please try again.');
            }
        });
    }
}
</script>