<?php
require_once __DIR__ . '/connect_common.php';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') connect_json(204);
$user = connect_user($pdo);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$userId = (int)($user['id'] ?? 0);

try {
    if ($method === 'GET') {
        $communityId = (int)($_GET['community_id'] ?? 0);
        if ($communityId <= 0) connect_json(400, ['detail' => 'community_id is required.']);
        $stmt = $pdo->prepare("SELECT user_id, user_name, user_email, role, joined_at
                              FROM connect_community_members
                              WHERE community_id = ?
                              ORDER BY CASE WHEN role = 'admin' THEN 0 ELSE 1 END, joined_at ASC");
        $stmt->execute([$communityId]);
        connect_json(200, ['data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    }

    if ($method !== 'POST') connect_json(405, ['detail' => 'Only GET and POST are supported for community membership.']);
    $body = connect_body();
    $communityId = (int)($body['community_id'] ?? 0);
    $action = strtolower(connect_text($body['action'] ?? 'join', 20));
    if ($communityId <= 0) connect_json(400, ['detail' => 'A valid community is required.']);
    if (!in_array($action, ['join', 'leave'], true)) connect_json(400, ['detail' => 'Invalid membership action.']);

    $communityStmt = $pdo->prepare('SELECT * FROM connect_communities WHERE id = ? AND is_active = TRUE');
    $communityStmt->execute([$communityId]);
    $community = $communityStmt->fetch(PDO::FETCH_ASSOC);
    if (!$community) connect_json(404, ['detail' => 'Community not found.']);

    if ($action === 'join') {
        $stmt = $pdo->prepare("INSERT INTO connect_community_members
            (community_id, user_id, user_name, user_email, role)
            VALUES (?, ?, ?, ?, 'member')
            ON CONFLICT (community_id, user_id) DO NOTHING");
        $stmt->execute([
            $communityId,
            $userId,
            connect_text($user['full_name'] ?? $user['name'] ?? 'Rockview User', 255),
            connect_text($user['email'] ?? '', 255),
        ]);
        $inserted = $stmt->rowCount() > 0;
        $isMember = true;

        if ($inserted) {
            connect_notify(
                $pdo,
                (int)($community['creator_id'] ?? 0),
                connect_text($community['creator_email'] ?? '', 255),
                $user,
                'community_join',
                'New community member',
                connect_text($user['full_name'] ?? 'A staff member', 120) . ' joined ' . connect_text($community['name'] ?? 'your community', 120) . '.',
                null,
                null,
                $communityId,
                'community-join:' . $communityId . ':' . $userId
            );
        }
    } else {
        if ((int)$community['creator_id'] === $userId) {
            connect_json(409, ['detail' => 'The community creator cannot leave the community.']);
        }
        $stmt = $pdo->prepare('DELETE FROM connect_community_members WHERE community_id = ? AND user_id = ?');
        $stmt->execute([$communityId, $userId]);
        connect_delete_notification_by_key($pdo, (int)$community['creator_id'], 'community-join:' . $communityId . ':' . $userId);
        $isMember = false;
    }

    $countStmt = $pdo->prepare('SELECT COUNT(*) FROM connect_community_members WHERE community_id = ?');
    $countStmt->execute([$communityId]);
    connect_json(200, [
        'is_member' => $isMember,
        'members_count' => (int)$countStmt->fetchColumn(),
    ]);
} catch (Throwable $e) {
    connect_json(500, ['detail' => 'Community membership service error: ' . $e->getMessage()]);
}
