<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/media.php';

requireLogin();
$db = Database::getInstance();
$user = getCurrentUser();
$userId = (int)($user['id'] ?? 0);
$role = $_SESSION['role'] ?? null;

if ($userId <= 0) {
    setFlashMessage('error', 'User account not found.');
    redirect(APP_URL . '/lms/login.php');
}

$communityId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($communityId <= 0) {
    setFlashMessage('error', 'Community not found.');
    redirect(APP_URL . '/lms/community_index.php');
}

$community = $db->get(
    'SELECT c.*, crs.title AS course_title, crs.id AS course_id, crs.instructor_id, crs.slug AS course_slug
     FROM communities c
     JOIN courses crs ON c.course_id = crs.id
     WHERE c.id = ?',
    [$communityId]
);

if (!$community) {
    setFlashMessage('error', 'Community not found.');
    redirect(APP_URL . '/lms/community_index.php');
}

$isAdmin = in_array($role, ['admin', 'super_admin', 'regional_admin'], true);
$isCourseInstructor = ((int)$community['instructor_id'] === $userId);

$member = $db->get(
    'SELECT * FROM community_members WHERE community_id = ? AND user_id = ? LIMIT 1',
    [$communityId, $userId]
);

// Ensure course instructor is an owner member
if ($isCourseInstructor) {
    if (!$member) {
        $db->insert('community_members', [
            'community_id' => $communityId,
            'user_id' => $userId,
            'role' => 'owner',
            'status' => 'active',
            'joined_at' => formatDate(),
        ]);
        $member = $db->get('SELECT * FROM community_members WHERE community_id = ? AND user_id = ? LIMIT 1', [$communityId, $userId]);
    } elseif ($member['status'] !== 'active') {
        $db->update('community_members', [
            'status' => 'active',
            'role' => 'owner',
        ], 'id = ?', [$member['id']]);
        $member['status'] = 'active';
        $member['role'] = 'owner';
    }
}

// Auto-join for active enrolled students when appropriate
if ($role === 'student' && (!$member || $member['status'] !== 'active')) {
    $enrollment = $db->get(
        'SELECT course_id, cohort_id, status FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status = "active" LIMIT 1',
        [$community['course_id'], $userId]
    );

    if ($enrollment) {
        $visibility = $community['visibility'] ?? 'course';
        $shouldJoin = false;

        if ($visibility === 'course' || $visibility === 'public') {
            $shouldJoin = true;
        } elseif ($visibility === 'cohort') {
            $communityCohortId = $community['cohort_id'] !== null ? (int)$community['cohort_id'] : 0;
            if ($communityCohortId && (int)$enrollment['cohort_id'] === $communityCohortId) {
                $shouldJoin = true;
            }
        }

        if ($shouldJoin) {
            if (!$member) {
                $db->insert('community_members', [
                    'community_id' => $communityId,
                    'user_id' => $userId,
                    'role' => 'member',
                    'status' => 'active',
                    'joined_at' => formatDate(),
                ]);
                $member = $db->get('SELECT * FROM community_members WHERE community_id = ? AND user_id = ? LIMIT 1', [$communityId, $userId]);
            } elseif ($member['status'] === 'left') {
                $db->update('community_members', [
                    'status' => 'active',
                ], 'id = ?', [$member['id']]);
                $member['status'] = 'active';
            }
        }
    }
}

$isBanned = $member && ($member['status'] === 'banned');
$hasActiveMembership = $member && ($member['status'] === 'active');

if ($isBanned && !$isAdmin) {
    setFlashMessage('error', 'You have been banned from this community.');
    redirect(APP_URL . '/lms/community_index.php');
}

$canView = $isAdmin || $isCourseInstructor || $hasActiveMembership;

if (!$canView) {
    setFlashMessage('error', 'You do not have access to this community.');
    redirect(APP_URL . '/lms/community_index.php');
}

$canPost = $canView && !$isBanned && ($community['status'] === 'active');

$canFlag = $hasActiveMembership && !$isBanned;

$memberRole = ($member && isset($member['role'])) ? $member['role'] : 'member';
$canModerate = $isAdmin || in_array($memberRole, ['owner', 'moderator'], true);
$canManageRoles = $isAdmin || $memberRole === 'owner';

// Handle post, comment creation, and moderation actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Member flagging: posts
    if ($action === 'flag_post') {
        if (!$canFlag) {
            setFlashMessage('error', 'You are not allowed to flag content in this community.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $postId = (int)($_POST['post_id'] ?? 0);
        if ($postId <= 0) {
            setFlashMessage('error', 'Invalid post selected.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $post = $db->get(
            'SELECT * FROM community_posts WHERE id = ? AND community_id = ? AND status != "deleted" LIMIT 1',
            [$postId, $communityId]
        );
        if (!$post) {
            setFlashMessage('error', 'Post not found.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $db->insert('activity_logs', [
            'user_id' => $userId,
            'action' => 'community_post_flagged',
            'description' => sprintf('Post #%d in community #%d flagged by user #%d', $postId, $communityId, $userId),
            'resource_type' => 'community_post',
            'resource_id' => $postId,
            'ip_address' => getClientIP(),
            'user_agent' => getUserAgent(),
            'region' => $_SESSION['region'] ?? DEFAULT_REGION,
        ]);

        setFlashMessage('success', 'Thank you. This post has been flagged for review.');
        redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
    }

    // Member flagging: comments
    if ($action === 'flag_comment') {
        if (!$canFlag) {
            setFlashMessage('error', 'You are not allowed to flag content in this community.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $commentId = (int)($_POST['comment_id'] ?? 0);
        if ($commentId <= 0) {
            setFlashMessage('error', 'Invalid comment selected.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $comment = $db->get(
            'SELECT c.id, c.post_id, c.status, p.community_id
             FROM community_comments c
             JOIN community_posts p ON c.post_id = p.id
             WHERE c.id = ? AND p.community_id = ?
             LIMIT 1',
            [$commentId, $communityId]
        );

        if (!$comment || $comment['status'] === 'deleted') {
            setFlashMessage('error', 'Comment not found.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $db->insert('activity_logs', [
            'user_id' => $userId,
            'action' => 'community_comment_flagged',
            'description' => sprintf('Comment #%d on post #%d in community #%d flagged by user #%d', $commentId, $comment['post_id'], $communityId, $userId),
            'resource_type' => 'community_comment',
            'resource_id' => $commentId,
            'ip_address' => getClientIP(),
            'user_agent' => getUserAgent(),
            'region' => $_SESSION['region'] ?? DEFAULT_REGION,
        ]);

        setFlashMessage('success', 'Thank you. This comment has been flagged for review.');
        redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
    }

    // Moderation: hide/delete posts
    if (in_array($action, ['hide_post', 'delete_post'], true)) {
        if (!$canModerate) {
            setFlashMessage('error', 'You do not have permission to moderate posts.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $postId = (int)($_POST['post_id'] ?? 0);
        if ($postId <= 0) {
            setFlashMessage('error', 'Invalid post selected.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $post = $db->get(
            'SELECT id, status FROM community_posts WHERE id = ? AND community_id = ? LIMIT 1',
            [$postId, $communityId]
        );
        if (!$post) {
            setFlashMessage('error', 'Post not found.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $newStatus = ($action === 'hide_post') ? 'hidden' : 'deleted';
        if ($post['status'] !== $newStatus) {
            $db->update('community_posts', [
                'status' => $newStatus,
            ], 'id = ?', [$postId]);

            // Log moderation activity
            $logAction = $action === 'hide_post' ? 'community_post_hidden' : 'community_post_deleted';
            $db->insert('activity_logs', [
                'user_id' => $userId,
                'action' => $logAction,
                'description' => sprintf('Post #%d in community #%d set to %s by user #%d', $postId, $communityId, $newStatus, $userId),
                'resource_type' => 'community_post',
                'resource_id' => $postId,
                'ip_address' => getClientIP(),
                'user_agent' => getUserAgent(),
                'region' => $_SESSION['region'] ?? DEFAULT_REGION,
            ]);
        }

        setFlashMessage('success', $action === 'hide_post' ? 'Post hidden.' : 'Post deleted.');
        redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
    }

    // Moderation: lock/unlock posts (threads)
    if (in_array($action, ['lock_post', 'unlock_post'], true)) {
        if (!$canModerate) {
            setFlashMessage('error', 'You do not have permission to moderate posts.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $postId = (int)($_POST['post_id'] ?? 0);
        if ($postId <= 0) {
            setFlashMessage('error', 'Invalid post selected.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $post = $db->get(
            'SELECT * FROM community_posts WHERE id = ? AND community_id = ? LIMIT 1',
            [$postId, $communityId]
        );

        if (!$post) {
            setFlashMessage('error', 'Post not found.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $shouldLock = ($action === 'lock_post');
        $currentLocked = !empty($post['is_locked']) ? 1 : 0;
        $newLocked = $shouldLock ? 1 : 0;

        if ($currentLocked !== $newLocked) {
            $db->update('community_posts', [
                'is_locked' => $newLocked,
            ], 'id = ?', [$postId]);

            $logAction = $shouldLock ? 'community_post_locked' : 'community_post_unlocked';
            $db->insert('activity_logs', [
                'user_id' => $userId,
                'action' => $logAction,
                'description' => sprintf('Post #%d in community #%d %s by user #%d', $postId, $communityId, $shouldLock ? 'locked' : 'unlocked', $userId),
                'resource_type' => 'community_post',
                'resource_id' => $postId,
                'ip_address' => getClientIP(),
                'user_agent' => getUserAgent(),
                'region' => $_SESSION['region'] ?? DEFAULT_REGION,
            ]);
        }

        setFlashMessage('success', $shouldLock ? 'Thread locked. New comments are disabled.' : 'Thread unlocked.');
        redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
    }

    // Moderation: hide/delete comments
    if (in_array($action, ['hide_comment', 'delete_comment'], true)) {
        if (!$canModerate) {
            setFlashMessage('error', 'You do not have permission to moderate comments.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $commentId = (int)($_POST['comment_id'] ?? 0);
        if ($commentId <= 0) {
            setFlashMessage('error', 'Invalid comment selected.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $comment = $db->get(
            'SELECT c.id, c.status, c.post_id, p.community_id
             FROM community_comments c
             JOIN community_posts p ON c.post_id = p.id
             WHERE c.id = ? AND p.community_id = ?
             LIMIT 1',
            [$commentId, $communityId]
        );

        if (!$comment) {
            setFlashMessage('error', 'Comment not found.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $newStatus = ($action === 'hide_comment') ? 'hidden' : 'deleted';
        if ($comment['status'] !== $newStatus) {
            $db->update('community_comments', [
                'status' => $newStatus,
            ], 'id = ?', [$commentId]);

            if ($comment['status'] === 'visible') {
                $db->query(
                    'UPDATE community_posts SET comment_count = GREATEST(comment_count - 1, 0) WHERE id = ?',
                    [$comment['post_id']]
                );
            }

            // Log moderation activity
            $logAction = $action === 'hide_comment' ? 'community_comment_hidden' : 'community_comment_deleted';
            $db->insert('activity_logs', [
                'user_id' => $userId,
                'action' => $logAction,
                'description' => sprintf('Comment #%d on post #%d in community #%d set to %s by user #%d', $commentId, $comment['post_id'], $communityId, $newStatus, $userId),
                'resource_type' => 'community_comment',
                'resource_id' => $commentId,
                'ip_address' => getClientIP(),
                'user_agent' => getUserAgent(),
                'region' => $_SESSION['region'] ?? DEFAULT_REGION,
            ]);
        }

        setFlashMessage('success', $action === 'hide_comment' ? 'Comment hidden.' : 'Comment deleted.');
        redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
    }

    // Manage member roles: promote/demote moderators
    if (in_array($action, ['promote_member', 'demote_member'], true)) {
        if (!$canManageRoles) {
            setFlashMessage('error', 'You do not have permission to change member roles.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $targetUserId = (int)($_POST['target_user_id'] ?? 0);
        if ($targetUserId <= 0 || $targetUserId === $userId) {
            setFlashMessage('error', 'Invalid member selected.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $membership = $db->get(
            'SELECT id, role FROM community_members WHERE community_id = ? AND user_id = ? LIMIT 1',
            [$communityId, $targetUserId]
        );

        if (!$membership) {
            setFlashMessage('error', 'Member not found in this community.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        if ($action === 'promote_member') {
            if ($membership['role'] === 'member') {
                $db->update('community_members', [
                    'role' => 'moderator',
                ], 'id = ?', [$membership['id']]);

                $db->insert('activity_logs', [
                    'user_id' => $userId,
                    'action' => 'community_member_promoted',
                    'description' => sprintf('User #%d promoted to moderator in community #%d by user #%d', $targetUserId, $communityId, $userId),
                    'resource_type' => 'community_member',
                    'resource_id' => $membership['id'],
                    'ip_address' => getClientIP(),
                    'user_agent' => getUserAgent(),
                    'region' => $_SESSION['region'] ?? DEFAULT_REGION,
                ]);

                setFlashMessage('success', 'Member promoted to moderator.');
            } else {
                setFlashMessage('error', 'User is already a moderator or owner.');
            }
        } else { // demote_member
            if ($membership['role'] === 'moderator') {
                $db->update('community_members', [
                    'role' => 'member',
                ], 'id = ?', [$membership['id']]);

                $db->insert('activity_logs', [
                    'user_id' => $userId,
                    'action' => 'community_member_demoted',
                    'description' => sprintf('User #%d demoted from moderator in community #%d by user #%d', $targetUserId, $communityId, $userId),
                    'resource_type' => 'community_member',
                    'resource_id' => $membership['id'],
                    'ip_address' => getClientIP(),
                    'user_agent' => getUserAgent(),
                    'region' => $_SESSION['region'] ?? DEFAULT_REGION,
                ]);

                setFlashMessage('success', 'Moderator role removed from member.');
            } else {
                setFlashMessage('error', 'Only moderators can be demoted.');
            }
        }

        redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
    }

    if ($action === 'create_post' && $canPost) {
        $title = trim($_POST['title'] ?? '');
        $body = trim($_POST['body'] ?? '');
        $type = $_POST['type'] ?? 'discussion';
        $allowedTypes = ['discussion', 'project', 'assignment', 'announcement'];
        if (!in_array($type, $allowedTypes, true)) {
            $type = 'discussion';
        }

        if ($title === '' || $body === '') {
            setFlashMessage('error', 'Title and body are required to create a post.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        // Handle attachments (Phase 2)
        $attachments = [];
        $uploadErrors = [];

        if (!empty($_FILES['attachments']) && is_array($_FILES['attachments']['name'])) {
            $files = $_FILES['attachments'];
            $count = count($files['name']);

            $uploadDir = __DIR__ . '/../uploads/communities/' . (int)$communityId;
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            $finfo = function_exists('finfo_open') ? finfo_open(FILEINFO_MIME_TYPE) : null;

            for ($i = 0; $i < $count; $i++) {
                $name = $files['name'][$i] ?? '';
                $tmpName = $files['tmp_name'][$i] ?? '';
                $error = $files['error'][$i] ?? UPLOAD_ERR_NO_FILE;
                $size = (int)($files['size'][$i] ?? 0);

                if ($error === UPLOAD_ERR_NO_FILE || $name === '' || $tmpName === '') {
                    continue;
                }
                if ($error !== UPLOAD_ERR_OK) {
                    $uploadErrors[] = 'One or more attachments failed to upload.';
                    continue;
                }

                $mime = 'application/octet-stream';
                if ($finfo) {
                    $detected = finfo_file($finfo, $tmpName);
                    if ($detected) {
                        $mime = $detected;
                    }
                }

                // Map MIME to allowed media type
                $mediaType = null;
                foreach (MEDIA_ALLOWED as $typeKey => $mimeList) {
                    if (in_array($mime, $mimeList, true)) {
                        $mediaType = $typeKey;
                        break;
                    }
                }

                // Restrict to images, slides, assignments, and video for attachments
                if (!in_array($mediaType, ['image', 'slides', 'assignment', 'video'], true)) {
                    $uploadErrors[] = 'Attachment type not allowed: ' . $name;
                    continue;
                }

                $maxSize = MEDIA_MAX_SIZE[$mediaType] ?? (20 * 1024 * 1024);
                if ($size <= 0 || $size > $maxSize) {
                    $uploadErrors[] = 'Attachment too large or invalid: ' . $name;
                    continue;
                }

                $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                $baseName = pathinfo($name, PATHINFO_FILENAME);
                $safeBase = preg_replace('/[^A-Za-z0-9_-]/', '_', $baseName);
                if ($safeBase === '') {
                    $safeBase = 'file';
                }
                $fileName = time() . '_' . $i . '_' . $safeBase . ($ext ? '.' . $ext : '');
                $destPath = rtrim($uploadDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $fileName;

                if (!move_uploaded_file($tmpName, $destPath)) {
                    $uploadErrors[] = 'Failed to save attachment: ' . $name;
                    continue;
                }

                $webPath = 'uploads/communities/' . (int)$communityId . '/' . $fileName;
                $attachments[] = [
                    'path' => $webPath,
                    'mime' => $mime,
                    'size' => $size,
                ];
            }

            if ($finfo) {
                finfo_close($finfo);
            }
        }

        $attachmentsJson = $attachments ? json_encode($attachments) : null;

        $now = formatDate();
        $relatedLessonId = (int)($_POST['lesson_id'] ?? 0);

        $db->insert('community_posts', [
            'community_id' => $communityId,
            'user_id' => $userId,
            'type' => $type,
            'title' => $title,
            'body' => $body,
            'attachments' => $attachmentsJson,
            'related_course_id' => (int)$community['course_id'],
            'related_lesson_id' => $relatedLessonId > 0 ? $relatedLessonId : null,
            'status' => 'visible',
            'is_pinned' => 0,
            'comment_count' => 0,
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        if (!empty($uploadErrors)) {
            setFlashMessage('error', implode(' ', array_unique($uploadErrors)));
        } else {
            setFlashMessage('success', 'Post created successfully.');
        }

        redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
    }

    if ($action === 'add_comment' && $canPost) {
        $postId = (int)($_POST['post_id'] ?? 0);
        $commentBody = trim($_POST['comment_body'] ?? '');

        if ($postId <= 0 || $commentBody === '') {
            setFlashMessage('error', 'Comment cannot be empty.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $post = $db->get(
            'SELECT * FROM community_posts WHERE id = ? AND community_id = ? LIMIT 1',
            [$postId, $communityId]
        );
        if (!$post || ($post['status'] ?? 'visible') !== 'visible') {
            setFlashMessage('error', 'Post not found.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        if (!empty($post['is_locked'])) {
            setFlashMessage('error', 'This thread is locked. New comments are disabled.');
            redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
        }

        $now = formatDate();
        $db->insert('community_comments', [
            'post_id' => $postId,
            'user_id' => $userId,
            'body' => $commentBody,
            'parent_id' => null,
            'status' => 'visible',
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        $db->query('UPDATE community_posts SET comment_count = comment_count + 1 WHERE id = ?', [$postId]);

        setFlashMessage('success', 'Comment added.');
        redirect(APP_URL . '/lms/community_view.php?id=' . $communityId);
    }
}

// Filters and pagination for posts
$allowedTypes = ['all', 'discussion', 'project', 'assignment', 'announcement'];
$filterType = isset($_GET['type']) ? strtolower(trim($_GET['type'])) : 'all';
if (!in_array($filterType, $allowedTypes, true)) {
    $filterType = 'all';
}

$perPage = 10;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $perPage;

$whereParts = ['p.community_id = ?', 'p.status = "visible"'];
$params = [$communityId];

if ($filterType !== 'all') {
    $whereParts[] = 'p.type = ?';
    $params[] = $filterType;
}

$whereSql = implode(' AND ', $whereParts);

// Total count for pagination
$countRow = $db->get(
    "SELECT COUNT(*) AS cnt
     FROM community_posts p
     WHERE $whereSql",
    $params
);
$totalPosts = (int)($countRow['cnt'] ?? 0);

$postParams = $params;
$postParams[] = $perPage;
$postParams[] = $offset;

// Load posts and comments for display
$posts = $db->getAll(
    "SELECT p.*, u.first_name, u.last_name
     FROM community_posts p
     JOIN users u ON p.user_id = u.id
     WHERE $whereSql
     ORDER BY p.is_pinned DESC, p.created_at DESC
     LIMIT ? OFFSET ?",
    $postParams
);

$postIds = array_map(static function ($p) { return (int)$p['id']; }, $posts);
$commentsByPost = [];
$memberRolesByUser = [];
$memberStatusByUser = [];

if (!empty($postIds)) {
    $placeholders = implode(',', array_fill(0, count($postIds), '?'));
    $comments = $db->getAll(
        "SELECT c.*, u.first_name, u.last_name
         FROM community_comments c
         JOIN users u ON c.user_id = u.id
         WHERE c.post_id IN ($placeholders) AND c.status = 'visible'
         ORDER BY c.created_at ASC",
        $postIds
    );

    foreach ($comments as $cmt) {
        $pid = (int)$cmt['post_id'];
        if (!isset($commentsByPost[$pid])) {
            $commentsByPost[$pid] = [];
        }
        $commentsByPost[$pid][] = $cmt;
    }

    // Preload roles for all users involved in posts/comments
    $userIdsForRoles = [];
    foreach ($posts as $p) {
        $userIdsForRoles[(int)$p['user_id']] = true;
    }
    foreach ($comments as $cmt) {
        $userIdsForRoles[(int)$cmt['user_id']] = true;
    }

    if (!empty($userIdsForRoles)) {
        $userIdList = array_keys($userIdsForRoles);
        $userPlaceholders = implode(',', array_fill(0, count($userIdList), '?'));
        $roleRows = $db->getAll(
            "SELECT user_id, role, status FROM community_members WHERE community_id = ? AND user_id IN ($userPlaceholders)",
            array_merge([$communityId], $userIdList)
        );
        foreach ($roleRows as $row) {
            $uid = (int)$row['user_id'];
            $memberRolesByUser[$uid] = $row['role'];
            $memberStatusByUser[$uid] = $row['status'];
        }
    }
}

$pageTitle = 'Community - ' . htmlspecialchars($community['title']);
include __DIR__ . '/includes/header.php';
?>

<div class="row">
    <div class="col-md-8">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
                <h4 class="mb-1"><?php echo htmlspecialchars($community['title']); ?></h4>
                <p class="text-muted mb-0">
                    Course:
                    <a href="<?php echo APP_URL; ?>/lms/courses.php?course_id=<?php echo (int)$community['course_id']; ?>">
                        <?php echo htmlspecialchars($community['course_title']); ?>
                    </a>
                </p>
            </div>
        </div>

        <?php if (!empty($community['description'])): ?>
            <div class="card mb-3">
                <div class="card-body">
                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($community['description'])); ?></p>
                </div>
            </div>
        <?php endif; ?>

        <?php
            $typeOptions = [
                'all' => 'All posts',
                'discussion' => 'Discussions',
                'project' => 'Projects',
                'assignment' => 'Assignments',
                'announcement' => 'Announcements',
            ];
        ?>

        <div class="d-flex justify-content-between align-items-center mb-3">
            <form method="get" class="d-flex align-items-center gap-2">
                <input type="hidden" name="id" value="<?php echo (int)$communityId; ?>" />
                <label class="form-label mb-0 me-2 small text-muted">Filter</label>
                <select name="type" class="form-select form-select-sm" onchange="this.form.submit()">
                    <?php foreach ($typeOptions as $key => $label): ?>
                        <option value="<?php echo $key; ?>" <?php echo $filterType === $key ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($label); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </form>

            <?php if ($totalPosts > 0): ?>
                <div class="small text-muted">
                    <?php
                        $from = $totalPosts ? $offset + 1 : 0;
                        $to = min($totalPosts, $offset + count($posts));
                    ?>
                    Showing <?php echo $from; ?>–<?php echo $to; ?> of <?php echo $totalPosts; ?> post(s)
                </div>
            <?php endif; ?>
        </div>

        <?php if ($canPost): ?>
            <div class="card mb-4">
                <div class="card-body">
                    <h5 class="card-title mb-3">New Post</h5>
                    <form method="post" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="create_post" />
                        <div class="mb-3">
                            <label class="form-label">Title</label>
                            <input type="text" name="title" class="form-control" required />
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Type</label>
                            <select name="type" class="form-select">
                                <option value="discussion">Discussion</option>
                                <option value="project">Project</option>
                                <option value="assignment">Assignment</option>
                                <option value="announcement">Announcement</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Body</label>
                            <textarea name="body" class="form-control" rows="4" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Attachments (optional)</label>
                            <input type="file" name="attachments[]" class="form-control" multiple />
                            <small class="text-muted d-block mt-1">Images, PDFs, slides, and short videos are allowed. Large files may be rejected.</small>
                        </div>
                        <div class="text-end">
                            <button type="submit" class="btn btn-primary">Post</button>
                        </div>
                    </form>
                </div>
            </div>
        <?php endif; ?>

        <?php if (empty($posts)): ?>
            <div class="card">
                <div class="card-body">
                    <p class="text-muted mb-0">No posts yet. Be the first to start a discussion.</p>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($posts as $post): ?>
                <div class="card mb-3">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <div>
                                <h6 class="mb-1">
                                    <?php echo htmlspecialchars($post['title']); ?>
                                    <?php if (!empty($post['is_locked'])): ?>
                                        <span class="badge bg-label-warning ms-1">Locked</span>
                                    <?php endif; ?>
                                </h6>
                                <div class="text-muted small">
                                    <?php
                                        $authorName = trim(($post['first_name'] ?? '') . ' ' . ($post['last_name'] ?? ''));
                                        echo htmlspecialchars($authorName !== '' ? $authorName : 'User #' . (int)$post['user_id']);
                                    ?>
                                    &middot;
                                    <?php echo htmlspecialchars(ucfirst($post['type'])); ?>
                                    &middot;
                                    <?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($post['created_at']))); ?>
                                </div>
                                <?php
                                    $authorId = (int)$post['user_id'];
                                    $authorRole = $memberRolesByUser[$authorId] ?? 'member';
                                    $authorStatus = $memberStatusByUser[$authorId] ?? 'active';
                                ?>
                                <?php if ($authorRole !== 'member' || $authorStatus === 'banned' || ($canManageRoles && $authorId !== $userId)): ?>
                                    <div class="text-muted small mt-1">
                                        <?php if ($authorRole === 'owner'): ?>
                                            <span class="badge bg-label-primary me-1">Owner</span>
                                        <?php elseif ($authorRole === 'moderator'): ?>
                                            <span class="badge bg-label-secondary me-1">Moderator</span>
                                        <?php endif; ?>

                                        <?php if ($authorStatus === 'banned'): ?>
                                            <span class="badge bg-label-danger me-1">Banned</span>
                                        <?php endif; ?>

                                        <?php if ($canManageRoles && $authorId !== $userId): ?>
                                            <?php if ($authorRole === 'member'): ?>
                                                <form method="post" class="d-inline">
                                                    <input type="hidden" name="action" value="promote_member" />
                                                    <input type="hidden" name="target_user_id" value="<?php echo $authorId; ?>" />
                                                    <button type="submit" class="btn btn-xs btn-outline-primary">Make moderator</button>
                                                </form>
                                            <?php elseif ($authorRole === 'moderator'): ?>
                                                <form method="post" class="d-inline ms-1" onsubmit="return confirm('Remove moderator role from this member?');">
                                                    <input type="hidden" name="action" value="demote_member" />
                                                    <input type="hidden" name="target_user_id" value="<?php echo $authorId; ?>" />
                                                    <button type="submit" class="btn btn-xs btn-outline-secondary">Remove moderator</button>
                                                </form>
                                            <?php endif; ?>

                                            <?php if ($authorStatus !== 'banned'): ?>
                                                <form method="post" class="d-inline ms-1" onsubmit="return confirm('Ban this member from the community?');">
                                                    <input type="hidden" name="action" value="ban_member" />
                                                    <input type="hidden" name="target_user_id" value="<?php echo $authorId; ?>" />
                                                    <button type="submit" class="btn btn-xs btn-outline-danger">Ban</button>
                                                </form>
                                            <?php else: ?>
                                                <form method="post" class="d-inline ms-1" onsubmit="return confirm('Unban this member and allow participation again?');">
                                                    <input type="hidden" name="action" value="unban_member" />
                                                    <input type="hidden" name="target_user_id" value="<?php echo $authorId; ?>" />
                                                    <button type="submit" class="btn btn-xs btn-outline-success">Unban</button>
                                                </form>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="ms-2 text-end">
                                <?php if ($canModerate): ?>
                                    <div class="mb-1">
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="action" value="hide_post" />
                                            <input type="hidden" name="post_id" value="<?php echo (int)$post['id']; ?>" />
                                            <button type="submit" class="btn btn-sm btn-outline-secondary">Hide</button>
                                        </form>
                                        <form method="post" class="d-inline ms-1" onsubmit="return confirm('Delete this post and hide it from the community?');">
                                            <input type="hidden" name="action" value="delete_post" />
                                            <input type="hidden" name="post_id" value="<?php echo (int)$post['id']; ?>" />
                                            <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
                                        </form>
                                    </div>
                                    <div class="mb-1">
                                        <?php if (empty($post['is_locked'])): ?>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Lock this thread and prevent new comments?');">
                                                <input type="hidden" name="action" value="lock_post" />
                                                <input type="hidden" name="post_id" value="<?php echo (int)$post['id']; ?>" />
                                                <button type="submit" class="btn btn-sm btn-outline-warning">Lock</button>
                                            </form>
                                        <?php else: ?>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Unlock this thread and allow new comments?');">
                                                <input type="hidden" name="action" value="unlock_post" />
                                                <input type="hidden" name="post_id" value="<?php echo (int)$post['id']; ?>" />
                                                <button type="submit" class="btn btn-sm btn-outline-success">Unlock</button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>

                                <?php if ($canFlag && !$canModerate): ?>
                                    <form method="post" class="d-inline" onsubmit="return confirm('Flag this post for moderator review?');">
                                        <input type="hidden" name="action" value="flag_post" />
                                        <input type="hidden" name="post_id" value="<?php echo (int)$post['id']; ?>" />
                                        <button type="submit" class="btn btn-sm btn-outline-secondary">Flag</button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </div>
                        <p class="mb-2"><?php echo nl2br(htmlspecialchars($post['body'])); ?></p>

                        <?php
                            $attachments = [];
                            if (!empty($post['attachments'])) {
                                $decoded = json_decode($post['attachments'], true);
                                if (is_array($decoded)) {
                                    $attachments = $decoded;
                                }
                            }
                        ?>

                        <?php if (!empty($attachments)): ?>
                            <div class="mb-2">
                                <strong class="d-block mb-1 small text-muted">Attachments</strong>
                                <div class="d-flex flex-wrap gap-2">
                                    <?php foreach ($attachments as $att): ?>
                                        <?php
                                            $attPath = $att['path'] ?? '';
                                            $attMime = $att['mime'] ?? '';
                                            if (!$attPath) {
                                                continue;
                                            }
                                            $viewUrl = APP_URL . '/lms/file_view.php?path=' . urlencode($attPath);
                                        ?>
                                        <div class="border rounded p-2 small" style="max-width: 220px;">
                                            <a href="<?php echo htmlspecialchars($viewUrl); ?>" target="_blank">
                                                <?php echo htmlspecialchars(basename($attPath)); ?>
                                            </a>
                                            <?php if (strpos($attMime, 'image/') === 0): ?>
                                                <div class="mt-1">
                                                    <img src="<?php echo htmlspecialchars($viewUrl); ?>" alt="Attachment" style="max-width: 200px; height: auto;" />
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php
                            $pid = (int)$post['id'];
                            $postComments = $commentsByPost[$pid] ?? [];
                        ?>

                        <hr class="my-3" />
                        <div class="mb-2 small text-muted"><?php echo count($postComments); ?> comment(s)</div>

                        <?php if (!empty($postComments)): ?>
                            <div class="mb-2">
                                <?php foreach ($postComments as $cmt): ?>
                                    <div class="mb-2">
                                        <div class="small fw-semibold">
                                            <?php
                                                $cName = trim(($cmt['first_name'] ?? '') . ' ' . ($cmt['last_name'] ?? ''));
                                                echo htmlspecialchars($cName !== '' ? $cName : 'User #' . (int)$cmt['user_id']);
                                            ?>
                                            <span class="text-muted">&middot; <?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($cmt['created_at']))); ?></span>
                                        </div>
                                        <div class="small"><?php echo nl2br(htmlspecialchars($cmt['body'])); ?></div>
                                        <div class="small mt-1">
                                            <?php
                                                $commentUserId = (int)$cmt['user_id'];
                                                $commentUserStatus = $memberStatusByUser[$commentUserId] ?? 'active';
                                            ?>

                                            <?php if ($canModerate): ?>
                                                <form method="post" class="d-inline">
                                                    <input type="hidden" name="action" value="hide_comment" />
                                                    <input type="hidden" name="comment_id" value="<?php echo (int)$cmt['id']; ?>" />
                                                    <button type="submit" class="btn btn-sm btn-outline-secondary btn-xs">Hide</button>
                                                </form>
                                                <form method="post" class="d-inline ms-1" onsubmit="return confirm('Delete this comment?');">
                                                    <input type="hidden" name="action" value="delete_comment" />
                                                    <input type="hidden" name="comment_id" value="<?php echo (int)$cmt['id']; ?>" />
                                                    <button type="submit" class="btn btn-sm btn-outline-danger btn-xs">Delete</button>
                                                </form>
                                            <?php endif; ?>

                                            <?php if ($canManageRoles && $commentUserId !== $userId): ?>
                                                <?php if ($commentUserStatus !== 'banned'): ?>
                                                    <form method="post" class="d-inline ms-1" onsubmit="return confirm('Ban this member from the community?');">
                                                        <input type="hidden" name="action" value="ban_member" />
                                                        <input type="hidden" name="target_user_id" value="<?php echo $commentUserId; ?>" />
                                                        <button type="submit" class="btn btn-sm btn-outline-danger btn-xs">Ban</button>
                                                    </form>
                                                <?php else: ?>
                                                    <form method="post" class="d-inline ms-1" onsubmit="return confirm('Unban this member and allow participation again?');">
                                                        <input type="hidden" name="action" value="unban_member" />
                                                        <input type="hidden" name="target_user_id" value="<?php echo $commentUserId; ?>" />
                                                        <button type="submit" class="btn btn-sm btn-outline-success btn-xs">Unban</button>
                                                    </form>
                                                <?php endif; ?>
                                            <?php endif; ?>

                                            <?php if ($canFlag && !$canModerate): ?>
                                                <form method="post" class="d-inline ms-1" onsubmit="return confirm('Flag this comment for moderator review?');">
                                                    <input type="hidden" name="action" value="flag_comment" />
                                                    <input type="hidden" name="comment_id" value="<?php echo (int)$cmt['id']; ?>" />
                                                    <button type="submit" class="btn btn-sm btn-outline-secondary btn-xs">Flag</button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($canPost): ?>
                            <?php if (empty($post['is_locked'])): ?>
                                <form method="post" class="mt-2">
                                    <input type="hidden" name="action" value="add_comment" />
                                    <input type="hidden" name="post_id" value="<?php echo (int)$post['id']; ?>" />
                                    <div class="input-group input-group-sm">
                                        <textarea name="comment_body" class="form-control" rows="1" placeholder="Add a comment..."></textarea>
                                        <button type="submit" class="btn btn-outline-primary">Post</button>
                                    </div>
                                </form>
                            <?php else: ?>
                                <div class="small text-muted mt-2">This thread is locked. New comments are disabled.</div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

        <?php $totalPages = (int)ceil($totalPosts / $perPage); ?>
        <?php if ($totalPages > 1): ?>
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center mt-3">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php
                            $query = $_GET;
                            $query['id'] = $communityId;
                            $query['page'] = max(1, $page - 1);
                            echo htmlspecialchars(http_build_query($query));
                        ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                        <li class="page-item <?php echo $p === $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?<?php
                                $query = $_GET;
                                $query['id'] = $communityId;
                                $query['page'] = $p;
                                echo htmlspecialchars(http_build_query($query));
                            ?>"><?php echo $p; ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php
                            $query = $_GET;
                            $query['id'] = $communityId;
                            $query['page'] = min($totalPages, $page + 1);
                            echo htmlspecialchars(http_build_query($query));
                        ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php';
