<?php
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

if ($method === 'POST') {
    if (!isset($input['invite_code']) || !isset($input['user_id'])) {
        jsonResponse(['error' => 'Missing required fields'], 400);
    }
    
    $pdo = getDB();
    
    $stmt = $pdo->prepare("SELECT id FROM groups_table WHERE invite_code = ?");
    $stmt->execute([$input['invite_code']]);
    $group = $stmt->fetch();
    
    if (!$group) {
        jsonResponse(['error' => 'Invalid invite code'], 404);
    }
    
    $stmt = $pdo->prepare("SELECT * FROM group_members WHERE group_id = ? AND user_id = ?");
    $stmt->execute([$group['id'], $input['user_id']]);
    
    if ($stmt->fetch()) {
        jsonResponse(['error' => 'Already a member'], 409);
    }
    
    $stmt = $pdo->prepare("INSERT INTO group_members (group_id, user_id) VALUES (?, ?)");
    $stmt->execute([$group['id'], $input['user_id']]);
    
    jsonResponse(['success' => true, 'message' => 'Joined group successfully'], 201);
}
?>