<?php
require_once 'config.php';

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

if ($method === 'POST') {
    if (!isset($input['name']) || !isset($input['owner_id'])) {
        jsonResponse(['error' => 'Missing required fields'], 400);
    }
    
    $pdo = getDB();
    $inviteCode = generateInviteCode();
    
    $stmt = $pdo->prepare("INSERT INTO groups_table (name, invite_code, owner_id) VALUES (?, ?, ?)");
    $stmt->execute([$input['name'], $inviteCode, $input['owner_id']]);
    
    $groupId = $pdo->lastInsertId();
    
    $stmt = $pdo->prepare("INSERT INTO group_members (group_id, user_id) VALUES (?, ?)");
    $stmt->execute([$groupId, $input['owner_id']]);
    
    jsonResponse(['success' => true, 'group_id' => $groupId, 'invite_code' => $inviteCode], 201);
}

if ($method === 'PUT') {
    if (!isset($input['group_id'])) {
        jsonResponse(['error' => 'Group ID required'], 400);
    }
    
    $pdo = getDB();
    $fields = [];
    $values = [];
    
    if (isset($input['club_name'])) {
        $fields[] = 'club_name = ?';
        $values[] = $input['club_name'];
    }
    if (isset($input['club_logo'])) {
        $fields[] = 'club_logo = ?';
        $values[] = $input['club_logo'];
    }
    
    if (empty($fields)) {
        jsonResponse(['error' => 'No fields to update'], 400);
    }
    
    $values[] = $input['group_id'];
    $sql = "UPDATE groups_table SET " . implode(', ', $fields) . " WHERE id = ?";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($values);
    
    jsonResponse(['success' => true, 'message' => 'Group updated']);
}

if ($method === 'GET') {
    if (isset($_GET['invite_code'])) {
        $pdo = getDB();
        $stmt = $pdo->prepare("SELECT * FROM groups_table WHERE invite_code = ?");
        $stmt->execute([$_GET['invite_code']]);
        $group = $stmt->fetch();
        
        if ($group) {
            jsonResponse(['success' => true, 'group' => $group]);
        } else {
            jsonResponse(['error' => 'Group not found'], 404);
        }
    } elseif (isset($_GET['user_id'])) {
        $pdo = getDB();
        $stmt = $pdo->prepare("SELECT g.* FROM groups_table g INNER JOIN group_members gm ON g.id = gm.group_id WHERE gm.user_id = ?");
        $stmt->execute([$_GET['user_id']]);
        $groups = $stmt->fetchAll();
        
        jsonResponse(['success' => true, 'groups' => $groups]);
    } else {
        jsonResponse(['error' => 'Missing parameters'], 400);
    }
}
?>