<?php
require_once __DIR__ . '/../config/database.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');
}

// Handle create community (instructors and admins only)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create_community') {
        if (!in_array($role, ['instructor', 'admin', 'super_admin', 'regional_admin'], true)) {
            setFlashMessage('error', 'Only instructors and admins can create communities.');
            redirect(APP_URL . '/lms/community_index.php');
        }

        $courseId = (int)($_POST['course_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');

        if ($courseId <= 0) {
            setFlashMessage('error', 'Please select a course.');
            redirect(APP_URL . '/lms/community_index.php');
        }

        // Ensure course exists and belongs to instructor (unless admin)
        $course = $db->get('SELECT id, title, instructor_id FROM courses WHERE id = ?', [$courseId]);
        if (!$course) {
            setFlashMessage('error', 'Selected course not found.');
            redirect(APP_URL . '/lms/community_index.php');
        }

        if ($role === 'instructor' && (int)$course['instructor_id'] !== $userId) {
            setFlashMessage('error', 'You can only create communities for your own courses.');
            redirect(APP_URL . '/lms/community_index.php');
        }

        if ($title === '') {
            $title = ($course['title'] ?? 'Course') . ' Community';
        }

        // Generate unique slug
        $slug = strtolower($title);
        $slug = preg_replace('/[^a-z0-9\s-]/', '', $slug);
        $slug = preg_replace('/[\s-]+/', '-', $slug);
        $slug = trim($slug, '-');
        if ($slug === '') {
            $slug = 'community-' . $courseId;
        }
        $baseSlug = $slug;
        $i = 1;
        while (true) {
            $existing = $db->get('SELECT id FROM communities WHERE slug = ? LIMIT 1', [$slug]);
            if (!$existing) {
                break;
            }
            $slug = $baseSlug . '-' . $i;
            $i++;
        }

        // Create community as default course-level community
        $now = formatDate();
        $communityId = $db->insert('communities', [
            'course_id' => $courseId,
            'cohort_id' => null,
            'title' => $title,
            'slug' => $slug,
            'description' => $description !== '' ? $description : null,
            'visibility' => 'course',
            'status' => 'active',
            'is_default' => 1,
            'created_by' => $userId,
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        // Ensure creator is owner member
        $db->insert('community_members', [
            'community_id' => $communityId,
            'user_id' => $userId,
            'role' => 'owner',
            'status' => 'active',
            'joined_at' => $now,
        ]);

        setFlashMessage('success', 'Community created successfully.');
        redirect(APP_URL . '/lms/community_view.php?id=' . (int)$communityId);
    }
}

// Prepare data for view
$communities = [];
$courses = [];

if ($role === 'instructor') {
    // Instructor: show communities they created
    $communities = $db->getAll(
        'SELECT c.*, crs.title AS course_title,
                (SELECT COUNT(*) FROM community_members cm WHERE cm.community_id = c.id AND cm.status = "active") AS member_count
         FROM communities c
         JOIN courses crs ON c.course_id = crs.id
         WHERE c.created_by = ?
         ORDER BY c.created_at DESC',
        [$userId]
    );

    // Courses they can attach communities to
    $courses = $db->getAll(
        'SELECT id, title FROM courses WHERE instructor_id = ? ORDER BY title',
        [$userId]
    );
} elseif ($role === 'student') {
    // Student: auto-join communities for their active course/cohort enrollments
    $enrollments = $db->getAll(
        'SELECT course_id, cohort_id FROM course_enrollments WHERE student_id = ? AND status = "active"',
        [$userId]
    );

    $courseIds = [];
    $cohortsByCourse = [];
    foreach ($enrollments as $en) {
        $cid = (int)$en['course_id'];
        if ($cid > 0) {
            $courseIds[$cid] = $cid;
            $cohortsByCourse[$cid][] = $en['cohort_id'];
        }
    }

    if (!empty($courseIds)) {
        $courseIdParams = array_values($courseIds);
        $placeholders = implode(',', array_fill(0, count($courseIdParams), '?'));

        $potentialCommunities = $db->getAll(
            "SELECT * FROM communities WHERE status = 'active' AND course_id IN ($placeholders)",
            $courseIdParams
        );

        foreach ($potentialCommunities as $comm) {
            $commId = (int)$comm['id'];
            $cid = (int)$comm['course_id'];
            $visibility = $comm['visibility'] ?? 'course';
            $shouldJoin = false;

            if ($visibility === 'course' || $visibility === 'public') {
                $shouldJoin = true;
            } elseif ($visibility === 'cohort') {
                $communityCohortId = $comm['cohort_id'] !== null ? (int)$comm['cohort_id'] : 0;
                if ($communityCohortId && isset($cohortsByCourse[$cid])) {
                    foreach ($cohortsByCourse[$cid] as $enCohortId) {
                        if ((int)$enCohortId === $communityCohortId) {
                            $shouldJoin = true;
                            break;
                        }
                    }
                }
            }

            if (!$shouldJoin) {
                continue;
            }

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

            if (!$member) {
                $db->insert('community_members', [
                    'community_id' => $commId,
                    'user_id' => $userId,
                    'role' => 'member',
                    'status' => 'active',
                    'joined_at' => formatDate(),
                ]);
            }
        }
    }

    // Now load communities where the student is an active member
    $communities = $db->getAll(
        'SELECT c.*, cm.role AS member_role, crs.title AS course_title
         FROM communities c
         JOIN community_members cm ON cm.community_id = c.id
         JOIN courses crs ON c.course_id = crs.id
         WHERE cm.user_id = ? AND cm.status = "active" AND c.status = "active"
         ORDER BY c.created_at DESC',
        [$userId]
    );
} else {
    // Admin/regional_admin: show all communities
    if (in_array($role, ['admin', 'super_admin', 'regional_admin'], true)) {
        $communities = $db->getAll(
            'SELECT c.*, crs.title AS course_title,
                    (SELECT COUNT(*) FROM community_members cm WHERE cm.community_id = c.id AND cm.status = "active") AS member_count
             FROM communities c
             JOIN courses crs ON c.course_id = crs.id
             ORDER BY c.created_at DESC'
        );
    }
}

$pageTitle = 'Communities';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h4 mb-0">Communities</h1>
        <?php if ($role === 'instructor'): ?>
            <p class="text-muted mb-0">Create and manage communities for your courses.</p>
        <?php elseif ($role === 'student'): ?>
            <p class="text-muted mb-0">Collaborate with peers in your course communities.</p>
        <?php else: ?>
            <p class="text-muted mb-0">Browse and manage course communities.</p>
        <?php endif; ?>
    </div>
</div>

<?php if ($role === 'instructor' && !empty($courses)): ?>
<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-3">Create New Community</h5>
        <form method="post" class="row g-3">
            <input type="hidden" name="action" value="create_community" />
            <div class="col-md-4">
                <label class="form-label">Course</label>
                <select name="course_id" class="form-select" required>
                    <option value="">Select course...</option>
                    <?php foreach ($courses as $c): ?>
                        <option value="<?php echo (int)$c['id']; ?>"><?php echo htmlspecialchars($c['title']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">Community Title (optional)</label>
                <input type="text" name="title" class="form-control" placeholder="e.g. <?php echo htmlspecialchars(APP_NAME); ?> Cohort Community" />
            </div>
            <div class="col-md-12">
                <label class="form-label">Description (optional)</label>
                <textarea name="description" class="form-control" rows="2" placeholder="Short description of this community..."></textarea>
            </div>
            <div class="col-12 text-end">
                <button type="submit" class="btn btn-primary">Create Community</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <?php if (empty($communities)): ?>
            <p class="text-muted mb-0">No communities found.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Community</th>
                            <th>Course</th>
                            <?php if ($role !== 'student'): ?>
                                <th>Members</th>
                            <?php endif; ?>
                            <th>Created</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($communities as $comm): ?>
                            <tr>
                                <td>
                                    <div class="fw-semibold mb-0"><?php echo htmlspecialchars($comm['title']); ?></div>
                                    <?php if (!empty($comm['description'])): ?>
                                        <div class="text-muted small text-truncate" style="max-width: 320px;">
                                            <?php echo htmlspecialchars($comm['description']); ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($comm['course_title'] ?? ''); ?></td>
                                <?php if ($role !== 'student'): ?>
                                    <td>
                                        <?php
                                            $memberCount = isset($comm['member_count']) ? (int)$comm['member_count'] : null;
                                            if ($memberCount === null && isset($comm['id'])) {
                                                $cntRow = $db->get('SELECT COUNT(*) AS cnt FROM community_members WHERE community_id = ? AND status = "active"', [(int)$comm['id']]);
                                                $memberCount = (int)($cntRow['cnt'] ?? 0);
                                            }
                                        ?>
                                        <span class="badge bg-label-primary"><?php echo $memberCount; ?> members</span>
                                    </td>
                                <?php endif; ?>
                                <td>
                                    <?php
                                        $createdAt = $comm['created_at'] ?? '';
                                        echo $createdAt ? htmlspecialchars(date('Y-m-d H:i', strtotime($createdAt))) : '';
                                    ?>
                                </td>
                                <td class="text-end">
                                    <a href="<?php echo APP_URL; ?>/lms/community_view.php?id=<?php echo (int)$comm['id']; ?>" class="btn btn-sm btn-outline-primary">Open</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

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