<?php
/**
 * ============================================================================
 * posts/index.php - Enhanced Social Feed Page with Stories
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Feed';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Load classes
require_once __DIR__ . '/../classes/Post_Enhanced.php';
require_once __DIR__ . '/../classes/Story.php';

$postClass = new \App\Post($db);
$storyClass = new \App\Story($db);

// Get posts using enhanced feed
$posts = $postClass->getEnhancedFeed($userId);

// Get active stories
$stories = $storyClass->getActiveFeedStories($userId);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
/* Stories Bar */
.stories-container {
    background: white;
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    overflow-x: auto;
    white-space: nowrap;
}

.stories-scroll {
    display: flex;
    gap: 15px;
    padding: 5px 0;
}

.story-item {
    flex-shrink: 0;
    width: 100px;
    cursor: pointer;
    text-align: center;
}

.story-avatar-wrapper {
    position: relative;
    width: 80px;
    height: 80px;
    margin: 0 auto 8px;
}

.story-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #0d6efd;
    padding: 3px;
    background: white;
}

.story-avatar.viewed {
    border-color: #dee2e6;
}

.story-avatar.own {
    border-color: #28a745;
}

.story-add-btn {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 28px;
    height: 28px;
    background: #0d6efd;
    border: 3px solid white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 18px;
    font-weight: bold;
}

.story-name {
    font-size: 12px;
    color: #1c1e21;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100px;
}

/* Create Post Card */
.create-post-card {
    border-radius: 10px;
    margin-bottom: 20px;
}

.post-card {
    border-radius: 10px;
    margin-bottom: 20px;
    transition: box-shadow 0.3s;
}

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

.post-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 15px;
}

.post-avatar {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    object-fit: cover;
}

.post-user-type-badge {
    font-size: 11px;
    padding: 2px 8px;
    border-radius: 12px;
    margin-left: 5px;
}

.badge-extension {
    background: #17a2b8;
    color: white;
}

.badge-buyer {
    background: #28a745;
    color: white;
}

.badge-tip {
    background: #ffc107;
    color: #000;
}

.post-source-badge {
    font-size: 10px;
    color: #6c757d;
    margin-top: 2px;
}

.post-images {
    display: grid;
    gap: 5px;
    margin: 15px 0;
}

.post-images.single {
    grid-template-columns: 1fr;
}

.post-images.double {
    grid-template-columns: repeat(2, 1fr);
}

.post-images.multiple {
    grid-template-columns: repeat(3, 1fr);
}

.post-images img {
    width: 100%;
    height: 250px;
    object-fit: cover;
    border-radius: 8px;
    cursor: pointer;
}

.post-actions {
    display: flex;
    justify-content: space-around;
    padding: 10px 0;
    border-top: 1px solid #dee2e6;
    border-bottom: 1px solid #dee2e6;
}

.post-action-btn {
    background: none;
    border: none;
    color: #6c757d;
    cursor: pointer;
    padding: 5px 15px;
    transition: color 0.3s;
}

.post-action-btn:hover {
    color: #0d6efd;
}

.post-action-btn.liked {
    color: #dc3545;
}

.comment-section {
    margin-top: 15px;
}

.comment {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}

.comment-avatar {
    width: 35px;
    height: 35px;
    border-radius: 50%;
    object-fit: cover;
}

.comment-content {
    flex: 1;
    background: #f1f3f5;
    padding: 10px 15px;
    border-radius: 18px;
}

.comment-author {
    font-weight: 600;
    font-size: 0.9rem;
}

.comment-text {
    margin-top: 5px;
    font-size: 0.9rem;
}

.comment-time {
    font-size: 0.75rem;
    color: #6c757d;
    margin-top: 5px;
}

/* Story Modal */
.story-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.9);
    z-index: 9999;
}

.story-modal.active {
    display: flex;
    align-items: center;
    justify-content: center;
}

.story-content {
    max-width: 500px;
    max-height: 90vh;
    position: relative;
}

.story-media {
    max-width: 100%;
    max-height: 90vh;
    border-radius: 10px;
}

.story-close {
    position: absolute;
    top: 20px;
    right: 20px;
    color: white;
    font-size: 30px;
    cursor: pointer;
    background: rgba(0,0,0,0.5);
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.story-user-info {
    position: absolute;
    top: 20px;
    left: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.story-user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: 2px solid white;
}

.story-user-name {
    color: white;
    font-weight: 600;
}

.story-time {
    color: #ccc;
    font-size: 12px;
}
</style>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-6 col-md-8">
            <!-- Stories Bar -->
            <div class="stories-container">
                <div class="stories-scroll">
                    <!-- User's Own Stories or Add Story -->
                    <?php
                    $ownStories = array_filter($stories, function($s) use ($userId) {
                        return $s['user_id'] == $userId;
                    });
                    $ownStoryData = !empty($ownStories) ? reset($ownStories) : null;
                    ?>
                    
                    <?php if ($ownStoryData): ?>
                        <!-- View Own Stories -->
                        <div class="story-item" onclick='viewStory(<?php echo json_encode($ownStoryData); ?>)'>
                            <div class="story-avatar-wrapper">
                                <img src="<?php echo getAvatarUrl($_SESSION['profile_picture']); ?>" 
                                     class="story-avatar own"
                                     alt="Your Story">
                                <?php if ($ownStoryData['total_stories'] > 1): ?>
                                    <div class="position-absolute top-0 end-0 badge bg-primary" style="font-size: 10px;">
                                        <?php echo $ownStoryData['total_stories']; ?>
                                    </div>
                                <?php endif; ?>
                                <div class="story-add-btn" onclick="event.stopPropagation(); openAddStoryModal();">+</div>
                            </div>
                            <div class="story-name">Your Story</div>
                        </div>
                    <?php else: ?>
                        <!-- Add Story (No existing stories) -->
                        <div class="story-item" onclick="openAddStoryModal()">
                            <div class="story-avatar-wrapper">
                                <img src="<?php echo getAvatarUrl($_SESSION['profile_picture']); ?>" 
                                     class="story-avatar own"
                                     alt="Your Story">
                                <div class="story-add-btn">+</div>
                            </div>
                            <div class="story-name">Add Story</div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Friend Stories -->
                    <?php foreach ($stories as $userStories): ?>
                        <?php if ($userStories['user_id'] != $userId): ?>
                        <div class="story-item" onclick='viewStory(<?php echo json_encode($userStories); ?>)'>
                            <div class="story-avatar-wrapper">
                                <img src="<?php echo getAvatarUrl($userStories['profile_picture']); ?>" 
                                     class="story-avatar <?php echo $userStories['has_unseen'] ? '' : 'viewed'; ?>"
                                     alt="<?php echo htmlspecialchars($userStories['full_name']); ?>">
                                <?php if ($userStories['total_stories'] > 1): ?>
                                    <div class="position-absolute top-0 end-0 badge bg-primary" style="font-size: 10px;">
                                        <?php echo $userStories['total_stories']; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="story-name"><?php echo htmlspecialchars($userStories['full_name']); ?></div>
                        </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <!-- Create Post Card -->
            <div class="card border-0 shadow-sm create-post-card">
                <div class="card-body">
                    <div class="d-flex gap-2">
                        <img src="<?php echo getAvatarUrl($_SESSION['profile_picture']); ?>" 
                             class="rounded-circle" 
                             width="40" height="40"
                             alt="<?php echo htmlspecialchars(getUserName()); ?>">
                        <button class="btn btn-light flex-grow-1 text-start" 
                                data-bs-toggle="modal" 
                                data-bs-target="#createPostModal">
                            What's on your mind, <?php echo htmlspecialchars(explode(' ', getUserName())[0]); ?>?
                        </button>
                    </div>
                    
                    <hr>
                    
                    <div class="d-flex justify-content-around">
                        <button class="btn btn-link text-decoration-none" 
                                onclick="openCreatePost('image')">
                            <i class="bi bi-image text-success"></i> Photo
                        </button>
                        <button class="btn btn-link text-decoration-none" 
                                onclick="openCreatePost('tip')">
                            <i class="bi bi-lightbulb text-warning"></i> Tip
                        </button>
                        <button class="btn btn-link text-decoration-none" 
                                onclick="openCreatePost('text')">
                            <i class="bi bi-pencil text-primary"></i> Post
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- Posts Feed -->
            <?php if (empty($posts)): ?>
                <div class="card border-0 shadow-sm text-center py-5">
                    <div class="card-body">
                        <i class="bi bi-inbox" style="font-size: 4rem; color: #dee2e6;"></i>
                        <h5 class="mt-3">No Posts Yet</h5>
                        <p class="text-muted">Start following farmers or create your first post!</p>
                        <a href="<?php echo APP_URL; ?>/friends/find-farmers.php" class="btn btn-primary">
                            Find Farmers
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($posts as $post): ?>
                    <?php include __DIR__ . '/post-card.php'; ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Create Post Modal -->
<div class="modal fade" id="createPostModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create Post</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createPostForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="mb-3">
                        <textarea class="form-control" 
                                  name="content" 
                                  rows="4" 
                                  placeholder="What's on your mind?"
                                  required></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Visibility</label>
                        <select class="form-select" name="visibility">
                            <option value="public">Public</option>
                            <option value="friends">Friends Only</option>
                            <option value="private">Only Me</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Add Photos (Optional)</label>
                        <input type="file" 
                               class="form-control" 
                               name="images[]" 
                               multiple 
                               accept="image/*">
                        <small class="text-muted">You can select multiple images</small>
                    </div>
                    
                    <div id="imagePreview" class="d-flex gap-2 flex-wrap"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-send"></i> Post
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Story Modal -->
<div class="modal fade" id="addStoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Stories</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addStoryForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Upload Photos/Videos (Multiple)</label>
                        <input type="file" 
                               class="form-control" 
                               name="media[]" 
                               accept="image/*,video/*"
                               multiple
                               required>
                        <small class="text-muted">Select multiple images/videos to create multiple stories at once. Each file can be up to 50MB.</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Caption (Optional - applies to all)</label>
                        <textarea class="form-control" 
                                  name="content" 
                                  rows="3" 
                                  placeholder="Add a caption..."></textarea>
                    </div>
                    
                    <div id="storyPreview" class="d-flex gap-2 flex-wrap"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="submitStoryBtn">
                        <i class="bi bi-plus-circle"></i> Add <span id="storyCount">Story</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Story Viewer Modal -->
<div class="story-modal" id="storyModal">
    <div class="story-close" onclick="closeStoryModal()">&times;</div>
    <div class="story-content" id="storyContent"></div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function openCreatePost(type) {
    $('#createPostModal').modal('show');
}

function openAddStoryModal() {
    $('#addStoryModal').modal('show');
}

// Preview images before upload
$('input[name="images[]"]').on('change', function() {
    const files = this.files;
    const preview = $('#imagePreview');
    preview.html('');
    
    if (files.length > 0) {
        for (let i = 0; i < files.length && i < 10; i++) {
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.append(`
                    <img src="${e.target.result}" 
                         class="img-thumbnail" 
                         style="width: 100px; height: 100px; object-fit: cover;">
                `);
            };
            reader.readAsDataURL(files[i]);
        }
    }
});

// Preview story media (multiple files)
$('input[name="media[]"]').on('change', function() {
    const files = this.files;
    const preview = $('#storyPreview');
    const storyCount = $('#storyCount');
    preview.html('');
    
    if (files.length > 0) {
        storyCount.text(files.length + ' ' + (files.length === 1 ? 'Story' : 'Stories'));
        
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const reader = new FileReader();
            
            reader.onload = function(e) {
                if (file.type.startsWith('image/')) {
                    preview.append(`
                        <div class="position-relative">
                            <img src="${e.target.result}" 
                                 class="img-thumbnail" 
                                 style="width: 100px; height: 100px; object-fit: cover;">
                            <span class="position-absolute top-0 start-0 badge bg-primary">${i + 1}</span>
                        </div>
                    `);
                } else if (file.type.startsWith('video/')) {
                    preview.append(`
                        <div class="position-relative">
                            <video class="img-thumbnail" style="width: 100px; height: 100px; object-fit: cover;">
                                <source src="${e.target.result}" type="${file.type}">
                            </video>
                            <span class="position-absolute top-0 start-0 badge bg-danger">
                                <i class="bi bi-play-fill"></i> ${i + 1}
                            </span>
                        </div>
                    `);
                }
            };
            
            reader.readAsDataURL(file);
        }
    } else {
        storyCount.text('Story');
    }
});

// Handle post creation
$('#createPostForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    $.ajax({
        url: '<?php echo APP_URL; ?>/posts/create.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                location.reload();
            } else {
                alert('Failed to create post: ' + (response.error || 'Unknown error'));
            }
        },
        error: function() {
            alert('Error creating post');
        }
    });
});

// Handle story creation (multiple files)
$('#addStoryForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const files = $('input[name="media[]"]')[0].files;
    
    if (files.length === 0) {
        alert('Please select at least one image or video');
        return;
    }
    
    // Disable submit button
    const submitBtn = $('#submitStoryBtn');
    submitBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> Uploading...');
    
    let successCount = 0;
    let errorCount = 0;
    let processedCount = 0;
    
    // Upload each file separately
    Array.from(files).forEach((file, index) => {
        const singleFormData = new FormData();
        singleFormData.append('media', file);
        singleFormData.append('content', formData.get('content') || '');
        
        $.ajax({
            url: '<?php echo APP_URL; ?>/stories/create.php',
            type: 'POST',
            data: singleFormData,
            processData: false,
            contentType: false,
            success: function(response) {
                processedCount++;
                if (response.success) {
                    successCount++;
                } else {
                    errorCount++;
                }
                
                // Check if all files processed
                if (processedCount === files.length) {
                    if (successCount > 0) {
                        location.reload();
                    } else {
                        alert('Failed to create stories: ' + (response.error || 'Unknown error'));
                        submitBtn.prop('disabled', false).html('<i class="bi bi-plus-circle"></i> Add Stories');
                    }
                }
            },
            error: function() {
                processedCount++;
                errorCount++;
                
                if (processedCount === files.length) {
                    if (successCount > 0) {
                        location.reload();
                    } else {
                        alert('Error creating stories');
                        submitBtn.prop('disabled', false).html('<i class="bi bi-plus-circle"></i> Add Stories');
                    }
                }
            }
        });
    });
});

// View story
function viewStory(userStories) {
    const stories = userStories.stories;
    let currentIndex = 0;
    
    function showStory(index) {
        const story = stories[index];
        
        // Mark as viewed
        $.post('<?php echo APP_URL; ?>/stories/view.php', {
            story_id: story.story_id
        });
        
        // Construct proper image URL
        let mediaUrl = story.media_url;
        if (!mediaUrl.startsWith('http')) {
            // If it's a relative path, add APP_URL
            mediaUrl = '<?php echo APP_URL; ?>/' + mediaUrl;
        }
        
        let mediaHtml = '';
        if (story.media_type === 'image') {
            mediaHtml = `<img src="${mediaUrl}" class="story-media" alt="Story">`;
        } else if (story.media_type === 'video') {
            mediaHtml = `<video src="${mediaUrl}" class="story-media" controls autoplay></video>`;
        } else {
            mediaHtml = `<div class="story-media bg-primary text-white p-5 d-flex align-items-center justify-content-center" style="min-height: 400px;">
                <h3>${story.content || ''}</h3>
            </div>`;
        }
        
        const timeAgo = formatTimeAgo(story.created_at);
        
        // Construct avatar URL
        let avatarUrl = userStories.profile_picture;
        if (avatarUrl && !avatarUrl.startsWith('http')) {
            avatarUrl = '<?php echo APP_URL; ?>/' + avatarUrl;
        } else if (!avatarUrl) {
            avatarUrl = '<?php echo APP_URL; ?>/assets/images/default-avatar.png';
        }
        
        // Check if this is user's own story
        const isOwnStory = userStories.is_own;
        const deleteBtn = isOwnStory ? `
            <button class="btn btn-sm btn-danger position-absolute" 
                    style="top: 20px; right: 70px; z-index: 10000;"
                    onclick="deleteStory(${story.story_id}); event.stopPropagation();">
                <i class="bi bi-trash"></i>
            </button>
        ` : '';
        
        $('#storyContent').html(`
            ${deleteBtn}
            <div class="story-user-info">
                <img src="${avatarUrl}" class="story-user-avatar" alt="User">
                <div>
                    <div class="story-user-name">${userStories.full_name}</div>
                    <div class="story-time">${timeAgo}</div>
                </div>
            </div>
            ${mediaHtml}
            ${story.content ? `<div class="position-absolute bottom-0 start-0 end-0 p-3 text-white" style="background: linear-gradient(transparent, rgba(0,0,0,0.7));">
                <p class="mb-0">${story.content}</p>
            </div>` : ''}
        `);
        
        // Auto advance after 5 seconds for images
        if (story.media_type === 'image') {
            setTimeout(() => {
                if (currentIndex < stories.length - 1) {
                    currentIndex++;
                    showStory(currentIndex);
                } else {
                    closeStoryModal();
                }
            }, 5000);
        }
    }
    
    $('#storyModal').addClass('active');
    showStory(0);
}

function closeStoryModal() {
    $('#storyModal').removeClass('active');
}

function deleteStory(storyId) {
    if (confirm('Delete this story?')) {
        $.ajax({
            url: '<?php echo APP_URL; ?>/stories/delete.php',
            type: 'POST',
            data: { story_id: storyId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    closeStoryModal();
                    location.reload();
                } else {
                    alert('Failed to delete story: ' + (response.error || 'Unknown error'));
                }
            },
            error: function() {
                alert('Error deleting story');
            }
        });
    }
}

function formatTimeAgo(datetime) {
    const now = new Date();
    const then = new Date(datetime);
    const seconds = Math.floor((now - then) / 1000);
    
    if (seconds < 60) return 'Just now';
    if (seconds < 3600) return Math.floor(seconds / 60) + 'm ago';
    if (seconds < 86400) return Math.floor(seconds / 3600) + 'h ago';
    return Math.floor(seconds / 86400) + 'd ago';
}

// Handle like button
function toggleLike(postId) {
    $.ajax({
        url: '<?php echo APP_URL; ?>/posts/toggle-like.php',
        type: 'POST',
        data: { post_id: postId },
        success: function(response) {
            if (response.success) {
                location.reload();
            }
        }
    });
}

// Handle comment submission
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
        },
        success: function(response) {
            if (response.success) {
                location.reload();
            } else {
                alert('Failed to add comment');
            }
        },
        error: function() {
            alert('Error adding comment');
        }
    });
}
</script>

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